file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
script.js
const currentDate = () => new Date(); const xmasDay = () => new Date(2021, 12, 25); const newYear = () => new Date(2022, 01, 01); const valentinesDay = () => new Date(2022, 02, 14); const MILLISECONDSINDAY = () => 24 * 3600 * 1000;
const calcDaysUntilNewYear = () => { return parseInt((newYear() - currentDate()) / MILLISECONDSINDAY()); }; const calcDaysUntilValentinesDay = () => { return parseInt((valentinesDay() - currentDate()) / MILLISECONDSINDAY()); }; const printDaysUntilXmas = () => { return `<li> ${calcDaysUntilXmas().toString()} days until Christmas</li>`; }; const printDaysUntilNewYear = () => { return `<li> ${calcDaysUntilNewYear().toString()} days until New Year</li>`; }; const printDaysUntilValentines = () => { return `<li> ${calcDaysUntilValentinesDay().toString()} days until Valentines Day</li>`; }; const printDaysUntilAllHolidays = () => printDaysUntilXmas() + printDaysUntilNewYear() + printDaysUntilValentines(); $("#trigger").click(() => { $("#days-until").append($(printDaysUntilAllHolidays())); });
const calcDaysUntilXmas = () => { return parseInt((xmasDay() - currentDate()) / MILLISECONDSINDAY()); };
TaskPage.tsx
/* * Copyright 2021 The Backstage Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { parseEntityRef } from '@backstage/catalog-model'; import { Content, ErrorPage, Header, Lifecycle, Page, LogViewer, Progress, } from '@backstage/core-components'; import { useRouteRef } from '@backstage/core-plugin-api'; import { BackstageTheme } from '@backstage/theme'; import { Button, CircularProgress, Paper, StepButton, StepIconProps, } from '@material-ui/core'; import Grid from '@material-ui/core/Grid'; import Step from '@material-ui/core/Step'; import StepLabel from '@material-ui/core/StepLabel'; import Stepper from '@material-ui/core/Stepper'; import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import Cancel from '@material-ui/icons/Cancel'; import Check from '@material-ui/icons/Check'; import FiberManualRecordIcon from '@material-ui/icons/FiberManualRecord'; import classNames from 'classnames'; import { DateTime, Interval } from 'luxon'; import qs from 'qs'; import React, { memo, useEffect, useMemo, useState } from 'react'; import { useNavigate, useParams } from 'react-router'; import useInterval from 'react-use/lib/useInterval'; import { rootRouteRef, selectedTemplateRouteRef } from '../../routes'; import { ScaffolderTaskStatus, ScaffolderTaskOutput } from '../../types'; import { useTaskEventStream } from '../hooks/useEventStream'; import { TaskPageLinks } from './TaskPageLinks'; // typings are wrong for this library, so fallback to not parsing types. const humanizeDuration = require('humanize-duration'); const useStyles = makeStyles((theme: Theme) => createStyles({ root: { width: '100%', }, button: { marginBottom: theme.spacing(2), marginLeft: theme.spacing(2), }, actionsContainer: { marginBottom: theme.spacing(2), }, resetContainer: { padding: theme.spacing(3), }, labelWrapper: { display: 'flex', flex: 1, flexDirection: 'row', justifyContent: 'space-between', }, stepWrapper: { width: '100%', }, }), ); type TaskStep = { id: string; name: string; status: ScaffolderTaskStatus; startedAt?: string; endedAt?: string; }; const StepTimeTicker = ({ step }: { step: TaskStep }) => { const [time, setTime] = useState(''); useInterval(() => { if (!step.startedAt) { setTime(''); return; } const end = step.endedAt ? DateTime.fromISO(step.endedAt) : DateTime.local(); const startedAt = DateTime.fromISO(step.startedAt); const formatted = Interval.fromDateTimes(startedAt, end) .toDuration() .valueOf(); setTime(humanizeDuration(formatted, { round: true })); }, 1000); return <Typography variant="caption">{time}</Typography>; }; const useStepIconStyles = makeStyles((theme: BackstageTheme) => createStyles({ root: { color: theme.palette.text.disabled, display: 'flex', height: 22, alignItems: 'center', }, completed: { color: theme.palette.status.ok, }, error: { color: theme.palette.status.error, }, }), ); function TaskStepIconComponent(props: StepIconProps) { const classes = useStepIconStyles(); const { active, completed, error } = props; const getMiddle = () => { if (active) { return <CircularProgress size="24px" />; } if (completed) { return <Check />; } if (error) { return <Cancel />; } return <FiberManualRecordIcon />; }; return ( <div className={classNames(classes.root, { [classes.completed]: completed, [classes.error]: error, })} > {getMiddle()} </div> ); } export const TaskStatusStepper = memo( ({ steps, currentStepId, onUserStepChange, }: { steps: TaskStep[]; currentStepId: string | undefined; onUserStepChange: (id: string) => void; }) => { const classes = useStyles(); return ( <div className={classes.root}> <Stepper activeStep={steps.findIndex(s => s.id === currentStepId)} orientation="vertical" nonLinear > {steps.map((step, index) => { const isCompleted = step.status === 'completed'; const isFailed = step.status === 'failed'; const isActive = step.status === 'processing'; const isSkipped = step.status === 'skipped'; return ( <Step key={String(index)} expanded> <StepButton onClick={() => onUserStepChange(step.id)}> <StepLabel StepIconProps={{ completed: isCompleted, error: isFailed, active: isActive, }} StepIconComponent={TaskStepIconComponent} className={classes.stepWrapper} > <div className={classes.labelWrapper}> <Typography variant="subtitle2">{step.name}</Typography> {isSkipped ? ( <Typography variant="caption">Skipped</Typography> ) : ( <StepTimeTicker step={step} /> )} </div> </StepLabel> </StepButton> </Step> ); })} </Stepper> </div> ); }, ); const hasLinks = ({ links = [] }: ScaffolderTaskOutput): boolean => links.length > 0; /** * TaskPageProps for constructing a TaskPage * @param loadingText - Optional loading text shown before a task begins executing. * * @public */ export type TaskPageProps = { loadingText?: string; }; /** * TaskPage for showing the status of the taskId provided as a param * @param loadingText - Optional loading text shown before a task begins executing. * * @public */ export const TaskPage = ({ loadingText }: TaskPageProps) => { const classes = useStyles(); const navigate = useNavigate(); const rootPath = useRouteRef(rootRouteRef); const templateRoute = useRouteRef(selectedTemplateRouteRef); const [userSelectedStepId, setUserSelectedStepId] = useState< string | undefined >(undefined); const [lastActiveStepId, setLastActiveStepId] = useState<string | undefined>(
const completed = taskStream.completed; const steps = useMemo( () => taskStream.task?.spec.steps.map(step => ({ ...step, ...taskStream?.steps?.[step.id], })) ?? [], [taskStream], ); useEffect(() => { const mostRecentFailedOrActiveStep = steps.find(step => ['failed', 'processing'].includes(step.status), ); if (completed && !mostRecentFailedOrActiveStep) { setLastActiveStepId(steps[steps.length - 1]?.id); return; } setLastActiveStepId(mostRecentFailedOrActiveStep?.id); }, [steps, completed]); const currentStepId = userSelectedStepId ?? lastActiveStepId; const logAsString = useMemo(() => { if (!currentStepId) { return loadingText ? loadingText : 'Loading...'; } const log = taskStream.stepLogs[currentStepId]; if (!log?.length) { return 'Waiting for logs...'; } return log.join('\n'); }, [taskStream.stepLogs, currentStepId, loadingText]); const taskNotFound = taskStream.completed === true && taskStream.loading === false && !taskStream.task; const { output } = taskStream; const handleStartOver = () => { if (!taskStream.task || !taskStream.task?.spec.templateInfo?.entityRef) { navigate(rootPath()); return; } const formData = taskStream.task!.spec.parameters; const { name } = parseEntityRef( taskStream.task!.spec.templateInfo?.entityRef, ); navigate( `${templateRoute({ templateName: name })}?${qs.stringify({ formData: JSON.stringify(formData), })}`, ); }; return ( <Page themeId="home"> <Header pageTitleOverride={`Task ${taskId}`} title={ <> Task Activity <Lifecycle alpha shorthand /> </> } subtitle={`Activity for task: ${taskId}`} /> <Content> {taskNotFound ? ( <ErrorPage status="404" statusMessage="Task not found" additionalInfo="No task found with this ID" /> ) : ( <div> <Grid container> <Grid item xs={3}> <Paper> <TaskStatusStepper steps={steps} currentStepId={currentStepId} onUserStepChange={setUserSelectedStepId} /> {output && hasLinks(output) && ( <TaskPageLinks output={output} /> )} <Button className={classes.button} onClick={handleStartOver} disabled={!completed} variant="contained" color="primary" > Start Over </Button> </Paper> </Grid> <Grid item xs={9}> {!currentStepId && <Progress />} <div style={{ height: '80vh' }}> <LogViewer text={logAsString} /> </div> </Grid> </Grid> </div> )} </Content> </Page> ); };
undefined, ); const { taskId } = useParams(); const taskStream = useTaskEventStream(taskId);
daemonset_test.go
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package daemonset import ( "fmt" "net/http/httptest" "testing" "time" apps "k8s.io/api/apps/v1" "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/uuid" "k8s.io/apimachinery/pkg/util/wait" utilfeature "k8s.io/apiserver/pkg/util/feature" utilfeaturetesting "k8s.io/apiserver/pkg/util/feature/testing" "k8s.io/client-go/informers" clientset "k8s.io/client-go/kubernetes" appstyped "k8s.io/client-go/kubernetes/typed/apps/v1" clientv1core "k8s.io/client-go/kubernetes/typed/core/v1" corev1typed "k8s.io/client-go/kubernetes/typed/core/v1" restclient "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/record" "k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/retry" "k8s.io/kubernetes/pkg/api/legacyscheme" podutil "k8s.io/kubernetes/pkg/api/v1/pod" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/daemon" "k8s.io/kubernetes/pkg/features" "k8s.io/kubernetes/pkg/scheduler" "k8s.io/kubernetes/pkg/scheduler/algorithmprovider" _ "k8s.io/kubernetes/pkg/scheduler/algorithmprovider" schedulerapi "k8s.io/kubernetes/pkg/scheduler/api" "k8s.io/kubernetes/pkg/scheduler/factory" labelsutil "k8s.io/kubernetes/pkg/util/labels" "k8s.io/kubernetes/test/integration/framework" ) var zero = int64(0) func setup(t *testing.T) (*httptest.Server, framework.CloseFunc, *daemon.DaemonSetsController, informers.SharedInformerFactory, clientset.Interface) { masterConfig := framework.NewIntegrationTestMasterConfig() _, server, closeFn := framework.RunAMaster(masterConfig) config := restclient.Config{Host: server.URL} clientSet, err := clientset.NewForConfig(&config) if err != nil { t.Fatalf("Error in creating clientset: %v", err) } resyncPeriod := 12 * time.Hour informers := informers.NewSharedInformerFactory(clientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "daemonset-informers")), resyncPeriod) dc, err := daemon.NewDaemonSetsController( informers.Apps().V1().DaemonSets(), informers.Apps().V1().ControllerRevisions(), informers.Core().V1().Pods(), informers.Core().V1().Nodes(), clientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "daemonset-controller")), flowcontrol.NewBackOff(5*time.Second, 15*time.Minute), ) if err != nil { t.Fatalf("error creating DaemonSets controller: %v", err) } return server, closeFn, dc, informers, clientSet } func setupScheduler( t *testing.T, cs clientset.Interface, informerFactory informers.SharedInformerFactory, stopCh chan struct{}, ) { // If ScheduleDaemonSetPods is disabled, do not start scheduler. if !utilfeature.DefaultFeatureGate.Enabled(features.ScheduleDaemonSetPods) { return } // Enable Features. algorithmprovider.ApplyFeatureGates() schedulerConfigFactory := factory.NewConfigFactory(&factory.ConfigFactoryArgs{ SchedulerName: v1.DefaultSchedulerName, Client: cs, NodeInformer: informerFactory.Core().V1().Nodes(), PodInformer: informerFactory.Core().V1().Pods(), PvInformer: informerFactory.Core().V1().PersistentVolumes(), PvcInformer: informerFactory.Core().V1().PersistentVolumeClaims(), ReplicationControllerInformer: informerFactory.Core().V1().ReplicationControllers(), ReplicaSetInformer: informerFactory.Apps().V1().ReplicaSets(), StatefulSetInformer: informerFactory.Apps().V1().StatefulSets(), ServiceInformer: informerFactory.Core().V1().Services(), PdbInformer: informerFactory.Policy().V1beta1().PodDisruptionBudgets(), StorageClassInformer: informerFactory.Storage().V1().StorageClasses(), HardPodAffinitySymmetricWeight: v1.DefaultHardPodAffinitySymmetricWeight, EnableEquivalenceClassCache: false, DisablePreemption: false, PercentageOfNodesToScore: 100, }) schedulerConfig, err := schedulerConfigFactory.Create() if err != nil { t.Fatalf("Couldn't create scheduler config: %v", err) } schedulerConfig.StopEverything = stopCh eventBroadcaster := record.NewBroadcaster() schedulerConfig.Recorder = eventBroadcaster.NewRecorder( legacyscheme.Scheme, v1.EventSource{Component: v1.DefaultSchedulerName}, ) eventBroadcaster.StartRecordingToSink(&clientv1core.EventSinkImpl{ Interface: cs.CoreV1().Events(""), }) sched, err := scheduler.NewFromConfigurator( &scheduler.FakeConfigurator{Config: schedulerConfig}, nil...) if err != nil { t.Fatalf("error creating scheduler: %v", err) } algorithmprovider.ApplyFeatureGates() go sched.Run() } func testLabels() map[string]string { return map[string]string{"name": "test"} } func newDaemonSet(name, namespace string) *apps.DaemonSet { two := int32(2) return &apps.DaemonSet{ TypeMeta: metav1.TypeMeta{ Kind: "DaemonSet", APIVersion: "apps/v1", }, ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, Name: name, }, Spec: apps.DaemonSetSpec{ RevisionHistoryLimit: &two, Selector: &metav1.LabelSelector{MatchLabels: testLabels()}, UpdateStrategy: apps.DaemonSetUpdateStrategy{ Type: apps.OnDeleteDaemonSetStrategyType, }, Template: v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: testLabels(), }, Spec: v1.PodSpec{ Containers: []v1.Container{{Name: "foo", Image: "bar"}}, TerminationGracePeriodSeconds: &zero, }, }, }, } } func cleanupDaemonSets(t *testing.T, cs clientset.Interface, ds *apps.DaemonSet) { ds, err := cs.AppsV1().DaemonSets(ds.Namespace).Get(ds.Name, metav1.GetOptions{}) if err != nil { t.Errorf("Failed to get DaemonSet %s/%s: %v", ds.Namespace, ds.Name, err) return } // We set the nodeSelector to a random label. This label is nearly guaranteed // to not be set on any node so the DameonSetController will start deleting // daemon pods. Once it's done deleting the daemon pods, it's safe to delete // the DaemonSet. ds.Spec.Template.Spec.NodeSelector = map[string]string{ string(uuid.NewUUID()): string(uuid.NewUUID()), } // force update to avoid version conflict ds.ResourceVersion = "" if ds, err = cs.AppsV1().DaemonSets(ds.Namespace).Update(ds); err != nil { t.Errorf("Failed to update DaemonSet %s/%s: %v", ds.Namespace, ds.Name, err) return } // Wait for the daemon set controller to kill all the daemon pods. if err := wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) { updatedDS, err := cs.AppsV1().DaemonSets(ds.Namespace).Get(ds.Name, metav1.GetOptions{}) if err != nil { return false, nil } return updatedDS.Status.CurrentNumberScheduled+updatedDS.Status.NumberMisscheduled == 0, nil }); err != nil { t.Errorf("Failed to kill the pods of DaemonSet %s/%s: %v", ds.Namespace, ds.Name, err) return } falseVar := false deleteOptions := &metav1.DeleteOptions{OrphanDependents: &falseVar} if err := cs.AppsV1().DaemonSets(ds.Namespace).Delete(ds.Name, deleteOptions); err != nil { t.Errorf("Failed to delete DaemonSet %s/%s: %v", ds.Namespace, ds.Name, err) } } func newRollbackStrategy() *apps.DaemonSetUpdateStrategy { one := intstr.FromInt(1) return &apps.DaemonSetUpdateStrategy{ Type: apps.RollingUpdateDaemonSetStrategyType, RollingUpdate: &apps.RollingUpdateDaemonSet{MaxUnavailable: &one}, } } func newOnDeleteStrategy() *apps.DaemonSetUpdateStrategy { return &apps.DaemonSetUpdateStrategy{ Type: apps.OnDeleteDaemonSetStrategyType, } } func updateStrategies() []*apps.DaemonSetUpdateStrategy { return []*apps.DaemonSetUpdateStrategy{newOnDeleteStrategy(), newRollbackStrategy()} } func featureGates() []utilfeature.Feature { return []utilfeature.Feature{ features.ScheduleDaemonSetPods, } } func allocatableResources(memory, cpu string) v1.ResourceList { return v1.ResourceList{ v1.ResourceMemory: resource.MustParse(memory), v1.ResourceCPU: resource.MustParse(cpu), v1.ResourcePods: resource.MustParse("100"), } } func resourcePodSpec(nodeName, memory, cpu string) v1.PodSpec { return v1.PodSpec{ NodeName: nodeName, Containers: []v1.Container{ { Name: "foo", Image: "bar", Resources: v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceMemory: resource.MustParse(memory), v1.ResourceCPU: resource.MustParse(cpu), }, }, }, }, TerminationGracePeriodSeconds: &zero, } } func newNode(name string, label map[string]string) *v1.Node { return &v1.Node{ TypeMeta: metav1.TypeMeta{ Kind: "Node", APIVersion: "v1", }, ObjectMeta: metav1.ObjectMeta{ Name: name, Labels: label, Namespace: metav1.NamespaceDefault, }, Status: v1.NodeStatus{ Conditions: []v1.NodeCondition{{Type: v1.NodeReady, Status: v1.ConditionTrue}}, Allocatable: v1.ResourceList{v1.ResourcePods: resource.MustParse("100")}, }, } } func addNodes(nodeClient corev1typed.NodeInterface, startIndex, numNodes int, label map[string]string, t *testing.T) { for i := startIndex; i < startIndex+numNodes; i++ { _, err := nodeClient.Create(newNode(fmt.Sprintf("node-%d", i), label)) if err != nil { t.Fatalf("Failed to create node: %v", err) } } } func validateDaemonSetPodsAndMarkReady( podClient corev1typed.PodInterface, podInformer cache.SharedIndexInformer, numberPods int, t *testing.T, ) { if err := wait.Poll(10*time.Second, 60*time.Second, func() (bool, error) { objects := podInformer.GetIndexer().List() if len(objects) != numberPods { return false, nil } for _, object := range objects { pod := object.(*v1.Pod) ownerReferences := pod.ObjectMeta.OwnerReferences if len(ownerReferences) != 1 { return false, fmt.Errorf("Pod %s has %d OwnerReferences, expected only 1", pod.Name, len(ownerReferences)) } controllerRef := ownerReferences[0] if got, want := controllerRef.Kind, "DaemonSet"; got != want { t.Errorf("controllerRef.Kind = %q, want %q", got, want) } if controllerRef.Controller == nil || *controllerRef.Controller != true { t.Errorf("controllerRef.Controller is not set to true") } if !podutil.IsPodReady(pod) && len(pod.Spec.NodeName) != 0 { podCopy := pod.DeepCopy() podCopy.Status = v1.PodStatus{ Phase: v1.PodRunning, Conditions: []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue}},
_, err := podClient.UpdateStatus(podCopy) if err != nil { return false, err } } } return true, nil }); err != nil { t.Fatal(err) } } // podUnschedulable returns a condition function that returns true if the given pod // gets unschedulable status. func podUnschedulable(c clientset.Interface, podNamespace, podName string) wait.ConditionFunc { return func() (bool, error) { pod, err := c.CoreV1().Pods(podNamespace).Get(podName, metav1.GetOptions{}) if errors.IsNotFound(err) { return false, nil } if err != nil { // This could be a connection error so we want to retry. return false, nil } _, cond := podutil.GetPodCondition(&pod.Status, v1.PodScheduled) return cond != nil && cond.Status == v1.ConditionFalse && cond.Reason == v1.PodReasonUnschedulable, nil } } // waitForPodUnscheduleWithTimeout waits for a pod to fail scheduling and returns // an error if it does not become unschedulable within the given timeout. func waitForPodUnschedulableWithTimeout(cs clientset.Interface, pod *v1.Pod, timeout time.Duration) error { return wait.Poll(100*time.Millisecond, timeout, podUnschedulable(cs, pod.Namespace, pod.Name)) } // waitForPodUnschedule waits for a pod to fail scheduling and returns // an error if it does not become unschedulable within the timeout duration (30 seconds). func waitForPodUnschedulable(cs clientset.Interface, pod *v1.Pod) error { return waitForPodUnschedulableWithTimeout(cs, pod, 10*time.Second) } // waitForPodsCreated waits for number of pods are created. func waitForPodsCreated(podInformer cache.SharedIndexInformer, num int) error { return wait.Poll(100*time.Millisecond, 10*time.Second, func() (bool, error) { objects := podInformer.GetIndexer().List() return len(objects) == num, nil }) } func waitForDaemonSetAndControllerRevisionCreated(c clientset.Interface, name string, namespace string) error { return wait.PollImmediate(100*time.Millisecond, 10*time.Second, func() (bool, error) { ds, err := c.AppsV1().DaemonSets(namespace).Get(name, metav1.GetOptions{}) if err != nil { return false, err } if ds == nil { return false, nil } revs, err := c.AppsV1().ControllerRevisions(namespace).List(metav1.ListOptions{}) if err != nil { return false, err } if revs.Size() == 0 { return false, nil } for _, rev := range revs.Items { for _, oref := range rev.OwnerReferences { if oref.Kind == "DaemonSet" && oref.UID == ds.UID { return true, nil } } } return false, nil }) } func hashAndNameForDaemonSet(ds *apps.DaemonSet) (string, string) { hash := fmt.Sprint(controller.ComputeHash(&ds.Spec.Template, ds.Status.CollisionCount)) name := ds.Name + "-" + hash return hash, name } func validateDaemonSetCollisionCount(dsClient appstyped.DaemonSetInterface, dsName string, expCount int32, t *testing.T) { ds, err := dsClient.Get(dsName, metav1.GetOptions{}) if err != nil { t.Fatalf("Failed to look up DaemonSet: %v", err) } collisionCount := ds.Status.CollisionCount if *collisionCount != expCount { t.Fatalf("Expected collisionCount to be %d, but found %d", expCount, *collisionCount) } } func validateDaemonSetStatus( dsClient appstyped.DaemonSetInterface, dsName string, expectedNumberReady int32, t *testing.T) { if err := wait.Poll(5*time.Second, 60*time.Second, func() (bool, error) { ds, err := dsClient.Get(dsName, metav1.GetOptions{}) if err != nil { return false, err } return ds.Status.NumberReady == expectedNumberReady, nil }); err != nil { t.Fatal(err) } } func validateFailedPlacementEvent(eventClient corev1typed.EventInterface, t *testing.T) { if err := wait.Poll(5*time.Second, 60*time.Second, func() (bool, error) { eventList, err := eventClient.List(metav1.ListOptions{}) if err != nil { return false, err } if len(eventList.Items) == 0 { return false, nil } if len(eventList.Items) > 1 { t.Errorf("Expected 1 event got %d", len(eventList.Items)) } event := eventList.Items[0] if event.Type != v1.EventTypeWarning { t.Errorf("Event type expected %s got %s", v1.EventTypeWarning, event.Type) } if event.Reason != daemon.FailedPlacementReason { t.Errorf("Event reason expected %s got %s", daemon.FailedPlacementReason, event.Reason) } return true, nil }); err != nil { t.Fatal(err) } } func updateDS(t *testing.T, dsClient appstyped.DaemonSetInterface, dsName string, updateFunc func(*apps.DaemonSet)) *apps.DaemonSet { var ds *apps.DaemonSet if err := retry.RetryOnConflict(retry.DefaultBackoff, func() error { newDS, err := dsClient.Get(dsName, metav1.GetOptions{}) if err != nil { return err } updateFunc(newDS) ds, err = dsClient.Update(newDS) return err }); err != nil { t.Fatalf("Failed to update DaemonSet: %v", err) } return ds } func forEachFeatureGate(t *testing.T, tf func(t *testing.T)) { for _, fg := range featureGates() { for _, f := range []bool{true, false} { func() { defer utilfeaturetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, fg, f)() t.Run(fmt.Sprintf("%v (%t)", fg, f), tf) }() } } } func forEachStrategy(t *testing.T, tf func(t *testing.T, strategy *apps.DaemonSetUpdateStrategy)) { for _, strategy := range updateStrategies() { t.Run(fmt.Sprintf("%s (%v)", t.Name(), strategy), func(tt *testing.T) { tf(tt, strategy) }) } } func TestOneNodeDaemonLaunchesPod(t *testing.T) { forEachFeatureGate(t, func(t *testing.T) { forEachStrategy(t, func(t *testing.T, strategy *apps.DaemonSetUpdateStrategy) { server, closeFn, dc, informers, clientset := setup(t) defer closeFn() ns := framework.CreateTestingNamespace("one-node-daemonset-test", server, t) defer framework.DeleteTestingNamespace(ns, server, t) dsClient := clientset.AppsV1().DaemonSets(ns.Name) podClient := clientset.CoreV1().Pods(ns.Name) nodeClient := clientset.CoreV1().Nodes() podInformer := informers.Core().V1().Pods().Informer() stopCh := make(chan struct{}) defer close(stopCh) informers.Start(stopCh) go dc.Run(5, stopCh) // Start Scheduler setupScheduler(t, clientset, informers, stopCh) ds := newDaemonSet("foo", ns.Name) ds.Spec.UpdateStrategy = *strategy _, err := dsClient.Create(ds) if err != nil { t.Fatalf("Failed to create DaemonSet: %v", err) } defer cleanupDaemonSets(t, clientset, ds) _, err = nodeClient.Create(newNode("single-node", nil)) if err != nil { t.Fatalf("Failed to create node: %v", err) } validateDaemonSetPodsAndMarkReady(podClient, podInformer, 1, t) validateDaemonSetStatus(dsClient, ds.Name, 1, t) }) }) } func TestSimpleDaemonSetLaunchesPods(t *testing.T) { forEachFeatureGate(t, func(t *testing.T) { forEachStrategy(t, func(t *testing.T, strategy *apps.DaemonSetUpdateStrategy) { server, closeFn, dc, informers, clientset := setup(t) defer closeFn() ns := framework.CreateTestingNamespace("simple-daemonset-test", server, t) defer framework.DeleteTestingNamespace(ns, server, t) dsClient := clientset.AppsV1().DaemonSets(ns.Name) podClient := clientset.CoreV1().Pods(ns.Name) nodeClient := clientset.CoreV1().Nodes() podInformer := informers.Core().V1().Pods().Informer() stopCh := make(chan struct{}) defer close(stopCh) informers.Start(stopCh) go dc.Run(5, stopCh) // Start Scheduler setupScheduler(t, clientset, informers, stopCh) ds := newDaemonSet("foo", ns.Name) ds.Spec.UpdateStrategy = *strategy _, err := dsClient.Create(ds) if err != nil { t.Fatalf("Failed to create DaemonSet: %v", err) } defer cleanupDaemonSets(t, clientset, ds) addNodes(nodeClient, 0, 5, nil, t) validateDaemonSetPodsAndMarkReady(podClient, podInformer, 5, t) validateDaemonSetStatus(dsClient, ds.Name, 5, t) }) }) } func TestDaemonSetWithNodeSelectorLaunchesPods(t *testing.T) { forEachFeatureGate(t, func(t *testing.T) { forEachStrategy(t, func(t *testing.T, strategy *apps.DaemonSetUpdateStrategy) { server, closeFn, dc, informers, clientset := setup(t) defer closeFn() ns := framework.CreateTestingNamespace("simple-daemonset-test", server, t) defer framework.DeleteTestingNamespace(ns, server, t) dsClient := clientset.AppsV1().DaemonSets(ns.Name) podClient := clientset.CoreV1().Pods(ns.Name) nodeClient := clientset.CoreV1().Nodes() podInformer := informers.Core().V1().Pods().Informer() stopCh := make(chan struct{}) defer close(stopCh) informers.Start(stopCh) go dc.Run(5, stopCh) // Start Scheduler setupScheduler(t, clientset, informers, stopCh) ds := newDaemonSet("foo", ns.Name) ds.Spec.UpdateStrategy = *strategy ds.Spec.Template.Spec.Affinity = &v1.Affinity{ NodeAffinity: &v1.NodeAffinity{ RequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{ NodeSelectorTerms: []v1.NodeSelectorTerm{ { MatchExpressions: []v1.NodeSelectorRequirement{ { Key: "zone", Operator: v1.NodeSelectorOpIn, Values: []string{"test"}, }, }, }, { MatchFields: []v1.NodeSelectorRequirement{ { Key: schedulerapi.NodeFieldSelectorKeyNodeName, Operator: v1.NodeSelectorOpIn, Values: []string{"node-1"}, }, }, }, }, }, }, } _, err := dsClient.Create(ds) if err != nil { t.Fatalf("Failed to create DaemonSet: %v", err) } defer cleanupDaemonSets(t, clientset, ds) addNodes(nodeClient, 0, 2, nil, t) // Two nodes with labels addNodes(nodeClient, 2, 2, map[string]string{ "zone": "test", }, t) addNodes(nodeClient, 4, 2, nil, t) validateDaemonSetPodsAndMarkReady(podClient, podInformer, 3, t) validateDaemonSetStatus(dsClient, ds.Name, 3, t) }) }) } func TestNotReadyNodeDaemonDoesLaunchPod(t *testing.T) { forEachStrategy(t, func(t *testing.T, strategy *apps.DaemonSetUpdateStrategy) { server, closeFn, dc, informers, clientset := setup(t) defer closeFn() ns := framework.CreateTestingNamespace("simple-daemonset-test", server, t) defer framework.DeleteTestingNamespace(ns, server, t) dsClient := clientset.AppsV1().DaemonSets(ns.Name) podClient := clientset.CoreV1().Pods(ns.Name) nodeClient := clientset.CoreV1().Nodes() podInformer := informers.Core().V1().Pods().Informer() stopCh := make(chan struct{}) defer close(stopCh) informers.Start(stopCh) go dc.Run(5, stopCh) // Start Scheduler setupScheduler(t, clientset, informers, stopCh) ds := newDaemonSet("foo", ns.Name) ds.Spec.UpdateStrategy = *strategy _, err := dsClient.Create(ds) if err != nil { t.Fatalf("Failed to create DaemonSet: %v", err) } defer cleanupDaemonSets(t, clientset, ds) node := newNode("single-node", nil) node.Status.Conditions = []v1.NodeCondition{ {Type: v1.NodeReady, Status: v1.ConditionFalse}, } _, err = nodeClient.Create(node) if err != nil { t.Fatalf("Failed to create node: %v", err) } validateDaemonSetPodsAndMarkReady(podClient, podInformer, 1, t) validateDaemonSetStatus(dsClient, ds.Name, 1, t) }) } // When ScheduleDaemonSetPods is disabled, DaemonSets should not launch onto nodes with insufficient capacity. // Look for TestInsufficientCapacityNodeWhenScheduleDaemonSetPodsEnabled, we don't need this test anymore. func TestInsufficientCapacityNodeDaemonDoesNotLaunchPod(t *testing.T) { defer utilfeaturetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.ScheduleDaemonSetPods, false)() forEachStrategy(t, func(t *testing.T, strategy *apps.DaemonSetUpdateStrategy) { server, closeFn, dc, informers, clientset := setup(t) defer closeFn() ns := framework.CreateTestingNamespace("insufficient-capacity", server, t) defer framework.DeleteTestingNamespace(ns, server, t) dsClient := clientset.AppsV1().DaemonSets(ns.Name) nodeClient := clientset.CoreV1().Nodes() eventClient := clientset.CoreV1().Events(ns.Namespace) stopCh := make(chan struct{}) defer close(stopCh) informers.Start(stopCh) go dc.Run(5, stopCh) ds := newDaemonSet("foo", ns.Name) ds.Spec.Template.Spec = resourcePodSpec("node-with-limited-memory", "120M", "75m") ds.Spec.UpdateStrategy = *strategy _, err := dsClient.Create(ds) if err != nil { t.Fatalf("Failed to create DaemonSet: %v", err) } defer cleanupDaemonSets(t, clientset, ds) node := newNode("node-with-limited-memory", nil) node.Status.Allocatable = allocatableResources("100M", "200m") _, err = nodeClient.Create(node) if err != nil { t.Fatalf("Failed to create node: %v", err) } validateFailedPlacementEvent(eventClient, t) }) } // TestInsufficientCapacityNodeDaemonSetCreateButNotLaunchPod tests that when "ScheduleDaemonSetPods" // feature is enabled, the DaemonSet should create Pods for all the nodes regardless of available resource // on the nodes, and kube-scheduler should not schedule Pods onto the nodes with insufficient resource. func TestInsufficientCapacityNodeWhenScheduleDaemonSetPodsEnabled(t *testing.T) { defer utilfeaturetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.ScheduleDaemonSetPods, true)() forEachStrategy(t, func(t *testing.T, strategy *apps.DaemonSetUpdateStrategy) { server, closeFn, dc, informers, clientset := setup(t) defer closeFn() ns := framework.CreateTestingNamespace("insufficient-capacity", server, t) defer framework.DeleteTestingNamespace(ns, server, t) dsClient := clientset.AppsV1().DaemonSets(ns.Name) podClient := clientset.CoreV1().Pods(ns.Name) podInformer := informers.Core().V1().Pods().Informer() nodeClient := clientset.CoreV1().Nodes() stopCh := make(chan struct{}) defer close(stopCh) informers.Start(stopCh) go dc.Run(5, stopCh) // Start Scheduler setupScheduler(t, clientset, informers, stopCh) ds := newDaemonSet("foo", ns.Name) ds.Spec.Template.Spec = resourcePodSpec("", "120M", "75m") ds.Spec.UpdateStrategy = *strategy ds, err := dsClient.Create(ds) if err != nil { t.Fatalf("Failed to create DaemonSet: %v", err) } defer cleanupDaemonSets(t, clientset, ds) node := newNode("node-with-limited-memory", nil) node.Status.Allocatable = allocatableResources("100M", "200m") _, err = nodeClient.Create(node) if err != nil { t.Fatalf("Failed to create node: %v", err) } if err := waitForPodsCreated(podInformer, 1); err != nil { t.Errorf("Failed to wait for pods created: %v", err) } objects := podInformer.GetIndexer().List() for _, object := range objects { pod := object.(*v1.Pod) if err := waitForPodUnschedulable(clientset, pod); err != nil { t.Errorf("Failed to wait for unschedulable status of pod %+v", pod) } } node1 := newNode("node-with-enough-memory", nil) node1.Status.Allocatable = allocatableResources("200M", "2000m") _, err = nodeClient.Create(node1) if err != nil { t.Fatalf("Failed to create node: %v", err) } // When ScheduleDaemonSetPods enabled, 2 pods are created. But only one // of two Pods is scheduled by default scheduler. validateDaemonSetPodsAndMarkReady(podClient, podInformer, 2, t) validateDaemonSetStatus(dsClient, ds.Name, 1, t) }) } // TestLaunchWithHashCollision tests that a DaemonSet can be updated even if there is a // hash collision with an existing ControllerRevision func TestLaunchWithHashCollision(t *testing.T) { server, closeFn, dc, informers, clientset := setup(t) defer closeFn() ns := framework.CreateTestingNamespace("one-node-daemonset-test", server, t) defer framework.DeleteTestingNamespace(ns, server, t) dsClient := clientset.AppsV1().DaemonSets(ns.Name) podInformer := informers.Core().V1().Pods().Informer() nodeClient := clientset.CoreV1().Nodes() stopCh := make(chan struct{}) defer close(stopCh) informers.Start(stopCh) go dc.Run(1, stopCh) setupScheduler(t, clientset, informers, stopCh) // Create single node _, err := nodeClient.Create(newNode("single-node", nil)) if err != nil { t.Fatalf("Failed to create node: %v", err) } // Create new DaemonSet with RollingUpdate strategy orgDs := newDaemonSet("foo", ns.Name) oneIntString := intstr.FromInt(1) orgDs.Spec.UpdateStrategy = apps.DaemonSetUpdateStrategy{ Type: apps.RollingUpdateDaemonSetStrategyType, RollingUpdate: &apps.RollingUpdateDaemonSet{ MaxUnavailable: &oneIntString, }, } ds, err := dsClient.Create(orgDs) if err != nil { t.Fatalf("Failed to create DaemonSet: %v", err) } // Wait for the DaemonSet to be created before proceeding err = waitForDaemonSetAndControllerRevisionCreated(clientset, ds.Name, ds.Namespace) if err != nil { t.Fatalf("Failed to create DaemonSet: %v", err) } ds, err = dsClient.Get(ds.Name, metav1.GetOptions{}) if err != nil { t.Fatalf("Failed to get DaemonSet: %v", err) } var orgCollisionCount int32 if ds.Status.CollisionCount != nil { orgCollisionCount = *ds.Status.CollisionCount } // Look up the ControllerRevision for the DaemonSet _, name := hashAndNameForDaemonSet(ds) revision, err := clientset.AppsV1().ControllerRevisions(ds.Namespace).Get(name, metav1.GetOptions{}) if err != nil || revision == nil { t.Fatalf("Failed to look up ControllerRevision: %v", err) } // Create a "fake" ControllerRevision that we know will create a hash collision when we make // the next update one := int64(1) ds.Spec.Template.Spec.TerminationGracePeriodSeconds = &one newHash, newName := hashAndNameForDaemonSet(ds) newRevision := &apps.ControllerRevision{ ObjectMeta: metav1.ObjectMeta{ Name: newName, Namespace: ds.Namespace, Labels: labelsutil.CloneAndAddLabel(ds.Spec.Template.Labels, apps.DefaultDaemonSetUniqueLabelKey, newHash), Annotations: ds.Annotations, OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(ds, apps.SchemeGroupVersion.WithKind("DaemonSet"))}, }, Data: revision.Data, Revision: revision.Revision + 1, } _, err = clientset.AppsV1().ControllerRevisions(ds.Namespace).Create(newRevision) if err != nil { t.Fatalf("Failed to create ControllerRevision: %v", err) } // Make an update of the DaemonSet which we know will create a hash collision when // the next ControllerRevision is created. ds = updateDS(t, dsClient, ds.Name, func(updateDS *apps.DaemonSet) { updateDS.Spec.Template.Spec.TerminationGracePeriodSeconds = &one }) // Wait for any pod with the latest Spec to exist err = wait.PollImmediate(100*time.Millisecond, 10*time.Second, func() (bool, error) { objects := podInformer.GetIndexer().List() for _, object := range objects { pod := object.(*v1.Pod) if *pod.Spec.TerminationGracePeriodSeconds == *ds.Spec.Template.Spec.TerminationGracePeriodSeconds { return true, nil } } return false, nil }) if err != nil { t.Fatalf("Failed to wait for Pods with the latest Spec to be created: %v", err) } validateDaemonSetCollisionCount(dsClient, ds.Name, orgCollisionCount+1, t) } // TestTaintedNode tests that no matter "ScheduleDaemonSetPods" feature is enabled or not // tainted node isn't expected to have pod scheduled func TestTaintedNode(t *testing.T) { forEachFeatureGate(t, func(t *testing.T) { forEachStrategy(t, func(t *testing.T, strategy *apps.DaemonSetUpdateStrategy) { server, closeFn, dc, informers, clientset := setup(t) defer closeFn() ns := framework.CreateTestingNamespace("tainted-node", server, t) defer framework.DeleteTestingNamespace(ns, server, t) dsClient := clientset.AppsV1().DaemonSets(ns.Name) podClient := clientset.CoreV1().Pods(ns.Name) podInformer := informers.Core().V1().Pods().Informer() nodeClient := clientset.CoreV1().Nodes() stopCh := make(chan struct{}) defer close(stopCh) informers.Start(stopCh) go dc.Run(5, stopCh) // Start Scheduler setupScheduler(t, clientset, informers, stopCh) ds := newDaemonSet("foo", ns.Name) ds.Spec.UpdateStrategy = *strategy ds, err := dsClient.Create(ds) if err != nil { t.Fatalf("Failed to create DaemonSet: %v", err) } defer cleanupDaemonSets(t, clientset, ds) nodeWithTaint := newNode("node-with-taint", nil) nodeWithTaint.Spec.Taints = []v1.Taint{{Key: "key1", Value: "val1", Effect: "NoSchedule"}} _, err = nodeClient.Create(nodeWithTaint) if err != nil { t.Fatalf("Failed to create nodeWithTaint: %v", err) } nodeWithoutTaint := newNode("node-without-taint", nil) _, err = nodeClient.Create(nodeWithoutTaint) if err != nil { t.Fatalf("Failed to create nodeWithoutTaint: %v", err) } validateDaemonSetPodsAndMarkReady(podClient, podInformer, 1, t) validateDaemonSetStatus(dsClient, ds.Name, 1, t) // remove taint from nodeWithTaint nodeWithTaint, err = nodeClient.Get("node-with-taint", metav1.GetOptions{}) if err != nil { t.Fatalf("Failed to retrieve nodeWithTaint: %v", err) } nodeWithTaintCopy := nodeWithTaint.DeepCopy() nodeWithTaintCopy.Spec.Taints = []v1.Taint{} _, err = nodeClient.Update(nodeWithTaintCopy) if err != nil { t.Fatalf("Failed to update nodeWithTaint: %v", err) } validateDaemonSetPodsAndMarkReady(podClient, podInformer, 2, t) validateDaemonSetStatus(dsClient, ds.Name, 2, t) }) }) } // TestUnschedulableNodeDaemonDoesLaunchPod tests that the DaemonSet Pods can still be scheduled // to the Unschedulable nodes when TaintNodesByCondition are enabled. func TestUnschedulableNodeDaemonDoesLaunchPod(t *testing.T) { defer utilfeaturetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.TaintNodesByCondition, true)() forEachFeatureGate(t, func(t *testing.T) { forEachStrategy(t, func(t *testing.T, strategy *apps.DaemonSetUpdateStrategy) { server, closeFn, dc, informers, clientset := setup(t) defer closeFn() ns := framework.CreateTestingNamespace("daemonset-unschedulable-test", server, t) defer framework.DeleteTestingNamespace(ns, server, t) dsClient := clientset.AppsV1().DaemonSets(ns.Name) podClient := clientset.CoreV1().Pods(ns.Name) nodeClient := clientset.CoreV1().Nodes() podInformer := informers.Core().V1().Pods().Informer() stopCh := make(chan struct{}) defer close(stopCh) informers.Start(stopCh) go dc.Run(5, stopCh) // Start Scheduler setupScheduler(t, clientset, informers, stopCh) ds := newDaemonSet("foo", ns.Name) ds.Spec.UpdateStrategy = *strategy ds.Spec.Template.Spec.HostNetwork = true _, err := dsClient.Create(ds) if err != nil { t.Fatalf("Failed to create DaemonSet: %v", err) } defer cleanupDaemonSets(t, clientset, ds) // Creates unschedulable node. node := newNode("unschedulable-node", nil) node.Spec.Unschedulable = true node.Spec.Taints = []v1.Taint{ { Key: schedulerapi.TaintNodeUnschedulable, Effect: v1.TaintEffectNoSchedule, }, } _, err = nodeClient.Create(node) if err != nil { t.Fatalf("Failed to create node: %v", err) } // Creates network-unavailable node. nodeNU := newNode("network-unavailable-node", nil) nodeNU.Status.Conditions = []v1.NodeCondition{ {Type: v1.NodeReady, Status: v1.ConditionFalse}, {Type: v1.NodeNetworkUnavailable, Status: v1.ConditionTrue}, } nodeNU.Spec.Taints = []v1.Taint{ { Key: schedulerapi.TaintNodeNetworkUnavailable, Effect: v1.TaintEffectNoSchedule, }, } _, err = nodeClient.Create(nodeNU) if err != nil { t.Fatalf("Failed to create node: %v", err) } validateDaemonSetPodsAndMarkReady(podClient, podInformer, 2, t) validateDaemonSetStatus(dsClient, ds.Name, 2, t) }) }) }
}
vue-router.esm.js
/*! * vue-router v3.0.4 * (c) 2019 Evan You * @license MIT */ /* */ function assert (condition, message) { if (!condition) { throw new Error(("[vue-router] " + message)) } } function warn (condition, message) { if (process.env.NODE_ENV !== 'production' && !condition) { typeof console !== 'undefined' && console.warn(("[vue-router] " + message)); } } function isError (err) { return Object.prototype.toString.call(err).indexOf('Error') > -1 } function extend (a, b) { for (var key in b) { a[key] = b[key]; } return a } var View = { name: 'RouterView', functional: true, props: { name: { type: String, default: 'default' } }, render: function render (_, ref) { var props = ref.props; var children = ref.children; var parent = ref.parent; var data = ref.data; // used by devtools to display a router-view badge data.routerView = true; // directly use parent context's createElement() function // so that components rendered by router-view can resolve named slots var h = parent.$createElement; var name = props.name; var route = parent.$route; var cache = parent._routerViewCache || (parent._routerViewCache = {}); // determine current view depth, also check to see if the tree // has been toggled inactive but kept-alive. var depth = 0; var inactive = false; while (parent && parent._routerRoot !== parent) { if (parent.$vnode && parent.$vnode.data.routerView) { depth++; } if (parent._inactive) { inactive = true; } parent = parent.$parent; } data.routerViewDepth = depth; // render previous view if the tree is inactive and kept-alive if (inactive) { return h(cache[name], data, children) } var matched = route.matched[depth]; // render empty node if no matched route if (!matched) { cache[name] = null; return h() } var component = cache[name] = matched.components[name]; // attach instance registration hook // this will be called in the instance's injected lifecycle hooks data.registerRouteInstance = function (vm, val) { // val could be undefined for unregistration var current = matched.instances[name]; if ( (val && current !== vm) || (!val && current === vm) ) { matched.instances[name] = val; } } // also register instance in prepatch hook // in case the same component instance is reused across different routes ;(data.hook || (data.hook = {})).prepatch = function (_, vnode) { matched.instances[name] = vnode.componentInstance; }; // resolve props var propsToPass = data.props = resolveProps(route, matched.props && matched.props[name]); if (propsToPass) { // clone to prevent mutation propsToPass = data.props = extend({}, propsToPass); // pass non-declared props as attrs var attrs = data.attrs = data.attrs || {}; for (var key in propsToPass) { if (!component.props || !(key in component.props)) { attrs[key] = propsToPass[key]; delete propsToPass[key]; } } } return h(component, data, children) } } function resolveProps (route, config) { switch (typeof config) { case 'undefined': return case 'object': return config case 'function': return config(route) case 'boolean': return config ? route.params : undefined default: if (process.env.NODE_ENV !== 'production') { warn( false, "props in \"" + (route.path) + "\" is a " + (typeof config) + ", " + "expecting an object, function or boolean." ); } } } /* */ var encodeReserveRE = /[!'()*]/g; var encodeReserveReplacer = function (c) { return '%' + c.charCodeAt(0).toString(16); }; var commaRE = /%2C/g; // fixed encodeURIComponent which is more conformant to RFC3986: // - escapes [!'()*] // - preserve commas var encode = function (str) { return encodeURIComponent(str) .replace(encodeReserveRE, encodeReserveReplacer) .replace(commaRE, ','); }; var decode = decodeURIComponent; function resolveQuery ( query, extraQuery, _parseQuery ) { if ( extraQuery === void 0 ) extraQuery = {}; var parse = _parseQuery || parseQuery; var parsedQuery; try { parsedQuery = parse(query || ''); } catch (e) { process.env.NODE_ENV !== 'production' && warn(false, e.message); parsedQuery = {}; } for (var key in extraQuery) { parsedQuery[key] = extraQuery[key]; } return parsedQuery } function parseQuery (query) { var res = {}; query = query.trim().replace(/^(\?|#|&)/, ''); if (!query) { return res } query.split('&').forEach(function (param) { var parts = param.replace(/\+/g, ' ').split('='); var key = decode(parts.shift()); var val = parts.length > 0 ? decode(parts.join('=')) : null; if (res[key] === undefined) { res[key] = val; } else if (Array.isArray(res[key])) { res[key].push(val); } else { res[key] = [res[key], val]; } }); return res } function stringifyQuery (obj) { var res = obj ? Object.keys(obj).map(function (key) { var val = obj[key]; if (val === undefined) { return '' } if (val === null) { return encode(key) } if (Array.isArray(val)) { var result = []; val.forEach(function (val2) { if (val2 === undefined) { return } if (val2 === null) { result.push(encode(key)); } else { result.push(encode(key) + '=' + encode(val2)); } }); return result.join('&') } return encode(key) + '=' + encode(val) }).filter(function (x) { return x.length > 0; }).join('&') : null; return res ? ("?" + res) : '' } /* */ var trailingSlashRE = /\/?$/; function createRoute ( record, location, redirectedFrom, router ) { var stringifyQuery$$1 = router && router.options.stringifyQuery; var query = location.query || {}; try { query = clone(query); } catch (e) {} var route = { name: location.name || (record && record.name), meta: (record && record.meta) || {}, path: location.path || '/', hash: location.hash || '', query: query, params: location.params || {}, fullPath: getFullPath(location, stringifyQuery$$1), matched: record ? formatMatch(record) : [] }; if (redirectedFrom) { route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery$$1); } return Object.freeze(route) } function clone (value) { if (Array.isArray(value)) { return value.map(clone) } else if (value && typeof value === 'object') { var res = {}; for (var key in value) { res[key] = clone(value[key]); } return res } else { return value } } // the starting route that represents the initial state var START = createRoute(null, { path: '/' }); function formatMatch (record) { var res = []; while (record) { res.unshift(record); record = record.parent; } return res } function getFullPath ( ref, _stringifyQuery ) { var path = ref.path; var query = ref.query; if ( query === void 0 ) query = {}; var hash = ref.hash; if ( hash === void 0 ) hash = ''; var stringify = _stringifyQuery || stringifyQuery; return (path || '/') + stringify(query) + hash } function isSameRoute (a, b) { if (b === START) { return a === b } else if (!b) { return false } else if (a.path && b.path) { return ( a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') && a.hash === b.hash && isObjectEqual(a.query, b.query) ) } else if (a.name && b.name) { return ( a.name === b.name && a.hash === b.hash && isObjectEqual(a.query, b.query) && isObjectEqual(a.params, b.params) ) } else { return false } } function isObjectEqual (a, b) { if ( a === void 0 ) a = {}; if ( b === void 0 ) b = {}; // handle null value #1566 if (!a || !b) { return a === b } var aKeys = Object.keys(a); var bKeys = Object.keys(b); if (aKeys.length !== bKeys.length) { return false } return aKeys.every(function (key) { var aVal = a[key]; var bVal = b[key]; // check nested equality if (typeof aVal === 'object' && typeof bVal === 'object') { return isObjectEqual(aVal, bVal) } return String(aVal) === String(bVal) }) } function isIncludedRoute (current, target) { return ( current.path.replace(trailingSlashRE, '/').indexOf( target.path.replace(trailingSlashRE, '/') ) === 0 && (!target.hash || current.hash === target.hash) && queryIncludes(current.query, target.query) ) } function queryIncludes (current, target) { for (var key in target) { if (!(key in current)) { return false } } return true } /* */ // work around weird flow bug var toTypes = [String, Object]; var eventTypes = [String, Array]; var Link = { name: 'RouterLink', props: { to: { type: toTypes, required: true }, tag: { type: String, default: 'a' }, exact: Boolean, append: Boolean, replace: Boolean, activeClass: String, exactActiveClass: String, event: { type: eventTypes, default: 'click' } }, render: function render (h) { var this$1 = this; var router = this.$router; var current = this.$route; var ref = router.resolve(this.to, current, this.append); var location = ref.location; var route = ref.route; var href = ref.href; var classes = {}; var globalActiveClass = router.options.linkActiveClass; var globalExactActiveClass = router.options.linkExactActiveClass; // Support global empty active class var activeClassFallback = globalActiveClass == null ? 'router-link-active' : globalActiveClass; var exactActiveClassFallback = globalExactActiveClass == null ? 'router-link-exact-active' : globalExactActiveClass; var activeClass = this.activeClass == null ? activeClassFallback : this.activeClass; var exactActiveClass = this.exactActiveClass == null ? exactActiveClassFallback : this.exactActiveClass; var compareTarget = location.path ? createRoute(null, location, null, router) : route; classes[exactActiveClass] = isSameRoute(current, compareTarget); classes[activeClass] = this.exact ? classes[exactActiveClass] : isIncludedRoute(current, compareTarget); var handler = function (e) { if (guardEvent(e)) { if (this$1.replace) { router.replace(location); } else { router.push(location); } } }; var on = { click: guardEvent }; if (Array.isArray(this.event)) { this.event.forEach(function (e) { on[e] = handler; }); } else { on[this.event] = handler; } var data = { class: classes }; if (this.tag === 'a') { data.on = on; data.attrs = { href: href }; } else { // find the first <a> child and apply listener and href var a = findAnchor(this.$slots.default); if (a) { // in case the <a> is a static node a.isStatic = false; var aData = a.data = extend({}, a.data); aData.on = on; var aAttrs = a.data.attrs = extend({}, a.data.attrs); aAttrs.href = href; } else { // doesn't have <a> child, apply listener to self data.on = on; } } return h(this.tag, data, this.$slots.default) } } function guardEvent (e) { // don't redirect with control keys if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) { return } // don't redirect when preventDefault called if (e.defaultPrevented) { return } // don't redirect on right click if (e.button !== undefined && e.button !== 0) { return } // don't redirect if `target="_blank"` if (e.currentTarget && e.currentTarget.getAttribute) { var target = e.currentTarget.getAttribute('target'); if (/\b_blank\b/i.test(target)) { return } } // this may be a Weex event which doesn't have this method if (e.preventDefault) { e.preventDefault(); } return true } function findAnchor (children) { if (children) { var child; for (var i = 0; i < children.length; i++) { child = children[i]; if (child.tag === 'a') { return child } if (child.children && (child = findAnchor(child.children))) { return child } } } } var _Vue; function install (Vue) { if (install.installed && _Vue === Vue) { return } install.installed = true; _Vue = Vue; var isDef = function (v) { return v !== undefined; }; var registerInstance = function (vm, callVal) { var i = vm.$options._parentVnode; if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) { i(vm, callVal); } }; Vue.mixin({ beforeCreate: function beforeCreate () { if (isDef(this.$options.router)) { this._routerRoot = this; this._router = this.$options.router; this._router.init(this); Vue.util.defineReactive(this, '_route', this._router.history.current); } else { this._routerRoot = (this.$parent && this.$parent._routerRoot) || this; } registerInstance(this, this); }, destroyed: function destroyed () { registerInstance(this); } }); Object.defineProperty(Vue.prototype, '$router', { get: function get () { return this._routerRoot._router } }); Object.defineProperty(Vue.prototype, '$route', { get: function get () { return this._routerRoot._route } }); Vue.component('RouterView', View); Vue.component('RouterLink', Link); var strats = Vue.config.optionMergeStrategies; // use the same hook merging strategy for route hooks strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created; } /* */ var inBrowser = typeof window !== 'undefined'; /* */ function resolvePath ( relative, base, append ) { var firstChar = relative.charAt(0); if (firstChar === '/') { return relative } if (firstChar === '?' || firstChar === '#') { return base + relative } var stack = base.split('/'); // remove trailing segment if: // - not appending // - appending to trailing slash (last segment is empty) if (!append || !stack[stack.length - 1]) { stack.pop(); } // resolve relative path var segments = relative.replace(/^\//, '').split('/'); for (var i = 0; i < segments.length; i++) { var segment = segments[i]; if (segment === '..') { stack.pop(); } else if (segment !== '.') { stack.push(segment); } } // ensure leading slash if (stack[0] !== '') { stack.unshift(''); } return stack.join('/') } function parsePath (path) { var hash = ''; var query = ''; var hashIndex = path.indexOf('#'); if (hashIndex >= 0) { hash = path.slice(hashIndex); path = path.slice(0, hashIndex); } var queryIndex = path.indexOf('?'); if (queryIndex >= 0) { query = path.slice(queryIndex + 1); path = path.slice(0, queryIndex); } return { path: path, query: query, hash: hash } } function cleanPath (path) { return path.replace(/\/\//g, '/') } var isarray = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; /** * Expose `pathToRegexp`. */ var pathToRegexp_1 = pathToRegexp; var parse_1 = parse; var compile_1 = compile; var tokensToFunction_1 = tokensToFunction; var tokensToRegExp_1 = tokensToRegExp; /** * The main path matching regexp utility. * * @type {RegExp} */ var PATH_REGEXP = new RegExp([ // Match escaped characters that would otherwise appear in future matches. // This allows the user to escape special characters that won't transform. '(\\\\.)', // Match Express-style parameters and un-named parameters with a prefix // and optional suffixes. Matches appear as: // // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined] // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined] // "/*" => ["/", undefined, undefined, undefined, undefined, "*"] '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))' ].join('|'), 'g'); /** * Parse a string for the raw tokens. * * @param {string} str * @param {Object=} options * @return {!Array} */ function parse (str, options) { var tokens = []; var key = 0; var index = 0; var path = ''; var defaultDelimiter = options && options.delimiter || '/'; var res; while ((res = PATH_REGEXP.exec(str)) != null) { var m = res[0]; var escaped = res[1]; var offset = res.index; path += str.slice(index, offset); index = offset + m.length; // Ignore already escaped sequences. if (escaped) { path += escaped[1]; continue } var next = str[index]; var prefix = res[2]; var name = res[3]; var capture = res[4]; var group = res[5]; var modifier = res[6]; var asterisk = res[7]; // Push the current path onto the tokens. if (path) { tokens.push(path); path = ''; } var partial = prefix != null && next != null && next !== prefix; var repeat = modifier === '+' || modifier === '*'; var optional = modifier === '?' || modifier === '*'; var delimiter = res[2] || defaultDelimiter; var pattern = capture || group; tokens.push({ name: name || key++, prefix: prefix || '', delimiter: delimiter, optional: optional, repeat: repeat, partial: partial, asterisk: !!asterisk, pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?') }); } // Match any characters still remaining. if (index < str.length) { path += str.substr(index); } // If the path exists, push it onto the end. if (path) { tokens.push(path); } return tokens } /** * Compile a string to a template function for the path. * * @param {string} str * @param {Object=} options * @return {!function(Object=, Object=)} */ function compile (str, options) { return tokensToFunction(parse(str, options)) } /** * Prettier encoding of URI path segments. * * @param {string} * @return {string} */ function encodeURIComponentPretty (str) { return encodeURI(str).replace(/[\/?#]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } /** * Encode the asterisk parameter. Similar to `pretty`, but allows slashes. * * @param {string} * @return {string} */ function encodeAsterisk (str) { return encodeURI(str).replace(/[?#]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } /** * Expose a method for transforming tokens into the path function. */ function tokensToFunction (tokens) { // Compile all the tokens into regexps. var matches = new Array(tokens.length); // Compile all the patterns before compilation. for (var i = 0; i < tokens.length; i++) { if (typeof tokens[i] === 'object') { matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$'); } } return function (obj, opts) { var path = ''; var data = obj || {}; var options = opts || {}; var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (typeof token === 'string') { path += token; continue } var value = data[token.name]; var segment; if (value == null) { if (token.optional) { // Prepend partial segment prefixes. if (token.partial) { path += token.prefix; } continue } else { throw new TypeError('Expected "' + token.name + '" to be defined') } } if (isarray(value)) { if (!token.repeat) { throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`') } if (value.length === 0) { if (token.optional) { continue } else { throw new TypeError('Expected "' + token.name + '" to not be empty') } } for (var j = 0; j < value.length; j++) { segment = encode(value[j]); if (!matches[i].test(segment)) { throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`') } path += (j === 0 ? token.prefix : token.delimiter) + segment; } continue } segment = token.asterisk ? encodeAsterisk(value) : encode(value); if (!matches[i].test(segment)) { throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"') } path += token.prefix + segment; } return path } } /** * Escape a regular expression string. * * @param {string} str * @return {string} */ function escapeString (str) { return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1') } /** * Escape the capturing group by escaping special characters and meaning. * * @param {string} group * @return {string} */ function escapeGroup (group) { return group.replace(/([=!:$\/()])/g, '\\$1') } /** * Attach the keys as a property of the regexp. * * @param {!RegExp} re * @param {Array} keys * @return {!RegExp} */ function attachKeys (re, keys) { re.keys = keys; return re } /** * Get the flags for a regexp from the options. * * @param {Object} options * @return {string} */ function flags (options) { return options.sensitive ? '' : 'i' } /** * Pull out keys from a regexp. * * @param {!RegExp} path * @param {!Array} keys * @return {!RegExp} */ function regexpToRegexp (path, keys) { // Use a negative lookahead to match only capturing groups. var groups = path.source.match(/\((?!\?)/g); if (groups) { for (var i = 0; i < groups.length; i++) { keys.push({ name: i, prefix: null, delimiter: null, optional: false, repeat: false, partial: false, asterisk: false, pattern: null }); } } return attachKeys(path, keys) } /** * Transform an array into a regexp. * * @param {!Array} path * @param {Array} keys * @param {!Object} options * @return {!RegExp} */ function arrayToRegexp (path, keys, options) { var parts = []; for (var i = 0; i < path.length; i++) { parts.push(pathToRegexp(path[i], keys, options).source); } var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options)); return attachKeys(regexp, keys) } /** * Create a path regexp from string input. * * @param {string} path * @param {!Array} keys * @param {!Object} options * @return {!RegExp} */ function stringToRegexp (path, keys, options) { return tokensToRegExp(parse(path, options), keys, options) } /** * Expose a function for taking tokens and returning a RegExp. * * @param {!Array} tokens * @param {(Array|Object)=} keys * @param {Object=} options * @return {!RegExp} */ function tokensToRegExp (tokens, keys, options) { if (!isarray(keys)) { options = /** @type {!Object} */ (keys || options); keys = []; } options = options || {}; var strict = options.strict; var end = options.end !== false; var route = ''; // Iterate over the tokens and create our regexp string. for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (typeof token === 'string') { route += escapeString(token); } else { var prefix = escapeString(token.prefix); var capture = '(?:' + token.pattern + ')'; keys.push(token); if (token.repeat) { capture += '(?:' + prefix + capture + ')*'; } if (token.optional) { if (!token.partial) { capture = '(?:' + prefix + '(' + capture + '))?'; } else { capture = prefix + '(' + capture + ')?'; } } else { capture = prefix + '(' + capture + ')'; } route += capture; } } var delimiter = escapeString(options.delimiter || '/'); var endsWithDelimiter = route.slice(-delimiter.length) === delimiter; // In non-strict mode we allow a slash at the end of match. If the path to // match already ends with a slash, we remove it for consistency. The slash // is valid at the end of a path match, not in the middle. This is important // in non-ending mode, where "/test/" shouldn't match "/test//route". if (!strict) { route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?'; } if (end) { route += '$'; } else { // In non-ending mode, we need the capturing groups to match as much as // possible by using a positive lookahead to the end or next path segment. route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)'; } return attachKeys(new RegExp('^' + route, flags(options)), keys) } /** * Normalize the given path string, returning a regular expression. * * An empty array can be passed in for the keys, which will hold the * placeholder key descriptions. For example, using `/user/:id`, `keys` will * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`. * * @param {(string|RegExp|Array)} path * @param {(Array|Object)=} keys * @param {Object=} options * @return {!RegExp} */ function pathToRegexp (path, keys, options) { if (!isarray(keys)) { options = /** @type {!Object} */ (keys || options); keys = []; } options = options || {}; if (path instanceof RegExp) { return regexpToRegexp(path, /** @type {!Array} */ (keys)) } if (isarray(path)) { return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options) } return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options) } pathToRegexp_1.parse = parse_1; pathToRegexp_1.compile = compile_1; pathToRegexp_1.tokensToFunction = tokensToFunction_1; pathToRegexp_1.tokensToRegExp = tokensToRegExp_1; /* */ // $flow-disable-line var regexpCompileCache = Object.create(null); function fillParams ( path, params, routeMsg ) { params = params || {}; try { var filler = regexpCompileCache[path] || (regexpCompileCache[path] = pathToRegexp_1.compile(path)); // Fix #2505 resolving asterisk routes { name: 'not-found', params: { pathMatch: '/not-found' }} if (params.pathMatch) { params[0] = params.pathMatch; } return filler(params, { pretty: true }) } catch (e) { if (process.env.NODE_ENV !== 'production') { warn(false, ("missing param for " + routeMsg + ": " + (e.message))); } return '' } finally { // delete the 0 if it was added delete params[0]; } } /* */ function createRouteMap ( routes, oldPathList, oldPathMap, oldNameMap ) { // the path list is used to control path matching priority var pathList = oldPathList || []; // $flow-disable-line var pathMap = oldPathMap || Object.create(null); // $flow-disable-line var nameMap = oldNameMap || Object.create(null); routes.forEach(function (route) { addRouteRecord(pathList, pathMap, nameMap, route); }); // ensure wildcard routes are always at the end for (var i = 0, l = pathList.length; i < l; i++) { if (pathList[i] === '*') { pathList.push(pathList.splice(i, 1)[0]); l--; i--; } } return { pathList: pathList, pathMap: pathMap, nameMap: nameMap } } function addRouteRecord ( pathList, pathMap, nameMap, route, parent, matchAs ) { var path = route.path; var name = route.name; if (process.env.NODE_ENV !== 'production') { assert(path != null, "\"path\" is required in a route configuration."); assert( typeof route.component !== 'string', "route config \"component\" for path: " + (String(path || name)) + " cannot be a " + "string id. Use an actual component instead." ); } var pathToRegexpOptions = route.pathToRegexpOptions || {}; var normalizedPath = normalizePath( path, parent, pathToRegexpOptions.strict ); if (typeof route.caseSensitive === 'boolean') { pathToRegexpOptions.sensitive = route.caseSensitive; } var record = { path: normalizedPath, regex: compileRouteRegex(normalizedPath, pathToRegexpOptions), components: route.components || { default: route.component }, instances: {}, name: name, parent: parent, matchAs: matchAs, redirect: route.redirect, beforeEnter: route.beforeEnter, meta: route.meta || {}, props: route.props == null ? {} : route.components ? route.props : { default: route.props } }; if (route.children) { // Warn if route is named, does not redirect and has a default child route. // If users navigate to this route by name, the default child will // not be rendered (GH Issue #629) if (process.env.NODE_ENV !== 'production') { if (route.name && !route.redirect && route.children.some(function (child) { return /^\/?$/.test(child.path); })) { warn( false, "Named Route '" + (route.name) + "' has a default child route. " + "When navigating to this named route (:to=\"{name: '" + (route.name) + "'\"), " + "the default child route will not be rendered. Remove the name from " + "this route and use the name of the default child route for named " + "links instead." ); } } route.children.forEach(function (child) { var childMatchAs = matchAs ? cleanPath((matchAs + "/" + (child.path))) : undefined; addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs); }); } if (route.alias !== undefined) { var aliases = Array.isArray(route.alias) ? route.alias : [route.alias]; aliases.forEach(function (alias) { var aliasRoute = { path: alias, children: route.children }; addRouteRecord( pathList, pathMap, nameMap, aliasRoute, parent, record.path || '/' // matchAs ); }); } if (!pathMap[record.path]) { pathList.push(record.path); pathMap[record.path] = record; } if (name) { if (!nameMap[name]) { nameMap[name] = record; } else if (process.env.NODE_ENV !== 'production' && !matchAs) { warn( false, "Duplicate named routes definition: " + "{ name: \"" + name + "\", path: \"" + (record.path) + "\" }" ); } } } function
(path, pathToRegexpOptions) { var regex = pathToRegexp_1(path, [], pathToRegexpOptions); if (process.env.NODE_ENV !== 'production') { var keys = Object.create(null); regex.keys.forEach(function (key) { warn(!keys[key.name], ("Duplicate param keys in route with path: \"" + path + "\"")); keys[key.name] = true; }); } return regex } function normalizePath (path, parent, strict) { if (!strict) { path = path.replace(/\/$/, ''); } if (path[0] === '/') { return path } if (parent == null) { return path } return cleanPath(((parent.path) + "/" + path)) } /* */ function normalizeLocation ( raw, current, append, router ) { var next = typeof raw === 'string' ? { path: raw } : raw; // named target if (next._normalized) { return next } else if (next.name) { return extend({}, raw) } // relative params if (!next.path && next.params && current) { next = extend({}, next); next._normalized = true; var params = extend(extend({}, current.params), next.params); if (current.name) { next.name = current.name; next.params = params; } else if (current.matched.length) { var rawPath = current.matched[current.matched.length - 1].path; next.path = fillParams(rawPath, params, ("path " + (current.path))); } else if (process.env.NODE_ENV !== 'production') { warn(false, "relative params navigation requires a current route."); } return next } var parsedPath = parsePath(next.path || ''); var basePath = (current && current.path) || '/'; var path = parsedPath.path ? resolvePath(parsedPath.path, basePath, append || next.append) : basePath; var query = resolveQuery( parsedPath.query, next.query, router && router.options.parseQuery ); var hash = next.hash || parsedPath.hash; if (hash && hash.charAt(0) !== '#') { hash = "#" + hash; } return { _normalized: true, path: path, query: query, hash: hash } } /* */ function createMatcher ( routes, router ) { var ref = createRouteMap(routes); var pathList = ref.pathList; var pathMap = ref.pathMap; var nameMap = ref.nameMap; function addRoutes (routes) { createRouteMap(routes, pathList, pathMap, nameMap); } function match ( raw, currentRoute, redirectedFrom ) { var location = normalizeLocation(raw, currentRoute, false, router); var name = location.name; if (name) { var record = nameMap[name]; if (process.env.NODE_ENV !== 'production') { warn(record, ("Route with name '" + name + "' does not exist")); } if (!record) { return _createRoute(null, location) } var paramNames = record.regex.keys .filter(function (key) { return !key.optional; }) .map(function (key) { return key.name; }); if (typeof location.params !== 'object') { location.params = {}; } if (currentRoute && typeof currentRoute.params === 'object') { for (var key in currentRoute.params) { if (!(key in location.params) && paramNames.indexOf(key) > -1) { location.params[key] = currentRoute.params[key]; } } } if (record) { location.path = fillParams(record.path, location.params, ("named route \"" + name + "\"")); return _createRoute(record, location, redirectedFrom) } } else if (location.path) { location.params = {}; for (var i = 0; i < pathList.length; i++) { var path = pathList[i]; var record$1 = pathMap[path]; if (matchRoute(record$1.regex, location.path, location.params)) { return _createRoute(record$1, location, redirectedFrom) } } } // no match return _createRoute(null, location) } function redirect ( record, location ) { var originalRedirect = record.redirect; var redirect = typeof originalRedirect === 'function' ? originalRedirect(createRoute(record, location, null, router)) : originalRedirect; if (typeof redirect === 'string') { redirect = { path: redirect }; } if (!redirect || typeof redirect !== 'object') { if (process.env.NODE_ENV !== 'production') { warn( false, ("invalid redirect option: " + (JSON.stringify(redirect))) ); } return _createRoute(null, location) } var re = redirect; var name = re.name; var path = re.path; var query = location.query; var hash = location.hash; var params = location.params; query = re.hasOwnProperty('query') ? re.query : query; hash = re.hasOwnProperty('hash') ? re.hash : hash; params = re.hasOwnProperty('params') ? re.params : params; if (name) { // resolved named direct var targetRecord = nameMap[name]; if (process.env.NODE_ENV !== 'production') { assert(targetRecord, ("redirect failed: named route \"" + name + "\" not found.")); } return match({ _normalized: true, name: name, query: query, hash: hash, params: params }, undefined, location) } else if (path) { // 1. resolve relative redirect var rawPath = resolveRecordPath(path, record); // 2. resolve params var resolvedPath = fillParams(rawPath, params, ("redirect route with path \"" + rawPath + "\"")); // 3. rematch with existing query and hash return match({ _normalized: true, path: resolvedPath, query: query, hash: hash }, undefined, location) } else { if (process.env.NODE_ENV !== 'production') { warn(false, ("invalid redirect option: " + (JSON.stringify(redirect)))); } return _createRoute(null, location) } } function alias ( record, location, matchAs ) { var aliasedPath = fillParams(matchAs, location.params, ("aliased route with path \"" + matchAs + "\"")); var aliasedMatch = match({ _normalized: true, path: aliasedPath }); if (aliasedMatch) { var matched = aliasedMatch.matched; var aliasedRecord = matched[matched.length - 1]; location.params = aliasedMatch.params; return _createRoute(aliasedRecord, location) } return _createRoute(null, location) } function _createRoute ( record, location, redirectedFrom ) { if (record && record.redirect) { return redirect(record, redirectedFrom || location) } if (record && record.matchAs) { return alias(record, location, record.matchAs) } return createRoute(record, location, redirectedFrom, router) } return { match: match, addRoutes: addRoutes } } function matchRoute ( regex, path, params ) { var m = path.match(regex); if (!m) { return false } else if (!params) { return true } for (var i = 1, len = m.length; i < len; ++i) { var key = regex.keys[i - 1]; var val = typeof m[i] === 'string' ? decodeURIComponent(m[i]) : m[i]; if (key) { // Fix #1994: using * with props: true generates a param named 0 params[key.name || 'pathMatch'] = val; } } return true } function resolveRecordPath (path, record) { return resolvePath(path, record.parent ? record.parent.path : '/', true) } /* */ var positionStore = Object.create(null); function setupScroll () { // Fix for #1585 for Firefox // Fix for #2195 Add optional third attribute to workaround a bug in safari https://bugs.webkit.org/show_bug.cgi?id=182678 window.history.replaceState({ key: getStateKey() }, '', window.location.href.replace(window.location.origin, '')); window.addEventListener('popstate', function (e) { saveScrollPosition(); if (e.state && e.state.key) { setStateKey(e.state.key); } }); } function handleScroll ( router, to, from, isPop ) { if (!router.app) { return } var behavior = router.options.scrollBehavior; if (!behavior) { return } if (process.env.NODE_ENV !== 'production') { assert(typeof behavior === 'function', "scrollBehavior must be a function"); } // wait until re-render finishes before scrolling router.app.$nextTick(function () { var position = getScrollPosition(); var shouldScroll = behavior.call(router, to, from, isPop ? position : null); if (!shouldScroll) { return } if (typeof shouldScroll.then === 'function') { shouldScroll.then(function (shouldScroll) { scrollToPosition((shouldScroll), position); }).catch(function (err) { if (process.env.NODE_ENV !== 'production') { assert(false, err.toString()); } }); } else { scrollToPosition(shouldScroll, position); } }); } function saveScrollPosition () { var key = getStateKey(); if (key) { positionStore[key] = { x: window.pageXOffset, y: window.pageYOffset }; } } function getScrollPosition () { var key = getStateKey(); if (key) { return positionStore[key] } } function getElementPosition (el, offset) { var docEl = document.documentElement; var docRect = docEl.getBoundingClientRect(); var elRect = el.getBoundingClientRect(); return { x: elRect.left - docRect.left - offset.x, y: elRect.top - docRect.top - offset.y } } function isValidPosition (obj) { return isNumber(obj.x) || isNumber(obj.y) } function normalizePosition (obj) { return { x: isNumber(obj.x) ? obj.x : window.pageXOffset, y: isNumber(obj.y) ? obj.y : window.pageYOffset } } function normalizeOffset (obj) { return { x: isNumber(obj.x) ? obj.x : 0, y: isNumber(obj.y) ? obj.y : 0 } } function isNumber (v) { return typeof v === 'number' } function scrollToPosition (shouldScroll, position) { var isObject = typeof shouldScroll === 'object'; if (isObject && typeof shouldScroll.selector === 'string') { var el = document.querySelector(shouldScroll.selector); if (el) { var offset = shouldScroll.offset && typeof shouldScroll.offset === 'object' ? shouldScroll.offset : {}; offset = normalizeOffset(offset); position = getElementPosition(el, offset); } else if (isValidPosition(shouldScroll)) { position = normalizePosition(shouldScroll); } } else if (isObject && isValidPosition(shouldScroll)) { position = normalizePosition(shouldScroll); } if (position) { window.scrollTo(position.x, position.y); } } /* */ var supportsPushState = inBrowser && (function () { var ua = window.navigator.userAgent; if ( (ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1 ) { return false } return window.history && 'pushState' in window.history })(); // use User Timing api (if present) for more accurate key precision var Time = inBrowser && window.performance && window.performance.now ? window.performance : Date; var _key = genKey(); function genKey () { return Time.now().toFixed(3) } function getStateKey () { return _key } function setStateKey (key) { _key = key; } function pushState (url, replace) { saveScrollPosition(); // try...catch the pushState call to get around Safari // DOM Exception 18 where it limits to 100 pushState calls var history = window.history; try { if (replace) { history.replaceState({ key: _key }, '', url); } else { _key = genKey(); history.pushState({ key: _key }, '', url); } } catch (e) { window.location[replace ? 'replace' : 'assign'](url); } } function replaceState (url) { pushState(url, true); } /* */ function runQueue (queue, fn, cb) { var step = function (index) { if (index >= queue.length) { cb(); } else { if (queue[index]) { fn(queue[index], function () { step(index + 1); }); } else { step(index + 1); } } }; step(0); } /* */ function resolveAsyncComponents (matched) { return function (to, from, next) { var hasAsync = false; var pending = 0; var error = null; flatMapComponents(matched, function (def, _, match, key) { // if it's a function and doesn't have cid attached, // assume it's an async component resolve function. // we are not using Vue's default async resolving mechanism because // we want to halt the navigation until the incoming component has been // resolved. if (typeof def === 'function' && def.cid === undefined) { hasAsync = true; pending++; var resolve = once(function (resolvedDef) { if (isESModule(resolvedDef)) { resolvedDef = resolvedDef.default; } // save resolved on async factory in case it's used elsewhere def.resolved = typeof resolvedDef === 'function' ? resolvedDef : _Vue.extend(resolvedDef); match.components[key] = resolvedDef; pending--; if (pending <= 0) { next(); } }); var reject = once(function (reason) { var msg = "Failed to resolve async component " + key + ": " + reason; process.env.NODE_ENV !== 'production' && warn(false, msg); if (!error) { error = isError(reason) ? reason : new Error(msg); next(error); } }); var res; try { res = def(resolve, reject); } catch (e) { reject(e); } if (res) { if (typeof res.then === 'function') { res.then(resolve, reject); } else { // new syntax in Vue 2.3 var comp = res.component; if (comp && typeof comp.then === 'function') { comp.then(resolve, reject); } } } } }); if (!hasAsync) { next(); } } } function flatMapComponents ( matched, fn ) { return flatten(matched.map(function (m) { return Object.keys(m.components).map(function (key) { return fn( m.components[key], m.instances[key], m, key ); }) })) } function flatten (arr) { return Array.prototype.concat.apply([], arr) } var hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; function isESModule (obj) { return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module') } // in Webpack 2, require.ensure now also returns a Promise // so the resolve/reject functions may get called an extra time // if the user uses an arrow function shorthand that happens to // return that Promise. function once (fn) { var called = false; return function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; if (called) { return } called = true; return fn.apply(this, args) } } /* */ var History = function History (router, base) { this.router = router; this.base = normalizeBase(base); // start with a route object that stands for "nowhere" this.current = START; this.pending = null; this.ready = false; this.readyCbs = []; this.readyErrorCbs = []; this.errorCbs = []; }; History.prototype.listen = function listen (cb) { this.cb = cb; }; History.prototype.onReady = function onReady (cb, errorCb) { if (this.ready) { cb(); } else { this.readyCbs.push(cb); if (errorCb) { this.readyErrorCbs.push(errorCb); } } }; History.prototype.onError = function onError (errorCb) { this.errorCbs.push(errorCb); }; History.prototype.transitionTo = function transitionTo (location, onComplete, onAbort) { var this$1 = this; var route = this.router.match(location, this.current); this.confirmTransition(route, function () { this$1.updateRoute(route); onComplete && onComplete(route); this$1.ensureURL(); // fire ready cbs once if (!this$1.ready) { this$1.ready = true; this$1.readyCbs.forEach(function (cb) { cb(route); }); } }, function (err) { if (onAbort) { onAbort(err); } if (err && !this$1.ready) { this$1.ready = true; this$1.readyErrorCbs.forEach(function (cb) { cb(err); }); } }); }; History.prototype.confirmTransition = function confirmTransition (route, onComplete, onAbort) { var this$1 = this; var current = this.current; var abort = function (err) { if (isError(err)) { if (this$1.errorCbs.length) { this$1.errorCbs.forEach(function (cb) { cb(err); }); } else { warn(false, 'uncaught error during route navigation:'); console.error(err); } } onAbort && onAbort(err); }; if ( isSameRoute(route, current) && // in the case the route map has been dynamically appended to route.matched.length === current.matched.length ) { this.ensureURL(); return abort() } var ref = resolveQueue(this.current.matched, route.matched); var updated = ref.updated; var deactivated = ref.deactivated; var activated = ref.activated; var queue = [].concat( // in-component leave guards extractLeaveGuards(deactivated), // global before hooks this.router.beforeHooks, // in-component update hooks extractUpdateHooks(updated), // in-config enter guards activated.map(function (m) { return m.beforeEnter; }), // async components resolveAsyncComponents(activated) ); this.pending = route; var iterator = function (hook, next) { if (this$1.pending !== route) { return abort() } try { hook(route, current, function (to) { if (to === false || isError(to)) { // next(false) -> abort navigation, ensure current URL this$1.ensureURL(true); abort(to); } else if ( typeof to === 'string' || (typeof to === 'object' && ( typeof to.path === 'string' || typeof to.name === 'string' )) ) { // next('/') or next({ path: '/' }) -> redirect abort(); if (typeof to === 'object' && to.replace) { this$1.replace(to); } else { this$1.push(to); } } else { // confirm transition and pass on the value next(to); } }); } catch (e) { abort(e); } }; runQueue(queue, iterator, function () { var postEnterCbs = []; var isValid = function () { return this$1.current === route; }; // wait until async components are resolved before // extracting in-component enter guards var enterGuards = extractEnterGuards(activated, postEnterCbs, isValid); var queue = enterGuards.concat(this$1.router.resolveHooks); runQueue(queue, iterator, function () { if (this$1.pending !== route) { return abort() } this$1.pending = null; onComplete(route); if (this$1.router.app) { this$1.router.app.$nextTick(function () { postEnterCbs.forEach(function (cb) { cb(); }); }); } }); }); }; History.prototype.updateRoute = function updateRoute (route) { var prev = this.current; this.current = route; this.cb && this.cb(route); this.router.afterHooks.forEach(function (hook) { hook && hook(route, prev); }); }; function normalizeBase (base) { if (!base) { if (inBrowser) { // respect <base> tag var baseEl = document.querySelector('base'); base = (baseEl && baseEl.getAttribute('href')) || '/'; // strip full URL origin base = base.replace(/^https?:\/\/[^\/]+/, ''); } else { base = '/'; } } // make sure there's the starting slash if (base.charAt(0) !== '/') { base = '/' + base; } // remove trailing slash return base.replace(/\/$/, '') } function resolveQueue ( current, next ) { var i; var max = Math.max(current.length, next.length); for (i = 0; i < max; i++) { if (current[i] !== next[i]) { break } } return { updated: next.slice(0, i), activated: next.slice(i), deactivated: current.slice(i) } } function extractGuards ( records, name, bind, reverse ) { var guards = flatMapComponents(records, function (def, instance, match, key) { var guard = extractGuard(def, name); if (guard) { return Array.isArray(guard) ? guard.map(function (guard) { return bind(guard, instance, match, key); }) : bind(guard, instance, match, key) } }); return flatten(reverse ? guards.reverse() : guards) } function extractGuard ( def, key ) { if (typeof def !== 'function') { // extend now so that global mixins are applied. def = _Vue.extend(def); } return def.options[key] } function extractLeaveGuards (deactivated) { return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true) } function extractUpdateHooks (updated) { return extractGuards(updated, 'beforeRouteUpdate', bindGuard) } function bindGuard (guard, instance) { if (instance) { return function boundRouteGuard () { return guard.apply(instance, arguments) } } } function extractEnterGuards ( activated, cbs, isValid ) { return extractGuards(activated, 'beforeRouteEnter', function (guard, _, match, key) { return bindEnterGuard(guard, match, key, cbs, isValid) }) } function bindEnterGuard ( guard, match, key, cbs, isValid ) { return function routeEnterGuard (to, from, next) { return guard(to, from, function (cb) { next(cb); if (typeof cb === 'function') { cbs.push(function () { // #750 // if a router-view is wrapped with an out-in transition, // the instance may not have been registered at this time. // we will need to poll for registration until current route // is no longer valid. poll(cb, match.instances, key, isValid); }); } }) } } function poll ( cb, // somehow flow cannot infer this is a function instances, key, isValid ) { if ( instances[key] && !instances[key]._isBeingDestroyed // do not reuse being destroyed instance ) { cb(instances[key]); } else if (isValid()) { setTimeout(function () { poll(cb, instances, key, isValid); }, 16); } } /* */ var HTML5History = /*@__PURE__*/(function (History$$1) { function HTML5History (router, base) { var this$1 = this; History$$1.call(this, router, base); var expectScroll = router.options.scrollBehavior; var supportsScroll = supportsPushState && expectScroll; if (supportsScroll) { setupScroll(); } var initLocation = getLocation(this.base); window.addEventListener('popstate', function (e) { var current = this$1.current; // Avoiding first `popstate` event dispatched in some browsers but first // history route not updated since async guard at the same time. var location = getLocation(this$1.base); if (this$1.current === START && location === initLocation) { return } this$1.transitionTo(location, function (route) { if (supportsScroll) { handleScroll(router, route, current, true); } }); }); } if ( History$$1 ) HTML5History.__proto__ = History$$1; HTML5History.prototype = Object.create( History$$1 && History$$1.prototype ); HTML5History.prototype.constructor = HTML5History; HTML5History.prototype.go = function go (n) { window.history.go(n); }; HTML5History.prototype.push = function push (location, onComplete, onAbort) { var this$1 = this; var ref = this; var fromRoute = ref.current; this.transitionTo(location, function (route) { pushState(cleanPath(this$1.base + route.fullPath)); handleScroll(this$1.router, route, fromRoute, false); onComplete && onComplete(route); }, onAbort); }; HTML5History.prototype.replace = function replace (location, onComplete, onAbort) { var this$1 = this; var ref = this; var fromRoute = ref.current; this.transitionTo(location, function (route) { replaceState(cleanPath(this$1.base + route.fullPath)); handleScroll(this$1.router, route, fromRoute, false); onComplete && onComplete(route); }, onAbort); }; HTML5History.prototype.ensureURL = function ensureURL (push) { if (getLocation(this.base) !== this.current.fullPath) { var current = cleanPath(this.base + this.current.fullPath); push ? pushState(current) : replaceState(current); } }; HTML5History.prototype.getCurrentLocation = function getCurrentLocation () { return getLocation(this.base) }; return HTML5History; }(History)); function getLocation (base) { var path = decodeURI(window.location.pathname); if (base && path.indexOf(base) === 0) { path = path.slice(base.length); } return (path || '/') + window.location.search + window.location.hash } /* */ var HashHistory = /*@__PURE__*/(function (History$$1) { function HashHistory (router, base, fallback) { History$$1.call(this, router, base); // check history fallback deeplinking if (fallback && checkFallback(this.base)) { return } ensureSlash(); } if ( History$$1 ) HashHistory.__proto__ = History$$1; HashHistory.prototype = Object.create( History$$1 && History$$1.prototype ); HashHistory.prototype.constructor = HashHistory; // this is delayed until the app mounts // to avoid the hashchange listener being fired too early HashHistory.prototype.setupListeners = function setupListeners () { var this$1 = this; var router = this.router; var expectScroll = router.options.scrollBehavior; var supportsScroll = supportsPushState && expectScroll; if (supportsScroll) { setupScroll(); } window.addEventListener(supportsPushState ? 'popstate' : 'hashchange', function () { var current = this$1.current; if (!ensureSlash()) { return } this$1.transitionTo(getHash(), function (route) { if (supportsScroll) { handleScroll(this$1.router, route, current, true); } if (!supportsPushState) { replaceHash(route.fullPath); } }); }); }; HashHistory.prototype.push = function push (location, onComplete, onAbort) { var this$1 = this; var ref = this; var fromRoute = ref.current; this.transitionTo(location, function (route) { pushHash(route.fullPath); handleScroll(this$1.router, route, fromRoute, false); onComplete && onComplete(route); }, onAbort); }; HashHistory.prototype.replace = function replace (location, onComplete, onAbort) { var this$1 = this; var ref = this; var fromRoute = ref.current; this.transitionTo(location, function (route) { replaceHash(route.fullPath); handleScroll(this$1.router, route, fromRoute, false); onComplete && onComplete(route); }, onAbort); }; HashHistory.prototype.go = function go (n) { window.history.go(n); }; HashHistory.prototype.ensureURL = function ensureURL (push) { var current = this.current.fullPath; if (getHash() !== current) { push ? pushHash(current) : replaceHash(current); } }; HashHistory.prototype.getCurrentLocation = function getCurrentLocation () { return getHash() }; return HashHistory; }(History)); function checkFallback (base) { var location = getLocation(base); if (!/^\/#/.test(location)) { window.location.replace( cleanPath(base + '/#' + location) ); return true } } function ensureSlash () { var path = getHash(); if (path.charAt(0) === '/') { return true } replaceHash('/' + path); return false } function getHash () { // We can't use window.location.hash here because it's not // consistent across browsers - Firefox will pre-decode it! var href = window.location.href; var index = href.indexOf('#'); // empty path if (index < 0) { return '' } href = href.slice(index + 1); // decode the hash but not the search or hash // as search(query) is already decoded // https://github.com/vuejs/vue-router/issues/2708 var searchIndex = href.indexOf('?'); if (searchIndex < 0) { var hashIndex = href.indexOf('#'); if (hashIndex > -1) { href = decodeURI(href.slice(0, hashIndex)) + href.slice(hashIndex); } else { href = decodeURI(href); } } else { if (searchIndex > -1) { href = decodeURI(href.slice(0, searchIndex)) + href.slice(searchIndex); } } return href } function getUrl (path) { var href = window.location.href; var i = href.indexOf('#'); var base = i >= 0 ? href.slice(0, i) : href; return (base + "#" + path) } function pushHash (path) { if (supportsPushState) { pushState(getUrl(path)); } else { window.location.hash = path; } } function replaceHash (path) { if (supportsPushState) { replaceState(getUrl(path)); } else { window.location.replace(getUrl(path)); } } /* */ var AbstractHistory = /*@__PURE__*/(function (History$$1) { function AbstractHistory (router, base) { History$$1.call(this, router, base); this.stack = []; this.index = -1; } if ( History$$1 ) AbstractHistory.__proto__ = History$$1; AbstractHistory.prototype = Object.create( History$$1 && History$$1.prototype ); AbstractHistory.prototype.constructor = AbstractHistory; AbstractHistory.prototype.push = function push (location, onComplete, onAbort) { var this$1 = this; this.transitionTo(location, function (route) { this$1.stack = this$1.stack.slice(0, this$1.index + 1).concat(route); this$1.index++; onComplete && onComplete(route); }, onAbort); }; AbstractHistory.prototype.replace = function replace (location, onComplete, onAbort) { var this$1 = this; this.transitionTo(location, function (route) { this$1.stack = this$1.stack.slice(0, this$1.index).concat(route); onComplete && onComplete(route); }, onAbort); }; AbstractHistory.prototype.go = function go (n) { var this$1 = this; var targetIndex = this.index + n; if (targetIndex < 0 || targetIndex >= this.stack.length) { return } var route = this.stack[targetIndex]; this.confirmTransition(route, function () { this$1.index = targetIndex; this$1.updateRoute(route); }); }; AbstractHistory.prototype.getCurrentLocation = function getCurrentLocation () { var current = this.stack[this.stack.length - 1]; return current ? current.fullPath : '/' }; AbstractHistory.prototype.ensureURL = function ensureURL () { // noop }; return AbstractHistory; }(History)); /* */ var VueRouter = function VueRouter (options) { if ( options === void 0 ) options = {}; this.app = null; this.apps = []; this.options = options; this.beforeHooks = []; this.resolveHooks = []; this.afterHooks = []; this.matcher = createMatcher(options.routes || [], this); var mode = options.mode || 'hash'; this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false; if (this.fallback) { mode = 'hash'; } if (!inBrowser) { mode = 'abstract'; } this.mode = mode; switch (mode) { case 'history': this.history = new HTML5History(this, options.base); break case 'hash': this.history = new HashHistory(this, options.base, this.fallback); break case 'abstract': this.history = new AbstractHistory(this, options.base); break default: if (process.env.NODE_ENV !== 'production') { assert(false, ("invalid mode: " + mode)); } } }; var prototypeAccessors = { currentRoute: { configurable: true } }; VueRouter.prototype.match = function match ( raw, current, redirectedFrom ) { return this.matcher.match(raw, current, redirectedFrom) }; prototypeAccessors.currentRoute.get = function () { return this.history && this.history.current }; VueRouter.prototype.init = function init (app /* Vue component instance */) { var this$1 = this; process.env.NODE_ENV !== 'production' && assert( install.installed, "not installed. Make sure to call `Vue.use(VueRouter)` " + "before creating root instance." ); this.apps.push(app); // set up app destroyed handler // https://github.com/vuejs/vue-router/issues/2639 app.$once('hook:destroyed', function () { // clean out app from this.apps array once destroyed var index = this$1.apps.indexOf(app); if (index > -1) { this$1.apps.splice(index, 1); } // ensure we still have a main app or null if no apps // we do not release the router so it can be reused if (this$1.app === app) { this$1.app = this$1.apps[0] || null; } }); // main app previously initialized // return as we don't need to set up new history listener if (this.app) { return } this.app = app; var history = this.history; if (history instanceof HTML5History) { history.transitionTo(history.getCurrentLocation()); } else if (history instanceof HashHistory) { var setupHashListener = function () { history.setupListeners(); }; history.transitionTo( history.getCurrentLocation(), setupHashListener, setupHashListener ); } history.listen(function (route) { this$1.apps.forEach(function (app) { app._route = route; }); }); }; VueRouter.prototype.beforeEach = function beforeEach (fn) { return registerHook(this.beforeHooks, fn) }; VueRouter.prototype.beforeResolve = function beforeResolve (fn) { return registerHook(this.resolveHooks, fn) }; VueRouter.prototype.afterEach = function afterEach (fn) { return registerHook(this.afterHooks, fn) }; VueRouter.prototype.onReady = function onReady (cb, errorCb) { this.history.onReady(cb, errorCb); }; VueRouter.prototype.onError = function onError (errorCb) { this.history.onError(errorCb); }; VueRouter.prototype.push = function push (location, onComplete, onAbort) { this.history.push(location, onComplete, onAbort); }; VueRouter.prototype.replace = function replace (location, onComplete, onAbort) { this.history.replace(location, onComplete, onAbort); }; VueRouter.prototype.go = function go (n) { this.history.go(n); }; VueRouter.prototype.back = function back () { this.go(-1); }; VueRouter.prototype.forward = function forward () { this.go(1); }; VueRouter.prototype.getMatchedComponents = function getMatchedComponents (to) { var route = to ? to.matched ? to : this.resolve(to).route : this.currentRoute; if (!route) { return [] } return [].concat.apply([], route.matched.map(function (m) { return Object.keys(m.components).map(function (key) { return m.components[key] }) })) }; VueRouter.prototype.resolve = function resolve ( to, current, append ) { current = current || this.history.current; var location = normalizeLocation( to, current, append, this ); var route = this.match(location, current); var fullPath = route.redirectedFrom || route.fullPath; var base = this.history.base; var href = createHref(base, fullPath, this.mode); return { location: location, route: route, href: href, // for backwards compat normalizedTo: location, resolved: route } }; VueRouter.prototype.addRoutes = function addRoutes (routes) { this.matcher.addRoutes(routes); if (this.history.current !== START) { this.history.transitionTo(this.history.getCurrentLocation()); } }; Object.defineProperties( VueRouter.prototype, prototypeAccessors ); function registerHook (list, fn) { list.push(fn); return function () { var i = list.indexOf(fn); if (i > -1) { list.splice(i, 1); } } } function createHref (base, fullPath, mode) { var path = mode === 'hash' ? '#' + fullPath : fullPath; return base ? cleanPath(base + '/' + path) : path } VueRouter.install = install; VueRouter.version = '3.0.4'; if (inBrowser && window.Vue) { window.Vue.use(VueRouter); } export default VueRouter;
compileRouteRegex
attr_on_variant.rs
use funcmap::FuncMap; #[derive(FuncMap)] enum
<T> { #[funcmap] TestVariant(T), } fn main() {}
Test
abort_posix.go
// Copyright 2019 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // +build darwin linux package event import ( "os" "os/signal" "golang.org/x/sys/unix" ) func notifyOnAbort(c chan os.Signal)
{ signal.Notify(c, unix.SIGTERM, unix.SIGINT) }
Main.js
import React from 'react'; import {BrowserRouter as Router, Route} from 'react-router-dom' import MoviesList from './MoviesList' import CharactersList from './CharactersList' export default function Main() { return ( <div> <Router> <Route exact path='/interactive-react' component={MoviesList}/> <Route path='/interactive-react/:title/:date/:number' component={CharactersList}/> </Router>
}
</div> );
2020_day23.rs
use aoc::aoc_input::get_input; #[derive(Debug, Clone)] struct Game { cups: Vec<usize>, current: usize, } impl Game { fn new(cup_labels: &[usize]) -> Self { // Assumes cup_labels contains exactly all integers 1..=cup_labels.len() // Input is 1-based so pad with an extra [0] entry to avoid subtracting // 1 everywhere let mut cups = vec![0; cup_labels.len() + 1]; for w in cup_labels.windows(2) { cups[w[0]] = w[1]; } cups[*cup_labels.last().unwrap()] = cup_labels[0]; Self { cups, current: cup_labels[0], } } fn
(&self, label: usize) -> usize { if label == 1 { (self.cups.len() - 1) as usize } else { label - 1 } } fn do_move(&mut self) { let current = self.current; let n1 = self.cups[current]; let n2 = self.cups[n1]; let n3 = self.cups[n2]; let pickup = [n1, n2, n3]; let mut destination = self.next_destination(current); while pickup.contains(&destination) { destination = self.next_destination(destination); } let after_destination = self.cups[destination]; let after_pickup = self.cups[n3]; self.current = after_pickup; self.cups[current] = after_pickup; self.cups[destination] = n1; self.cups[n3] = after_destination; } fn do_moves(&mut self, count: usize) { for _i in 0..count { self.do_move(); } } fn labels_after_1(&self) -> String { let mut s = String::with_capacity(self.cups.len() - 2); let mut cur = self.cups[1]; while cur != 1 { s.push(std::char::from_digit(cur as u32, 10).unwrap()); cur = self.cups[cur]; } s } fn mul_two_labels_after_1(&self) -> usize { let a = self.cups[1]; let b = self.cups[a]; a * b } } fn parse_cups(input: &str) -> Vec<usize> { input .chars() .map(|c| c.to_digit(10).unwrap() as usize) .collect() } fn main() { let input = get_input(2020, 23); let orig_cups = parse_cups(input.trim()); let mut game = Game::new(orig_cups.as_slice()); game.do_moves(100); dbg!(game.labels_after_1()); let mut orig_cups = orig_cups; let start = *orig_cups.iter().max().unwrap() + 1; let range = start..start + 1_000_000 - orig_cups.len(); orig_cups.extend(range); assert_eq!(orig_cups.len(), 1_000_000); let mut game = Game::new(orig_cups.as_slice()); game.do_moves(10_000_000); dbg!(game.mul_two_labels_after_1()); } #[cfg(test)] mod tests { use std::assert_eq; use super::*; #[test] fn test_labels_after_1() { let input = "389125467"; let mut game = Game::new(parse_cups(&input).as_slice()); game.do_moves(100); assert_eq!(game.labels_after_1(), "67384529"); } }
next_destination
options_test.go
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package options import ( "net" "reflect" "testing" "time" "github.com/spf13/pflag" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/diff" apiserverconfig "k8s.io/apiserver/pkg/apis/config" apiserveroptions "k8s.io/apiserver/pkg/server/options" cmoptions "k8s.io/kubernetes/cmd/controller-manager/app/options" )
s, _ := NewCloudControllerManagerOptions() expected := &CloudControllerManagerOptions{ CloudProvider: &cmoptions.CloudProviderOptions{ Name: "", CloudConfigFile: "", }, Debugging: &cmoptions.DebuggingOptions{ EnableContentionProfiling: false, }, GenericComponent: &cmoptions.GenericComponentConfigOptions{ MinResyncPeriod: metav1.Duration{Duration: 12 * time.Hour}, ContentType: "application/vnd.kubernetes.protobuf", KubeAPIQPS: 20.0, KubeAPIBurst: 30, ControllerStartInterval: metav1.Duration{Duration: 0}, LeaderElection: apiserverconfig.LeaderElectionConfiguration{ ResourceLock: "endpoints", LeaderElect: true, LeaseDuration: metav1.Duration{Duration: 15 * time.Second}, RenewDeadline: metav1.Duration{Duration: 10 * time.Second}, RetryPeriod: metav1.Duration{Duration: 2 * time.Second}, }, }, KubeCloudShared: &cmoptions.KubeCloudSharedOptions{ Port: 10253, // Note: DeprecatedInsecureServingOptions.ApplyTo will write the flag value back into the component config Address: "0.0.0.0", // Note: DeprecatedInsecureServingOptions.ApplyTo will write the flag value back into the component config RouteReconciliationPeriod: metav1.Duration{Duration: 10 * time.Second}, NodeMonitorPeriod: metav1.Duration{Duration: 5 * time.Second}, ClusterName: "kubernetes", ClusterCIDR: "", AllocateNodeCIDRs: false, CIDRAllocatorType: "", ConfigureCloudRoutes: true, }, ServiceController: &cmoptions.ServiceControllerOptions{ ConcurrentServiceSyncs: 1, }, SecureServing: &apiserveroptions.SecureServingOptions{ BindPort: 0, BindAddress: net.ParseIP("0.0.0.0"), ServerCert: apiserveroptions.GeneratableKeyCert{ CertDirectory: "/var/run/kubernetes", PairName: "cloud-controller-manager", }, HTTP2MaxStreamsPerConnection: 0, }, InsecureServing: &apiserveroptions.DeprecatedInsecureServingOptions{ BindAddress: net.ParseIP("0.0.0.0"), BindPort: int(10253), BindNetwork: "tcp", }, Kubeconfig: "", Master: "", NodeStatusUpdateFrequency: metav1.Duration{Duration: 5 * time.Minute}, } if !reflect.DeepEqual(expected, s) { t.Errorf("Got different run options than expected.\nDifference detected on:\n%s", diff.ObjectReflectDiff(expected, s)) } } func TestAddFlags(t *testing.T) { f := pflag.NewFlagSet("addflagstest", pflag.ContinueOnError) s, _ := NewCloudControllerManagerOptions() s.AddFlags(f) args := []string{ "--address=192.168.4.10", "--allocate-node-cidrs=true", "--bind-address=192.168.4.21", "--cert-dir=/a/b/c", "--cloud-config=/cloud-config", "--cloud-provider=gce", "--cluster-cidr=1.2.3.4/24", "--cluster-name=k8s", "--configure-cloud-routes=false", "--contention-profiling=true", "--controller-start-interval=2m", "--http2-max-streams-per-connection=47", "--kube-api-burst=100", "--kube-api-content-type=application/vnd.kubernetes.protobuf", "--kube-api-qps=50.0", "--kubeconfig=/kubeconfig", "--leader-elect=false", "--leader-elect-lease-duration=30s", "--leader-elect-renew-deadline=15s", "--leader-elect-resource-lock=configmap", "--leader-elect-retry-period=5s", "--master=192.168.4.20", "--min-resync-period=100m", "--node-status-update-frequency=10m", "--port=10000", "--profiling=false", "--route-reconciliation-period=30s", "--secure-port=10001", "--use-service-account-credentials=false", } f.Parse(args) expected := &CloudControllerManagerOptions{ CloudProvider: &cmoptions.CloudProviderOptions{ Name: "gce", CloudConfigFile: "/cloud-config", }, Debugging: &cmoptions.DebuggingOptions{ EnableContentionProfiling: true, }, GenericComponent: &cmoptions.GenericComponentConfigOptions{ MinResyncPeriod: metav1.Duration{Duration: 100 * time.Minute}, ContentType: "application/vnd.kubernetes.protobuf", KubeAPIQPS: 50.0, KubeAPIBurst: 100, ControllerStartInterval: metav1.Duration{Duration: 2 * time.Minute}, LeaderElection: apiserverconfig.LeaderElectionConfiguration{ ResourceLock: "configmap", LeaderElect: false, LeaseDuration: metav1.Duration{Duration: 30 * time.Second}, RenewDeadline: metav1.Duration{Duration: 15 * time.Second}, RetryPeriod: metav1.Duration{Duration: 5 * time.Second}, }, }, KubeCloudShared: &cmoptions.KubeCloudSharedOptions{ Port: 10253, // Note: DeprecatedInsecureServingOptions.ApplyTo will write the flag value back into the component config Address: "0.0.0.0", // Note: DeprecatedInsecureServingOptions.ApplyTo will write the flag value back into the component config RouteReconciliationPeriod: metav1.Duration{Duration: 30 * time.Second}, NodeMonitorPeriod: metav1.Duration{Duration: 5 * time.Second}, ClusterName: "k8s", ClusterCIDR: "1.2.3.4/24", AllocateNodeCIDRs: true, CIDRAllocatorType: "RangeAllocator", ConfigureCloudRoutes: false, }, ServiceController: &cmoptions.ServiceControllerOptions{ ConcurrentServiceSyncs: 1, }, SecureServing: &apiserveroptions.SecureServingOptions{ BindPort: 10001, BindAddress: net.ParseIP("192.168.4.21"), ServerCert: apiserveroptions.GeneratableKeyCert{ CertDirectory: "/a/b/c", PairName: "cloud-controller-manager", }, HTTP2MaxStreamsPerConnection: 47, }, InsecureServing: &apiserveroptions.DeprecatedInsecureServingOptions{ BindAddress: net.ParseIP("192.168.4.10"), BindPort: int(10000), BindNetwork: "tcp", }, Kubeconfig: "/kubeconfig", Master: "192.168.4.20", NodeStatusUpdateFrequency: metav1.Duration{Duration: 10 * time.Minute}, } if !reflect.DeepEqual(expected, s) { t.Errorf("Got different run options than expected.\nDifference detected on:\n%s", diff.ObjectReflectDiff(expected, s)) } }
func TestDefaultFlags(t *testing.T) {
simple.go
// Copyright 2016 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package executor import ( "context" "fmt" "strings" "github.com/pingcap/errors" "github.com/pingcap/parser/ast" "github.com/pingcap/parser/auth" "github.com/pingcap/parser/model" "github.com/pingcap/parser/mysql" "github.com/pingcap/parser/terror" "github.com/pingcap/tidb/config" "github.com/pingcap/tidb/domain" "github.com/pingcap/tidb/infoschema" "github.com/pingcap/tidb/plugin" "github.com/pingcap/tidb/privilege" "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/util/chunk" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/sqlexec" "go.uber.org/zap" ) // SimpleExec represents simple statement executor. // For statements do simple execution. // includes `UseStmt`, 'SetStmt`, `DoStmt`, // `BeginStmt`, `CommitStmt`, `RollbackStmt`. // TODO: list all simple statements. type SimpleExec struct { baseExecutor Statement ast.StmtNode done bool is infoschema.InfoSchema } // Next implements the Executor Next interface. func (e *SimpleExec) Next(ctx context.Context, req *chunk.RecordBatch) (err error) { if e.done { return nil } switch x := e.Statement.(type) { case *ast.GrantRoleStmt: err = e.executeGrantRole(x) case *ast.UseStmt: err = e.executeUse(x) case *ast.FlushStmt: err = e.executeFlush(x) case *ast.BeginStmt: err = e.executeBegin(ctx, x) case *ast.CommitStmt: e.executeCommit(x) case *ast.RollbackStmt: err = e.executeRollback(x) case *ast.CreateUserStmt: err = e.executeCreateUser(x) case *ast.AlterUserStmt: err = e.executeAlterUser(x) case *ast.DropUserStmt: err = e.executeDropUser(x) case *ast.SetPwdStmt: err = e.executeSetPwd(x) case *ast.KillStmt: err = e.executeKillStmt(x) case *ast.BinlogStmt: // We just ignore it. return nil case *ast.DropStatsStmt: err = e.executeDropStats(x) case *ast.SetRoleStmt: err = e.executeSetRole(x) case *ast.RevokeRoleStmt: err = e.executeRevokeRole(x) case *ast.SetDefaultRoleStmt: err = e.executeSetDefaultRole(x) } e.done = true return err } func (e *SimpleExec) setDefaultRoleNone(s *ast.SetDefaultRoleStmt) error { sqlExecutor := e.ctx.(sqlexec.SQLExecutor) if _, err := sqlExecutor.Execute(context.Background(), "begin"); err != nil { return err } for _, u := range s.UserList { if u.Hostname == "" { u.Hostname = "%" } sql := fmt.Sprintf("DELETE IGNORE FROM mysql.default_roles WHERE USER='%s' AND HOST='%s';", u.Username, u.Hostname) if _, err := sqlExecutor.Execute(context.Background(), sql); err != nil { logutil.Logger(context.Background()).Error(fmt.Sprintf("Error occur when executing %s", sql)) if _, rollbackErr := sqlExecutor.Execute(context.Background(), "rollback"); rollbackErr != nil { return rollbackErr } return err } } if _, err := sqlExecutor.Execute(context.Background(), "commit"); err != nil { return err } return nil } func (e *SimpleExec) setDefaultRoleRegular(s *ast.SetDefaultRoleStmt) error { for _, user := range s.UserList { exists, err := userExists(e.ctx, user.Username, user.Hostname) if err != nil { return err } if !exists { return ErrCannotUser.GenWithStackByArgs("SET DEFAULT ROLE", user.String()) } } for _, role := range s.RoleList { exists, err := userExists(e.ctx, role.Username, role.Hostname) if err != nil { return err } if !exists { return ErrCannotUser.GenWithStackByArgs("SET DEFAULT ROLE", role.String()) } } sqlExecutor := e.ctx.(sqlexec.SQLExecutor) if _, err := sqlExecutor.Execute(context.Background(), "begin"); err != nil { return err } for _, user := range s.UserList { if user.Hostname == "" { user.Hostname = "%" } sql := fmt.Sprintf("DELETE IGNORE FROM mysql.default_roles WHERE USER='%s' AND HOST='%s';", user.Username, user.Hostname) if _, err := sqlExecutor.Execute(context.Background(), sql); err != nil { logutil.Logger(context.Background()).Error(fmt.Sprintf("Error occur when executing %s", sql)) if _, rollbackErr := sqlExecutor.Execute(context.Background(), "rollback"); rollbackErr != nil { return rollbackErr } return err } for _, role := range s.RoleList { sql := fmt.Sprintf("INSERT IGNORE INTO mysql.default_roles values('%s', '%s', '%s', '%s');", user.Hostname, user.Username, role.Hostname, role.Username) checker := privilege.GetPrivilegeManager(e.ctx) ok := checker.FindEdge(e.ctx, role, user) if ok { if _, err := sqlExecutor.Execute(context.Background(), sql); err != nil { logutil.Logger(context.Background()).Error(fmt.Sprintf("Error occur when executing %s", sql)) if _, rollbackErr := sqlExecutor.Execute(context.Background(), "rollback"); rollbackErr != nil { return rollbackErr } return err } } else { if _, rollbackErr := sqlExecutor.Execute(context.Background(), "rollback"); rollbackErr != nil { return rollbackErr } return ErrRoleNotGranted.GenWithStackByArgs(role.String(), user.String()) } } } if _, err := sqlExecutor.Execute(context.Background(), "commit"); err != nil { return err } return nil } func (e *SimpleExec) setDefaultRoleAll(s *ast.SetDefaultRoleStmt) error { for _, user := range s.UserList { exists, err := userExists(e.ctx, user.Username, user.Hostname) if err != nil { return err } if !exists { return ErrCannotUser.GenWithStackByArgs("SET DEFAULT ROLE", user.String()) } } sqlExecutor := e.ctx.(sqlexec.SQLExecutor) if _, err := sqlExecutor.Execute(context.Background(), "begin"); err != nil { return err } for _, user := range s.UserList { if user.Hostname == "" { user.Hostname = "%" } sql := fmt.Sprintf("DELETE IGNORE FROM mysql.default_roles WHERE USER='%s' AND HOST='%s';", user.Username, user.Hostname) if _, err := sqlExecutor.Execute(context.Background(), sql); err != nil { logutil.Logger(context.Background()).Error(fmt.Sprintf("Error occur when executing %s", sql)) if _, rollbackErr := sqlExecutor.Execute(context.Background(), "rollback"); rollbackErr != nil { return rollbackErr } return err } sql = fmt.Sprintf("INSERT IGNORE INTO mysql.default_roles(HOST,USER,DEFAULT_ROLE_HOST,DEFAULT_ROLE_USER) "+ "SELECT TO_HOST,TO_USER,FROM_HOST,FROM_USER FROM mysql.role_edges WHERE TO_HOST='%s' AND TO_USER='%s';", user.Hostname, user.Username) if _, err := sqlExecutor.Execute(context.Background(), sql); err != nil { if _, rollbackErr := sqlExecutor.Execute(context.Background(), "rollback"); rollbackErr != nil { return rollbackErr } return err } } if _, err := sqlExecutor.Execute(context.Background(), "commit"); err != nil { return err } return nil } func (e *SimpleExec) executeSetDefaultRole(s *ast.SetDefaultRoleStmt) error { switch s.SetRoleOpt { case ast.SetRoleAll: return e.setDefaultRoleAll(s) case ast.SetRoleNone: return e.setDefaultRoleNone(s) case ast.SetRoleRegular: return e.setDefaultRoleRegular(s) } err := domain.GetDomain(e.ctx).PrivilegeHandle().Update(e.ctx.(sessionctx.Context)) return err } func (e *SimpleExec) setRoleRegular(s *ast.SetRoleStmt) error { // Deal with SQL like `SET ROLE role1, role2;` checkDup := make(map[string]*auth.RoleIdentity, len(s.RoleList)) // Check whether RoleNameList contain duplicate role name. for _, r := range s.RoleList { key := r.String() checkDup[key] = r } roleList := make([]*auth.RoleIdentity, 0, 10) for _, v := range checkDup { roleList = append(roleList, v) } checker := privilege.GetPrivilegeManager(e.ctx) ok, roleName := checker.ActiveRoles(e.ctx, roleList) if !ok { u := e.ctx.GetSessionVars().User return ErrRoleNotGranted.GenWithStackByArgs(roleName, u.String()) } return nil } func (e *SimpleExec) setRoleAll(s *ast.SetRoleStmt) error { // Deal with SQL like `SET ROLE ALL;` checker := privilege.GetPrivilegeManager(e.ctx) user, host := e.ctx.GetSessionVars().User.AuthUsername, e.ctx.GetSessionVars().User.AuthHostname roles := checker.GetAllRoles(user, host) ok, roleName := checker.ActiveRoles(e.ctx, roles) if !ok { u := e.ctx.GetSessionVars().User return ErrRoleNotGranted.GenWithStackByArgs(roleName, u.String()) } return nil } func (e *SimpleExec) setRoleAllExcept(s *ast.SetRoleStmt) error { // Deal with SQL like `SET ROLE ALL EXCEPT role1, role2;` for _, r := range s.RoleList { if r.Hostname == "" { r.Hostname = "%" } } checker := privilege.GetPrivilegeManager(e.ctx) user, host := e.ctx.GetSessionVars().User.AuthUsername, e.ctx.GetSessionVars().User.AuthHostname roles := checker.GetAllRoles(user, host) filter := func(arr []*auth.RoleIdentity, f func(*auth.RoleIdentity) bool) []*auth.RoleIdentity { i, j := 0, 0 for i = 0; i < len(arr); i++ { if f(arr[i]) { arr[j] = arr[i] j++ } } return arr[:j] } banned := func(r *auth.RoleIdentity) bool { for _, ban := range s.RoleList { if ban.Hostname == r.Hostname && ban.Username == r.Username { return false } } return true } afterExcept := filter(roles, banned) ok, roleName := checker.ActiveRoles(e.ctx, afterExcept) if !ok { u := e.ctx.GetSessionVars().User return ErrRoleNotGranted.GenWithStackByArgs(roleName, u.String()) } return nil } func (e *SimpleExec) setRoleDefault(s *ast.SetRoleStmt) error { // Deal with SQL like `SET ROLE DEFAULT;` checker := privilege.GetPrivilegeManager(e.ctx) user, host := e.ctx.GetSessionVars().User.AuthUsername, e.ctx.GetSessionVars().User.AuthHostname roles := checker.GetDefaultRoles(user, host) ok, roleName := checker.ActiveRoles(e.ctx, roles) if !ok { u := e.ctx.GetSessionVars().User return ErrRoleNotGranted.GenWithStackByArgs(roleName, u.String()) } return nil } func (e *SimpleExec) setRoleNone(s *ast.SetRoleStmt) error { // Deal with SQL like `SET ROLE NONE;` checker := privilege.GetPrivilegeManager(e.ctx) roles := make([]*auth.RoleIdentity, 0) ok, roleName := checker.ActiveRoles(e.ctx, roles) if !ok { u := e.ctx.GetSessionVars().User return ErrRoleNotGranted.GenWithStackByArgs(roleName, u.String()) } return nil } func (e *SimpleExec) executeSetRole(s *ast.SetRoleStmt) error { switch s.SetRoleOpt { case ast.SetRoleRegular: return e.setRoleRegular(s) case ast.SetRoleAll: return e.setRoleAll(s) case ast.SetRoleAllExcept: return e.setRoleAllExcept(s) case ast.SetRoleNone: return e.setRoleNone(s) case ast.SetRoleDefault: return e.setRoleDefault(s) } return nil } func (e *SimpleExec) dbAccessDenied(dbname string) error { user := e.ctx.GetSessionVars().User u := user.Username h := user.Hostname if len(user.AuthUsername) > 0 && len(user.AuthHostname) > 0 { u = user.AuthUsername h = user.AuthHostname } return ErrDBaccessDenied.GenWithStackByArgs(u, h, dbname) } func (e *SimpleExec) executeUse(s *ast.UseStmt) error { dbname := model.NewCIStr(s.DBName) checker := privilege.GetPrivilegeManager(e.ctx) if checker != nil && e.ctx.GetSessionVars().User != nil { if !checker.DBIsVisible(e.ctx.GetSessionVars().ActiveRoles, dbname.String()) { return e.dbAccessDenied(dbname.O) } } dbinfo, exists := e.is.SchemaByName(dbname) if !exists { return infoschema.ErrDatabaseNotExists.GenWithStackByArgs(dbname) } e.ctx.GetSessionVars().CurrentDB = dbname.O // character_set_database is the character set used by the default database. // The server sets this variable whenever the default database changes. // See http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_character_set_database sessionVars := e.ctx.GetSessionVars() terror.Log(sessionVars.SetSystemVar(variable.CharsetDatabase, dbinfo.Charset)) terror.Log(sessionVars.SetSystemVar(variable.CollationDatabase, dbinfo.Collate)) return nil } func (e *SimpleExec) executeBegin(ctx context.Context, s *ast.BeginStmt) error { // If BEGIN is the first statement in TxnCtx, we can reuse the existing transaction, without the // need to call NewTxn, which commits the existing transaction and begins a new one. txnCtx := e.ctx.GetSessionVars().TxnCtx if txnCtx.History != nil { err := e.ctx.NewTxn(ctx) if err != nil { return err } } // With START TRANSACTION, autocommit remains disabled until you end // the transaction with COMMIT or ROLLBACK. The autocommit mode then
return err } return nil } func (e *SimpleExec) executeRevokeRole(s *ast.RevokeRoleStmt) error { for _, role := range s.Roles { exists, err := userExists(e.ctx, role.Username, role.Hostname) if err != nil { return errors.Trace(err) } if !exists { return ErrCannotUser.GenWithStackByArgs("REVOKE ROLE", role.String()) } } // begin a transaction to insert role graph edges. if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "begin"); err != nil { return errors.Trace(err) } for _, user := range s.Users { exists, err := userExists(e.ctx, user.Username, user.Hostname) if err != nil { return errors.Trace(err) } if !exists { if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "rollback"); err != nil { return errors.Trace(err) } return ErrCannotUser.GenWithStackByArgs("REVOKE ROLE", user.String()) } for _, role := range s.Roles { if role.Hostname == "" { role.Hostname = "%" } sql := fmt.Sprintf(`DELETE IGNORE FROM %s.%s WHERE FROM_HOST='%s' and FROM_USER='%s' and TO_HOST='%s' and TO_USER='%s'`, mysql.SystemDB, mysql.RoleEdgeTable, role.Hostname, role.Username, user.Hostname, user.Username) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), sql); err != nil { if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "rollback"); err != nil { return errors.Trace(err) } return ErrCannotUser.GenWithStackByArgs("REVOKE ROLE", role.String()) } } } if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "commit"); err != nil { return err } err := domain.GetDomain(e.ctx).PrivilegeHandle().Update(e.ctx.(sessionctx.Context)) return errors.Trace(err) } func (e *SimpleExec) executeCommit(s *ast.CommitStmt) { e.ctx.GetSessionVars().SetStatusFlag(mysql.ServerStatusInTrans, false) } func (e *SimpleExec) executeRollback(s *ast.RollbackStmt) error { sessVars := e.ctx.GetSessionVars() logutil.Logger(context.Background()).Debug("execute rollback statement", zap.Uint64("conn", sessVars.ConnectionID)) sessVars.SetStatusFlag(mysql.ServerStatusInTrans, false) txn, err := e.ctx.Txn(true) if err != nil { return err } if txn.Valid() { e.ctx.GetSessionVars().TxnCtx.ClearDelta() return txn.Rollback() } return nil } func (e *SimpleExec) executeCreateUser(s *ast.CreateUserStmt) error { users := make([]string, 0, len(s.Specs)) for _, spec := range s.Specs { exists, err1 := userExists(e.ctx, spec.User.Username, spec.User.Hostname) if err1 != nil { return err1 } if exists { if !s.IfNotExists { return errors.New("Duplicate user") } continue } pwd, ok := spec.EncodedPassword() if !ok { return errors.Trace(ErrPasswordFormat) } user := fmt.Sprintf(`('%s', '%s', '%s')`, spec.User.Hostname, spec.User.Username, pwd) if s.IsCreateRole { user = fmt.Sprintf(`('%s', '%s', '%s', 'Y')`, spec.User.Hostname, spec.User.Username, pwd) } users = append(users, user) } if len(users) == 0 { return nil } sql := fmt.Sprintf(`INSERT INTO %s.%s (Host, User, Password) VALUES %s;`, mysql.SystemDB, mysql.UserTable, strings.Join(users, ", ")) if s.IsCreateRole { sql = fmt.Sprintf(`INSERT INTO %s.%s (Host, User, Password, Account_locked) VALUES %s;`, mysql.SystemDB, mysql.UserTable, strings.Join(users, ", ")) } _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), sql) if err != nil { return err } domain.GetDomain(e.ctx).NotifyUpdatePrivilege(e.ctx) return err } func (e *SimpleExec) executeAlterUser(s *ast.AlterUserStmt) error { if s.CurrentAuth != nil { user := e.ctx.GetSessionVars().User if user == nil { return errors.New("Session user is empty") } spec := &ast.UserSpec{ User: user, AuthOpt: s.CurrentAuth, } s.Specs = []*ast.UserSpec{spec} } failedUsers := make([]string, 0, len(s.Specs)) for _, spec := range s.Specs { exists, err := userExists(e.ctx, spec.User.Username, spec.User.Hostname) if err != nil { return err } if !exists { failedUsers = append(failedUsers, spec.User.String()) // TODO: Make this error as a warning. // if s.IfExists { // } continue } pwd := "" if spec.AuthOpt != nil { if spec.AuthOpt.ByAuthString { pwd = auth.EncodePassword(spec.AuthOpt.AuthString) } else { pwd = auth.EncodePassword(spec.AuthOpt.HashString) } } sql := fmt.Sprintf(`UPDATE %s.%s SET Password = '%s' WHERE Host = '%s' and User = '%s';`, mysql.SystemDB, mysql.UserTable, pwd, spec.User.Hostname, spec.User.Username) _, _, err = e.ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(e.ctx, sql) if err != nil { failedUsers = append(failedUsers, spec.User.String()) } } if len(failedUsers) > 0 { // Commit the transaction even if we returns error txn, err := e.ctx.Txn(true) if err != nil { return err } err = txn.Commit(sessionctx.SetCommitCtx(context.Background(), e.ctx)) if err != nil { return err } return ErrCannotUser.GenWithStackByArgs("ALTER USER", strings.Join(failedUsers, ",")) } domain.GetDomain(e.ctx).NotifyUpdatePrivilege(e.ctx) return nil } func (e *SimpleExec) executeGrantRole(s *ast.GrantRoleStmt) error { failedUsers := make([]string, 0, len(s.Users)) for _, role := range s.Roles { exists, err := userExists(e.ctx, role.Username, role.Hostname) if err != nil { return err } if !exists { return ErrCannotUser.GenWithStackByArgs("GRANT ROLE", role.String()) } } for _, user := range s.Users { exists, err := userExists(e.ctx, user.Username, user.Hostname) if err != nil { return err } if !exists { return ErrCannotUser.GenWithStackByArgs("GRANT ROLE", user.String()) } } // begin a transaction to insert role graph edges. if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "begin"); err != nil { return err } for _, user := range s.Users { for _, role := range s.Roles { sql := fmt.Sprintf(`INSERT IGNORE INTO %s.%s (FROM_HOST, FROM_USER, TO_HOST, TO_USER) VALUES ('%s','%s','%s','%s')`, mysql.SystemDB, mysql.RoleEdgeTable, role.Hostname, role.Username, user.Hostname, user.Username) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), sql); err != nil { failedUsers = append(failedUsers, user.String()) logutil.Logger(context.Background()).Error(fmt.Sprintf("Error occur when executing %s", sql)) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "rollback"); err != nil { return err } return ErrCannotUser.GenWithStackByArgs("GRANT ROLE", user.String()) } } } if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "commit"); err != nil { return err } err := domain.GetDomain(e.ctx).PrivilegeHandle().Update(e.ctx.(sessionctx.Context)) return err } func (e *SimpleExec) executeDropUser(s *ast.DropUserStmt) error { failedUsers := make([]string, 0, len(s.UserList)) for _, user := range s.UserList { exists, err := userExists(e.ctx, user.Username, user.Hostname) if err != nil { return err } if !exists { if !s.IfExists { failedUsers = append(failedUsers, user.String()) } continue } // begin a transaction to delete a user. if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "begin"); err != nil { return err } sql := fmt.Sprintf(`DELETE FROM %s.%s WHERE Host = '%s' and User = '%s';`, mysql.SystemDB, mysql.UserTable, user.Hostname, user.Username) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), sql); err != nil { failedUsers = append(failedUsers, user.String()) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "rollback"); err != nil { return err } continue } // delete privileges from mysql.db sql = fmt.Sprintf(`DELETE FROM %s.%s WHERE Host = '%s' and User = '%s';`, mysql.SystemDB, mysql.DBTable, user.Hostname, user.Username) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), sql); err != nil { failedUsers = append(failedUsers, user.String()) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "rollback"); err != nil { return err } continue } // delete privileges from mysql.tables_priv sql = fmt.Sprintf(`DELETE FROM %s.%s WHERE Host = '%s' and User = '%s';`, mysql.SystemDB, mysql.TablePrivTable, user.Hostname, user.Username) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), sql); err != nil { failedUsers = append(failedUsers, user.String()) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "rollback"); err != nil { return err } continue } // delete relationship from mysql.role_edges sql = fmt.Sprintf(`DELETE FROM %s.%s WHERE TO_HOST = '%s' and TO_USER = '%s';`, mysql.SystemDB, mysql.RoleEdgeTable, user.Hostname, user.Username) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), sql); err != nil { failedUsers = append(failedUsers, user.String()) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "rollback"); err != nil { return err } continue } sql = fmt.Sprintf(`DELETE FROM %s.%s WHERE FROM_HOST = '%s' and FROM_USER = '%s';`, mysql.SystemDB, mysql.RoleEdgeTable, user.Hostname, user.Username) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), sql); err != nil { failedUsers = append(failedUsers, user.String()) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "rollback"); err != nil { return err } continue } // delete relationship from mysql.default_roles sql = fmt.Sprintf(`DELETE FROM %s.%s WHERE DEFAULT_ROLE_HOST = '%s' and DEFAULT_ROLE_USER = '%s';`, mysql.SystemDB, mysql.DefaultRoleTable, user.Hostname, user.Username) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), sql); err != nil { failedUsers = append(failedUsers, user.String()) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "rollback"); err != nil { return err } continue } sql = fmt.Sprintf(`DELETE FROM %s.%s WHERE HOST = '%s' and USER = '%s';`, mysql.SystemDB, mysql.DefaultRoleTable, user.Hostname, user.Username) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), sql); err != nil { failedUsers = append(failedUsers, user.String()) if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "rollback"); err != nil { return err } continue } //TODO: need delete columns_priv once we implement columns_priv functionality. if _, err := e.ctx.(sqlexec.SQLExecutor).Execute(context.Background(), "commit"); err != nil { failedUsers = append(failedUsers, user.String()) } } if len(failedUsers) > 0 { return ErrCannotUser.GenWithStackByArgs("DROP USER", strings.Join(failedUsers, ",")) } domain.GetDomain(e.ctx).NotifyUpdatePrivilege(e.ctx) return nil } func userExists(ctx sessionctx.Context, name string, host string) (bool, error) { sql := fmt.Sprintf(`SELECT * FROM %s.%s WHERE User='%s' AND Host='%s';`, mysql.SystemDB, mysql.UserTable, name, host) rows, _, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(ctx, sql) if err != nil { return false, err } return len(rows) > 0, nil } func (e *SimpleExec) executeSetPwd(s *ast.SetPwdStmt) error { var u, h string if s.User == nil { if e.ctx.GetSessionVars().User == nil { return errors.New("Session error is empty") } u = e.ctx.GetSessionVars().User.AuthUsername h = e.ctx.GetSessionVars().User.AuthHostname } else { checker := privilege.GetPrivilegeManager(e.ctx) activeRoles := e.ctx.GetSessionVars().ActiveRoles if checker != nil && !checker.RequestVerification(activeRoles, "", "", "", mysql.SuperPriv) { return ErrDBaccessDenied.GenWithStackByArgs(u, h, "mysql") } u = s.User.Username h = s.User.Hostname } exists, err := userExists(e.ctx, u, h) if err != nil { return err } if !exists { return errors.Trace(ErrPasswordNoMatch) } // update mysql.user sql := fmt.Sprintf(`UPDATE %s.%s SET password='%s' WHERE User='%s' AND Host='%s';`, mysql.SystemDB, mysql.UserTable, auth.EncodePassword(s.Password), u, h) _, _, err = e.ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(e.ctx, sql) domain.GetDomain(e.ctx).NotifyUpdatePrivilege(e.ctx) return err } func (e *SimpleExec) executeKillStmt(s *ast.KillStmt) error { conf := config.GetGlobalConfig() if s.TiDBExtension || conf.CompatibleKillQuery { sm := e.ctx.GetSessionManager() if sm == nil { return nil } sm.Kill(s.ConnectionID, s.Query) } else { err := errors.New("Invalid operation. Please use 'KILL TIDB [CONNECTION | QUERY] connectionID' instead") e.ctx.GetSessionVars().StmtCtx.AppendWarning(err) } return nil } func (e *SimpleExec) executeFlush(s *ast.FlushStmt) error { switch s.Tp { case ast.FlushTables: if s.ReadLock { return errors.New("FLUSH TABLES WITH READ LOCK is not supported. Please use @@tidb_snapshot") } case ast.FlushPrivileges: dom := domain.GetDomain(e.ctx) sysSessionPool := dom.SysSessionPool() ctx, err := sysSessionPool.Get() if err != nil { return err } defer sysSessionPool.Put(ctx) err = dom.PrivilegeHandle().Update(ctx.(sessionctx.Context)) return err case ast.FlushTiDBPlugin: dom := domain.GetDomain(e.ctx) for _, pluginName := range s.Plugins { err := plugin.NotifyFlush(dom, pluginName) if err != nil { return err } } } return nil } func (e *SimpleExec) executeDropStats(s *ast.DropStatsStmt) error { h := domain.GetDomain(e.ctx).StatsHandle() err := h.DeleteTableStatsFromKV(s.Table.TableInfo.ID) if err != nil { return err } return h.Update(GetInfoSchema(e.ctx)) }
// reverts to its previous state. e.ctx.GetSessionVars().SetStatusFlag(mysql.ServerStatusInTrans, true) // Call ctx.Txn(true) to active pending txn. if _, err := e.ctx.Txn(true); err != nil {
executor.py
from __future__ import unicode_literals from django.apps.registry import apps as global_apps from django.db import migrations from .exceptions import InvalidMigrationPlan from .loader import MigrationLoader from .recorder import MigrationRecorder from .state import ProjectState class MigrationExecutor(object): """ End-to-end migration execution - loads migrations, and runs them up or down to a specified set of targets. """ def __init__(self, connection, progress_callback=None): self.connection = connection self.loader = MigrationLoader(self.connection) self.recorder = MigrationRecorder(self.connection) self.progress_callback = progress_callback def migration_plan(self, targets, clean_start=False): """ Given a set of targets, returns a list of (Migration instance, backwards?). """ plan = [] if clean_start: applied = set() else: applied = set(self.loader.applied_migrations) for target in targets: # If the target is (app_label, None), that means unmigrate everything if target[1] is None: for root in self.loader.graph.root_nodes(): if root[0] == target[0]: for migration in self.loader.graph.backwards_plan(root): if migration in applied: plan.append((self.loader.graph.nodes[migration], True)) applied.remove(migration) # If the migration is already applied, do backwards mode, # otherwise do forwards mode. elif target in applied: # Don't migrate backwards all the way to the target node (that # may roll back dependencies in other apps that don't need to # be rolled back); instead roll back through target's immediate # child(ren) in the same app, and no further. next_in_app = sorted( n for n in self.loader.graph.node_map[target].children if n[0] == target[0] ) for node in next_in_app: for migration in self.loader.graph.backwards_plan(node): if migration in applied: plan.append((self.loader.graph.nodes[migration], True)) applied.remove(migration) else: for migration in self.loader.graph.forwards_plan(target): if migration not in applied: plan.append((self.loader.graph.nodes[migration], False)) applied.add(migration) return plan def migrate(self, targets, plan=None, fake=False, fake_initial=False): """ Migrates the database up to the given targets. Django first needs to create all project states before a migration is (un)applied and in a second step run all the database operations. """ if plan is None: plan = self.migration_plan(targets) # Create the forwards plan Django would follow on an empty database full_plan = self.migration_plan(self.loader.graph.leaf_nodes(), clean_start=True) all_forwards = all(not backwards for mig, backwards in plan) all_backwards = all(backwards for mig, backwards in plan) if not plan: pass # Nothing to do for an empty plan elif all_forwards == all_backwards: # This should only happen if there's a mixed plan raise InvalidMigrationPlan( "Migration plans with both forwards and backwards migrations " "are not supported. Please split your migration process into " "separate plans of only forwards OR backwards migrations.", plan ) elif all_forwards: self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) else: # No need to check for `elif all_backwards` here, as that condition # would always evaluate to true. self._migrate_all_backwards(plan, full_plan, fake=fake) self.check_replacements() def _migrate_all_forwards(self, plan, full_plan, fake, fake_initial): """ Take a list of 2-tuples of the form (migration instance, False) and apply them in the order they occur in the full_plan. """ migrations_to_run = {m[0] for m in plan} state = ProjectState(real_apps=list(self.loader.unmigrated_apps)) for migration, _ in full_plan: if not migrations_to_run: # We remove every migration that we applied from this set so # that we can bail out once the last migration has been applied # and don't always run until the very end of the migration # process. break if migration in migrations_to_run: if 'apps' not in state.__dict__: if self.progress_callback: self.progress_callback("render_start") state.apps # Render all -- performance critical if self.progress_callback: self.progress_callback("render_success") state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) migrations_to_run.remove(migration) else: migration.mutate_state(state, preserve=False) def _migrate_all_backwards(self, plan, full_plan, fake): """ Take a list of 2-tuples of the form (migration instance, True) and unapply them in reverse order they occur in the full_plan. Since unapplying a migration requires the project state prior to that migration, Django will compute the migration states before each of them in a first run over the plan and then unapply them in a second run over the plan. """ migrations_to_run = {m[0] for m in plan} # Holds all migration states prior to the migrations being unapplied states = {} state = ProjectState(real_apps=list(self.loader.unmigrated_apps)) if self.progress_callback: self.progress_callback("render_start") for migration, _ in full_plan: if not migrations_to_run: # We remove every migration that we applied from this set so # that we can bail out once the last migration has been applied # and don't always run until the very end of the migration # process. break if migration in migrations_to_run: if 'apps' not in state.__dict__: state.apps # Render all -- performance critical # The state before this migration states[migration] = state # The old state keeps as-is, we continue with the new state state = migration.mutate_state(state, preserve=True) migrations_to_run.remove(migration) else: migration.mutate_state(state, preserve=False) if self.progress_callback: self.progress_callback("render_success") for migration, _ in plan: self.unapply_migration(states[migration], migration, fake=fake) def collect_sql(self, plan): """ Takes a migration plan and returns a list of collected SQL statements that represent the best-efforts version of that plan. """ statements = [] state = None for migration, backwards in plan: with self.connection.schema_editor(collect_sql=True) as schema_editor: if state is None: state = self.loader.project_state((migration.app_label, migration.name), at_end=False) if not backwards: state = migration.apply(state, schema_editor, collect_sql=True) else: state = migration.unapply(state, schema_editor, collect_sql=True) statements.extend(schema_editor.collected_sql) return statements def apply_migration(self, state, migration, fake=False, fake_initial=False): """ Runs a migration forwards. """ if self.progress_callback: self.progress_callback("apply_start", migration, fake) if not fake: if fake_initial: # Test to see if this is an already-applied initial migration applied, state = self.detect_soft_applied(state, migration) if applied: fake = True if not fake: # Alright, do it normally with self.connection.schema_editor() as schema_editor: state = migration.apply(state, schema_editor) # For replacement migrations, record individual statuses if migration.replaces: for app_label, name in migration.replaces: self.recorder.record_applied(app_label, name) else: self.recorder.record_applied(migration.app_label, migration.name) # Report progress if self.progress_callback: self.progress_callback("apply_success", migration, fake) return state def unapply_migration(self, state, migration, fake=False): """ Runs a migration backwards. """ if self.progress_callback: self.progress_callback("unapply_start", migration, fake) if not fake: with self.connection.schema_editor() as schema_editor: state = migration.unapply(state, schema_editor) # For replacement migrations, record individual statuses if migration.replaces: for app_label, name in migration.replaces: self.recorder.record_unapplied(app_label, name) else: self.recorder.record_unapplied(migration.app_label, migration.name) # Report progress if self.progress_callback: self.progress_callback("unapply_success", migration, fake) return state def check_replacements(self): """ Mark replacement migrations applied if their replaced set all are. We do this unconditionally on every migrate, rather than just when migrations are applied or unapplied, so as to correctly handle the case when a new squash migration is pushed to a deployment that already had all its replaced migrations applied. In this case no new migration will be applied, but we still want to correctly maintain the applied state of the squash migration. """ applied = self.recorder.applied_migrations() for key, migration in self.loader.replacements.items(): all_applied = all(m in applied for m in migration.replaces) if all_applied and key not in applied: self.recorder.record_applied(*key) def
(self, project_state, migration): """ Tests whether a migration has been implicitly applied - that the tables or columns it would create exist. This is intended only for use on initial migrations (as it only looks for CreateModel and AddField). """ if migration.initial is None: # Bail if the migration isn't the first one in its app if any(app == migration.app_label for app, name in migration.dependencies): return False, project_state elif migration.initial is False: # Bail if it's NOT an initial migration return False, project_state if project_state is None: after_state = self.loader.project_state((migration.app_label, migration.name), at_end=True) else: after_state = migration.mutate_state(project_state) apps = after_state.apps found_create_model_migration = False found_add_field_migration = False # Make sure all create model and add field operations are done for operation in migration.operations: if isinstance(operation, migrations.CreateModel): model = apps.get_model(migration.app_label, operation.name) if model._meta.swapped: # We have to fetch the model to test with from the # embedded app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if model._meta.proxy or not model._meta.managed: continue if model._meta.db_table not in self.connection.introspection.table_names(self.connection.cursor()): return False, project_state found_create_model_migration = True elif isinstance(operation, migrations.AddField): model = apps.get_model(migration.app_label, operation.model_name) if model._meta.swapped: # We have to fetch the model to test with from the # embedded app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if model._meta.proxy or not model._meta.managed: continue table = model._meta.db_table db_field = model._meta.get_field(operation.name).column fields = self.connection.introspection.get_table_description(self.connection.cursor(), table) if db_field not in (f.name for f in fields): return False, project_state found_add_field_migration = True # If we get this far and we found at least one CreateModel or AddField migration, # the migration is considered implicitly applied. return (found_create_model_migration or found_add_field_migration), after_state
detect_soft_applied
pos.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::{borrow::Cow, cmp::Ordering, ops::Range, path::PathBuf, result::Result::*}; use ocamlrep::rc::RcOc; use ocamlrep_derive::{FromOcamlRep, ToOcamlRep}; use serde::{Deserialize, Serialize}; use crate::file_pos_large::FilePosLarge; use crate::file_pos_small::FilePosSmall; use crate::relative_path::{Prefix, RelativePath}; #[derive(Clone, Debug, Deserialize, Hash, FromOcamlRep, ToOcamlRep, Serialize)] enum PosImpl { Small { file: RcOc<RelativePath>, start: FilePosSmall, end: FilePosSmall, }, Large { file: RcOc<RelativePath>, start: Box<FilePosLarge>, end: Box<FilePosLarge>, }, } use PosImpl::*; #[derive(Clone, Debug, Deserialize, Hash, FromOcamlRep, ToOcamlRep, Serialize)] pub struct Pos(PosImpl); pub type PosR<'a> = &'a Pos; impl Pos { pub fn make_none() -> Self { // TODO: shiqicao make NONE static, lazy_static doesn't allow Rc Pos(PosImpl::Small { file: RcOc::new(RelativePath::make(Prefix::Dummy, PathBuf::from(""))), start: FilePosSmall::make_dummy(), end: FilePosSmall::make_dummy(), }) } pub fn is_none(&self) -> bool { match self { Pos(PosImpl::Small { file, start, end }) => { start.is_dummy() && end.is_dummy() && file.is_empty() } _ => false, } } pub fn filename(&self) -> &RelativePath { match &self.0 { Small { file, .. } => &file, Large { file, .. } => &file, } } /// Returns a closed interval that's incorrect for multi-line spans. pub fn info_pos(&self) -> (usize, usize, usize) { fn compute<P: FilePos>(pos_start: &P, pos_end: &P) -> (usize, usize, usize) { let (line, start_minus1, bol) = pos_start.line_column_beg(); let start = start_minus1.wrapping_add(1); let end_offset = pos_end.offset(); let mut end = end_offset - bol; // To represent the empty interval, pos_start and pos_end are equal because // end_offset is exclusive. Here, it's best for error messages to the user if // we print characters N to N (highlighting a single character) rather than characters // N to (N-1), which is very unintuitive. if end == start_minus1 { end = start } (line, start, end) } match &self.0 { Small { start, end, .. } => compute(start, end), Large { start, end, .. } => compute(start.as_ref(), end.as_ref()), } } pub fn info_pos_extended(&self) -> (usize, usize, usize, usize) { let (line_begin, start, end) = self.info_pos(); let line_end = match &self.0 { Small { end, .. } => end.line_column_beg(), Large { end, .. } => (*end).line_column_beg(), } .0; (line_begin, line_end, start, end) } pub fn info_raw(&self) -> (usize, usize) { (self.start_cnum(), self.end_cnum()) } pub fn line(&self) -> usize { match &self.0 { Small { start, .. } => start.line(), Large { start, .. } => start.line(), } } pub fn from_lnum_bol_cnum( file: RcOc<RelativePath>, start: (usize, usize, usize), end: (usize, usize, usize), ) -> Self { let (start_line, start_bol, start_cnum) = start; let (end_line, end_bol, end_cnum) = end; let start = FilePosSmall::from_lnum_bol_cnum(start_line, start_bol, start_cnum); let end = FilePosSmall::from_lnum_bol_cnum(end_line, end_bol, end_cnum); match (start, end) { (Some(start), Some(end)) => Pos(Small { file, start, end }), _ => { let start = Box::new(FilePosLarge::from_lnum_bol_cnum( start_line, start_bol, start_cnum, )); let end = Box::new(FilePosLarge::from_lnum_bol_cnum( end_line, end_bol, end_cnum, )); Pos(Large { file, start, end }) } } } pub fn to_start_and_end_lnum_bol_cnum(&self) -> ((usize, usize, usize), (usize, usize, usize)) { match &self.0 { Small { start, end, .. } => (start.line_beg_offset(), end.line_beg_offset()), Large { start, end, .. } => (start.line_beg_offset(), end.line_beg_offset()), } } /// For single-line spans only. pub fn from_line_cols_offset( file: RcOc<RelativePath>, line: usize, cols: Range<usize>, start_offset: usize, ) -> Self { let start = FilePosSmall::from_line_column_offset(line, cols.start, start_offset); let end = FilePosSmall::from_line_column_offset( line, cols.end, start_offset + (cols.end - cols.start), ); match (start, end) { (Some(start), Some(end)) => Pos(Small { file, start, end }), _ => { let start = Box::new(FilePosLarge::from_line_column_offset( line, cols.start, start_offset, )); let end = Box::new(FilePosLarge::from_line_column_offset( line, cols.end, start_offset + (cols.end - cols.start), )); Pos(Large { file, start, end }) } } } fn small_to_large_file_pos(p: &FilePosSmall) -> FilePosLarge { let (lnum, col, bol) = p.line_column_beg(); FilePosLarge::from_lnum_bol_cnum(lnum, bol, bol + col) } pub fn btw_nocheck(x1: Self, x2: Self) -> Self { let inner = match (x1.0, x2.0) { (Small { file, start, .. }, Small { end, .. }) => Small { file, start, end }, (Large { file, start, .. }, Large { end, .. }) => Large { file, start, end }, (Small { file, start, .. }, Large { end, .. }) => Large { file, start: Box::new(Self::small_to_large_file_pos(&start)), end, }, (Large { file, start, .. }, Small { end, .. }) => Large { file, start, end: Box::new(Self::small_to_large_file_pos(&end)), }, }; Pos(inner) } pub fn btw(x1: &Self, x2: &Self) -> Result<Self, String> { if x1.filename() != x2.filename() { // using string concatenation instead of format!, // it is not stable see T52404885 Err(String::from("Position in separate files ") + &x1.filename().to_string() + " and " + &x2.filename().to_string()) } else if x1.end_cnum() > x2.end_cnum() { Err(String::from("btw: invalid positions") + &x1.end_cnum().to_string() + "and" + &x2.end_cnum().to_string()) } else { Ok(Self::btw_nocheck(x1.clone(), x2.clone())) } } pub fn merge(x1: &Self, x2: &Self) -> Result<Self, String> { if x1.filename() != x2.filename() { // see comment above (T52404885) return Err(String::from("Position in separate files ") + &x1.filename().to_string() + " and " + &x2.filename().to_string()); } match (&x1.0, &x2.0) { ( Small { file, start: start1, end: end1, }, Small { file: _, start: start2, end: end2, }, ) => { let start = if start1.is_dummy() { start2 } else if start2.is_dummy() { start1 } else if start1.offset() < start2.offset() { start1 } else { start2 }; let end = if end1.is_dummy() { end2 } else if end2.is_dummy() { end1 } else if end1.offset() < end2.offset() { end2 } else { end1 }; Ok(Pos(Small { file: file.clone(), start: *start, end: *end, })) } ( Large { file, start: start1, end: end1, }, Large { file: _, start: start2, end: end2, }, ) => { let start = if start1.is_dummy() { start2 } else if start2.is_dummy() { start1 } else if start1.offset() < start2.offset() { start1 } else { start2 }; let end = if end1.is_dummy() { end2 } else if end2.is_dummy() { end1 } else if end1.offset() < end2.offset() { end2 } else { end1 }; Ok(Pos(Large { file: file.clone(), start: Box::new(*start.clone()), end: Box::new(*end.clone()), })) } (Small { file, start, end }, Large { .. }) => Self::merge( &Pos(Large { file: file.clone(), start: Box::new(Self::small_to_large_file_pos(&start)), end: Box::new(Self::small_to_large_file_pos(&end)), }), x2, ), (Large { .. }, Small { file, start, end }) => Self::merge( x1, &Pos(Large { file: file.clone(), start: Box::new(Self::small_to_large_file_pos(&start)), end: Box::new(Self::small_to_large_file_pos(&end)), }), ), } } pub fn last_char(&self) -> Cow<Self> { if self.is_none() { Cow::Borrowed(self) } else { Cow::Owned(Pos(match &self.0 { Small { file, end, .. } => Small { file: file.clone(), start: *end, end: *end, }, Large { file, end, .. } => Large { file: file.clone(), start: end.clone(), end: end.clone(), }, })) } } pub fn first_char_of_line(&self) -> Cow<Self> { if self.is_none() { Cow::Borrowed(self) } else { Cow::Owned(Pos(match &self.0 { Small { file, start, .. } => { let start = start.with_column(0); Small { file: file.clone(), start, end: start, } } Large { file, start, .. } => { let start = start.with_column(0); Large { file: file.clone(), start: Box::new(start), end: Box::new(start), } } })) } } pub fn end_cnum(&self) -> usize { match &self.0 { Small { end, .. } => end.offset(), Large { end, .. } => end.offset(), } } pub fn start_cnum(&self) -> usize { match &self.0 { Small { start, .. } => start.offset(), Large { start, .. } => start.offset(), } } } impl std::fmt::Display for Pos { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn do_fmt<P: FilePos>( f: &mut std::fmt::Formatter<'_>, file: &RelativePath, start: &P, end: &P, ) -> std::fmt::Result { write!(f, "{}", file)?; let (start_line, start_col, _) = start.line_column_beg(); let (end_line, end_col, _) = end.line_column_beg(); if start_line == end_line { write!(f, "({}:{}-{})", start_line, start_col, end_col) } else { write!(f, "({}:{}-{}:{})", start_line, start_col, end_line, end_col) } } match &self.0 { Small { file, start, end } => do_fmt(f, file, start, end), Large { file, start, end } => do_fmt(f, file, &**start, &**end), } } } impl Ord for Pos { // Intended to match the implementation of `Pos.compare` in OCaml. fn cmp(&self, other: &Pos) -> Ordering { self.filename() .cmp(other.filename()) .then(self.start_cnum().cmp(&other.start_cnum())) .then(self.end_cnum().cmp(&other.end_cnum())) } } impl PartialOrd for Pos { fn
(&self, other: &Pos) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for Pos { fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } impl Eq for Pos {} impl Pos { /// Returns a struct implementing Display which produces the same format as /// `Pos.string` in OCaml. pub fn string(&self) -> PosString { PosString(self) } } /// This struct has an impl of Display which produces the same format as /// `Pos.string` in OCaml. pub struct PosString<'a>(&'a Pos); impl std::fmt::Display for PosString<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let (line, start, end) = self.0.info_pos(); write!( f, "File {:?}, line {}, characters {}-{}:", self.0.filename().path(), line, start, end ) } } // TODO(hrust) eventually move this into a separate file used by Small & Large trait FilePos { fn offset(&self) -> usize; fn line_column_beg(&self) -> (usize, usize, usize); } macro_rules! impl_file_pos { ($type: ty) => { impl FilePos for $type { fn offset(&self) -> usize { (*self).offset() } fn line_column_beg(&self) -> (usize, usize, usize) { (*self).line_column_beg() } } }; } impl_file_pos!(FilePosSmall); impl_file_pos!(FilePosLarge); #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; fn make_pos(name: &str, start: (usize, usize, usize), end: (usize, usize, usize)) -> Pos { Pos::from_lnum_bol_cnum( RcOc::new(RelativePath::make(Prefix::Dummy, PathBuf::from(name))), start, end, ) } #[test] fn test() { assert_eq!(Pos::make_none().is_none(), true); assert_eq!( Pos::from_lnum_bol_cnum( RcOc::new(RelativePath::make(Prefix::Dummy, PathBuf::from("a"))), (0, 0, 0), (0, 0, 0) ) .is_none(), false ); assert_eq!( Pos::from_lnum_bol_cnum( RcOc::new(RelativePath::make(Prefix::Dummy, PathBuf::from(""))), (1, 0, 0), (0, 0, 0) ) .is_none(), false ); } #[test] fn test_string() { assert_eq!( Pos::make_none().string().to_string(), r#"File "", line 0, characters 0-0:"# ); let path = RcOc::new(RelativePath::make(Prefix::Dummy, PathBuf::from("a.php"))); assert_eq!( Pos::from_lnum_bol_cnum(path, (5, 100, 117), (5, 100, 142)) .string() .to_string(), r#"File "a.php", line 5, characters 18-42:"# ); } #[test] fn test_merge() { let test = |name, (exp_start, exp_end), ((fst_start, fst_end), (snd_start, snd_end))| { assert_eq!( Ok(make_pos("a", exp_start, exp_end)), Pos::merge( &make_pos("a", fst_start, fst_end), &make_pos("a", snd_start, snd_end) ), "{}", name ); // Run this again because we want to test that we get the same // result regardless of order. assert_eq!( Ok(make_pos("a", exp_start, exp_end)), Pos::merge( &make_pos("a", snd_start, snd_end), &make_pos("a", fst_start, fst_end), ), "{} (reversed)", name ); }; test( "basic test", ((0, 0, 0), (0, 0, 5)), (((0, 0, 0), (0, 0, 2)), ((0, 0, 2), (0, 0, 5))), ); test( "merge should work with gaps", ((0, 0, 0), (0, 0, 15)), (((0, 0, 0), (0, 0, 5)), ((0, 0, 10), (0, 0, 15))), ); test( "merge should work with overlaps", ((0, 0, 0), (0, 0, 15)), (((0, 0, 0), (0, 0, 12)), ((0, 0, 7), (0, 0, 15))), ); test( "merge should work between lines", ((0, 0, 0), (2, 20, 25)), (((0, 0, 0), (1, 10, 15)), ((1, 10, 20), (2, 20, 25))), ); assert_eq!( Err("Position in separate files |a and |b".to_string()), Pos::merge( &make_pos("a", (0, 0, 0), (0, 0, 0)), &make_pos("b", (0, 0, 0), (0, 0, 0)) ), "should reject merges with different filenames" ); } }
partial_cmp
UpdateRepositoryMemberRequest.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RoaRequest class UpdateRepositoryMemberRequest(RoaRequest): def __init__(self): RoaRequest.__init__(self, 'codeup', '2020-04-14', 'UpdateRepositoryMember') self.set_uri_pattern('/api/v3/projects/[ProjectId]/members/[UserId]') self.set_method('PUT') def get_OrganizationId(self): return self.get_query_params().get('OrganizationId') def set_OrganizationId(self,OrganizationId): self.add_query_param('OrganizationId',OrganizationId) def get_SubUserId(self): return self.get_query_params().get('SubUserId') def set_SubUserId(self,SubUserId): self.add_query_param('SubUserId',SubUserId) def get_AccessToken(self): return self.get_query_params().get('AccessToken') def
(self,AccessToken): self.add_query_param('AccessToken',AccessToken) def get_ProjectId(self): return self.get_path_params().get('ProjectId') def set_ProjectId(self,ProjectId): self.add_path_param('ProjectId',ProjectId) def get_UserId(self): return self.get_path_params().get('UserId') def set_UserId(self,UserId): self.add_path_param('UserId',UserId)
set_AccessToken
handling_module.py
import importlib from json import loads from base64 import b64decode import sys import gevent.monkey gevent.monkey.patch_all() import gevent import config from os import getpid from requests import post def
(module): global message m = importlib.import_module('modules.'+module) m.go(message) def asynchronous(): threads = [] print("\033[91m>--------------------------------------------------------------------------------------<\033[37m") for module in config.MODULE_LIST: print("\033[36m"+module[1]+"\033[37m") threads.append(gevent.spawn(fetch, module[1])) gevent.joinall(threads) x = sys.argv[1] x = b64decode(x).decode("utf-8") host = sys.argv[2] host = b64decode(host).decode("utf-8") pid = getpid() data = { 'host': host, 'pid': str(pid), } post('http://localhost:8787/add', data=data) message = loads(x) asynchronous() post('http://localhost:8787/delete', data=data)
fetch
VGGnet_train.py
import tensorflow as tf from networks.network import Network #define n_classes = 21 _feat_stride = [16,] anchor_scales = [8, 16, 32] class VGGnet_train(Network): def
(self, trainable=True): self.inputs = [] self.data = tf.placeholder(tf.float32, shape=[None, None, None, 3]) #self.im_info = tf.placeholder(tf.float32, shape=[None, 3]) #self.gt_boxes = tf.placeholder(tf.float32, shape=[None, 5]) self.keep_prob = tf.placeholder(tf.float32) self.segmentation=tf.placeholder(tf.float32,shape=[None,900]) self.rois=tf.placeholder(tf.float32,shape=[None,5]) #self.mweights=tf.placeholder(tf.float32,shape=[None,2]) self.sweights=tf.placeholder(tf.bool,shape=[None]) self.labels=tf.placeholder(tf.int32,shape=[None]) self.layers = dict({'data':self.data, 'segmentation':self.segmentation, 'sweight':self.sweights, 'labels': self.labels, "rois": self.rois}) self.trainable = trainable self.setup() def setup(self): (self.feed('data') .conv(3, 3, 64, 1, 1, name='conv1_1', trainable=False) .conv(3, 3, 64, 1, 1, name='conv1_2', trainable=False) .max_pool(2, 2, 2, 2, padding='VALID', name='pool1') .conv(3, 3, 128, 1, 1, name='conv2_1', trainable=False) .conv(3, 3, 128, 1, 1, name='conv2_2', trainable=False) .max_pool(2, 2, 2, 2, padding='VALID', name='pool2') .conv(3, 3, 256, 1, 1, name='conv3_1') .conv(3, 3, 256, 1, 1, name='conv3_2') .conv(3, 3, 256, 1, 1, name='conv3_3') .max_pool(2, 2, 2, 2, padding='VALID', name='pool3') .conv(3, 3, 512, 1, 1, name='conv4_1') .conv(3, 3, 512, 1, 1, name='conv4_2') .conv(3, 3, 512, 1, 1, name='conv4_3')) #=========ROIPOOLING======= (self.feed('conv4_3','rois') .roi_pool(7, 7, 1.0/16, name='pool_4') .conv(3, 3, 512, 1, 1, name='conv5_1') .conv(3, 3, 512, 1, 1, name='conv5_2') .conv(3, 3, 512, 1, 1, name='conv5_3') .max_pool(2, 2, 2, 2, padding='VALID', name='pool5')) #========= RPN ============ # (self.feed('conv5_3') # .conv(3,3,512,1,1,name='rpn_conv/3x3') # .conv(1,1,len(anchor_scales)*3*2 ,1 , 1, padding='VALID', relu = False, name='rpn_cls_score'))# # (self.feed('rpn_cls_score','gt_boxes','im_info','data') # .anchor_target_layer(_feat_stride, anchor_scales, name = 'rpn-data' ))# # # Loss of rpn_cls & rpn_boxes # (self.feed('rpn_conv/3x3') # .conv(1,1,len(anchor_scales)*3*4, 1, 1, padding='VALID', relu = False, name='rpn_bbox_pred')) #========= RoI Proposal ============ # (self.feed('rpn_cls_score') # .reshape_layer(2,name = 'rpn_cls_score_reshape') # .softmax(name='rpn_cls_prob')) # # (self.feed('rpn_cls_prob') # .reshape_layer(len(anchor_scales)*3*2,name = 'rpn_cls_prob_reshape')) # # (self.feed('rpn_cls_prob_reshape','rpn_bbox_pred','im_info') # .proposal_layer(_feat_stride, anchor_scales, 'TRAIN',name = 'rpn_rois')) # # (self.feed('rpn_rois','gt_boxes') # .proposal_target_layer(n_classes,name = 'roi-data')) #========= RCNN ============ (self.feed('pool5') .fc(1024, name='fc6') .dropout(0.5, name='drop6') .fc(1024, name='fc7') .dropout(0.5, name='drop7') .fc(n_classes, relu=False, name='cls_score') .softmax(name='cls_prob')) # (self.feed('drop7') # .fc(n_classes*4, relu=False, name='bbox_pred')) #==========segment network=== (self.feed('conv5_3') .conv(1,1,512,1 , 1, padding='VALID', name='conv5_4') .fc(512, name='fc8') .fc(900, relu=False, name='seg_score'))
__init__
QLearning.py
""" 这份代码使用 Q learning 算法训练并运行俄罗斯方块游戏 ai。其中简化状态空间的方法可参考论文 Adapting Reinforcement Learning to Tetris """ import numpy as np from game import * sub_well = 4 base = 7 def getStateIndex(field_width, field_height, field_map): """ 因为每一列有 7 种不同的情况,所以采用七进制数来作为状态索引 """ temp = [0 for _ in range(field_width)] convert = {} for i in range(-(base - 1)//2, (base - 1)//2 + 1): convert[i] = i + (base - 1)//2 for x in range(field_width): while temp[x] < field_height and field_map[temp[x]][x] == 0: temp[x] += 1 index = 0 for i in range(field_width-1): if temp[i+1] - temp[i] > (base - 1)//2: index += base**i * convert[(base - 1)//2] elif temp[i+1] - temp[i] < -(base - 1)//2: index += base**i * convert[-(base - 1)//2] else: index += base**i * convert[temp[i+1] - temp[i]] return index def getAllPossibleLocation(field_width, field_map, block, layout): all_possible_position = [] for x in range(field_width): if block.isLegal(layout, (x, -4), field_map) is not State.Middle: all_possible_position.append(x) return all_possible_position def findBottomPosition(field_map, block, x, layout): y = -4 while block.isLegal(layout, (x, y), field_map) is not State.Bottom: y += 1 return y - 1 def dropBlock(field_height, field_map, x0, y0, layout): for (x, y) in layout: if 0 <= y0 + y < field_height: field_map[y0 + y][x0 + x] = 1 if y0 + y < 0: return False return True def resetMap(field_width, field_height, field_map): count = 0 for y in range(field_height): for x in range(field_width): if field_map[y][x] == 1: field_map[y][x] = 0 count += 1 if count == 4: return def getNewMap(block, position, direction, field_map): while block.direction is not direction: block.rotate(field_map) while block.position[0] > position[0]: block.l
= 200 self.alpha = 0.2 self.gamma = 0.8 self.lambda_ = 0.3 self.epsilon = 0.01 self.key = [((s, b), (p, d)) for s in range(base**(self.field_width-1)) for b in range(7) for p in range(self.field_width) for d in range(4)] self.V = [0 for _ in range(len(self.key))] self.Q = dict(zip(self.key, self.V)) #self.Q = np.load('QL.npy').item() def checkEvents(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit(0) def getBlock(self, block): for x in range(len(Blocks_color)): if block.color == Blocks_color[x]: return x def getReward(self): temp = [0 for _ in range(self.field_width)] for x in range(self.field_width): while temp[x] < self.field_height and self.field_map[temp[x]][x] == 0: temp[x] += 1 buried_holes = 0 block = self.block_factory.cur_block for (x, y) in block.layout: i = 1 while block.position[1]+y+i < self.field_height and self.field_map[block.position[1]+y+i][x] == 0: buried_holes += 1 i += 1 return np.var(temp)*(-2) + buried_holes*(-1) def getAllActions(self, block): actions = [] for direction in range(len(block.layouts)): for x in getAllPossibleLocation(self.field_width, self.field_map, block, block.layouts[direction]): y = findBottomPosition(self.field_map, block, x, block.layouts[direction]) if dropBlock(self.field_height, self.field_map, x, y, block.layouts[direction]): actions.append((x, direction)) resetMap(self.field_width, self.field_height, self.field_map) return actions def getBestActionWithGreedy(self, block): block_type = self.getBlock(block) state = getStateIndex(self.field_width, self.field_height, self.field_map) actions = self.getAllActions(block) actions_value = {} for action in actions: actions_value[action] = self.Q[((state, block_type), action)] if actions_value == {}: return None elif random.random() > self.epsilon: return max(actions_value, key=actions_value.get) else: return list(actions_value.keys())[random.randint(0, len(actions_value)-1)] def getBestAction(self, block): block_type = self.getBlock(block) state = getStateIndex(self.field_width, self.field_height, self.field_map) actions = self.getAllActions(block) actions_value = {} for action in actions: actions_value[action] = self.Q[((state, block_type), action)] if actions_value == {}: return None return max(actions_value, key=actions_value.get) def train(self): record = [] for i in range(1, self.repeat_num+1): self.initialize() while not self.block_factory.is_failed: cur_state = getStateIndex(self.field_width, self.field_height, self.field_map) cur_block = self.getBlock(self.block_factory.cur_block) cur_action = self.getBestActionWithGreedy(self.block_factory.cur_block) cur_index = ((cur_state, cur_block), cur_action) if cur_action == None: break getNewMap(self.block_factory.cur_block, cur_action, cur_action[1], self.field_map) next_state = getStateIndex(self.field_width, self.field_height, self.field_map) next_block = self.getBlock(self.block_factory.next_block) next_action = self.getBestAction(self.block_factory.next_block) next_index = ((next_state, next_block), next_action) if next_action == None: break self.Q[cur_index] += self.alpha*(self.getReward()+self.gamma*self.Q[next_index] - self.Q[cur_index]) self.update() print("Epoch:"+str(i)+"/"+str(self.repeat_num)+" Lines:"+ str(self.lines_num)+" Alpha:"+str(self.alpha)) record.append(self.lines_num) if i % 100 == 0: self.alpha *= 0.5 np.save('QL.npy', {"V": self.V}) np.save('record_QL.npy', {"record": record}) np.save('QL.npy', self.Q) np.save('record_QL.npy', {"record": record}) class QLGame(Game): def __init__(self): super(QLGame, self).__init__(10, 20) self.Q = np.load('QL.npy', allow_pickle=True).item() self.col = 0 def checkEvents(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit(0) def getBlock(self, block): for x in range(len(Blocks_color)): if block.color == Blocks_color[x]: return x def cutFieldMap(self, position): new_field_map = [[0]*sub_well for _ in range(self.field_height)] for y in range(self.field_height): for x in range(sub_well): new_field_map[y][x] = self.field_map[y][position+x] return new_field_map def getAllActions(self, field_width, field_height, block, field_map, init_pos): actions = {} for direction in range(len(block.layouts)): for x in getAllPossibleLocation(field_width, field_map, block, block.layouts[direction]): y = findBottomPosition(field_map, block, x, block.layouts[direction]) if dropBlock(field_height, field_map, x, y, block.layouts[direction]): block_type = self.getBlock(block) state = getStateIndex(field_width, field_height, field_map) actions[(x + init_pos, direction)] = self.Q[((state, block_type), (x, direction))] resetMap(field_width, field_height, field_map) return actions def getBestAction(self): actions = {} cur_block = Block(self.block_factory.cur_block.screen, sub_well, self.field_height, self.block_factory.cur_block.layouts, self.block_factory.cur_block.direction, self.block_factory.cur_block.color, (0, -4)) for x in range(self.field_width - sub_well + 1): loc_actions = self.getAllActions(sub_well, self.field_height, cur_block, self.cutFieldMap(x), x) for k, v in loc_actions.items(): if k in actions: actions[k].append(v) else: actions[k] = [v] for k, v in actions.items(): actions[k] = max(v) return max(actions, key=actions.get) if actions != {} else None def start(self): self.initialize() self.initializePygame() while not self.block_factory.is_failed: self.checkEvents() action = self.getBestAction() if action == None: break getNewMap(self.block_factory.cur_block, action, action[1], self.field_map) self.update() self.draw() return self.lines_num if __name__ == '__main__': train = QLearning() train.train() game = QLGame() game.start()
eft(field_map) while block.position[0] < position[0]: block.right(field_map) while not block.is_stop: block.down(field_map) class QLearning(Game): def __init__(self): super(QLearning, self).__init__(sub_well, 1000) self.repeat_num
main_flags.go
package main import ( "flag" "fmt" "os" "github.com/couchbase/eventing/logging" ) // Flags encapsulates different command-line parameters "eventing" // executable exposes type Flags struct { adminHTTPPort string adminSSLPort string sslCertFile string sslKeyFile string eventingDir string kvPort string restPort string debugPort string uuid string diagDir string ipv6 bool numVbuckets int } var flags Flags func
() { fset := flag.NewFlagSet(os.Args[0], flag.ContinueOnError) fset.StringVar(&flags.adminHTTPPort, "adminport", "8096", "Port eventing admin service is running on") fset.StringVar(&flags.adminSSLPort, "adminsslport", "", "Port eventing admin SSL service is running on") fset.StringVar(&flags.sslCertFile, "certfile", "", "SSL Certificate file for eventing admin service") fset.StringVar(&flags.sslKeyFile, "keyfile", "", "SSL Key file for eventing admin service") fset.StringVar(&flags.diagDir, "diagdir", os.TempDir(), "Location where diagnostic information like minidumps will be written") fset.StringVar(&flags.eventingDir, "dir", "", "Directory where eventing relating timer data is stored on disk") fset.StringVar(&flags.kvPort, "kvport", "11210", "Port memcached is running on") fset.StringVar(&flags.restPort, "restport", "8091", "ns_server's REST port") fset.StringVar(&flags.uuid, "uuid", "", "UUID supplied by ns_server") fset.StringVar(&flags.debugPort, "debugPort", "9140", "Port assigned to debugger") fset.BoolVar(&flags.ipv6, "ipv6", false, "Enable ipv6 mode") fset.IntVar(&flags.numVbuckets, "vbuckets", 1024, "Number of vbuckets configured in Couchbase") fset.Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) fset.PrintDefaults() } for i := 1; i < len(os.Args); i++ { if err := fset.Parse(os.Args[i : i+1]); err != nil { logging.Warnf("Unable to parse argument '%v', ignoring: %v", os.Args[i], err) } } if flags.uuid == "" { fset.Usage() os.Exit(2) } }
initFlags
textDecorator.js
(() => { 'use strict'; function textDecorate(collection, num) { for (let i = 0; i < collection.length; i++) { const h1Elm = collection.item(i); const h1Text = h1Elm.textContent;
let count = 0; h1Text.split('').forEach(function (c) { let classNum = 0; if ((count % 2) == 0) { classNum = Math.floor(Math.random() * Math.floor(num / 2)) * 2; } else { classNum = Math.floor(Math.random() * Math.floor(num / 2)) * 2 + 1; } h1Elm.innerHTML += '<span class="deco' + classNum + '">' + c + '</span>'; count++; }); } } textDecorate(document.getElementsByClassName('deco'), 4); })();
h1Elm.innerHTML = null;
about.js
import React from 'react' import IconFlask from "../assets/flask.svg" const About = () => ( <div className="About"> <IconFlask className = "About__logo-icon" /> <div className ="About__title-box"> <h1 className="About__title-box__title">Eklectic Alchemy</h1> <p className="About__title-box__description">Handcrafted goods made from natural materials</p> </div> </div>
) export default About
0006_recipe_image.py
# Generated by Django 3.0.5 on 2020-04-14 14:07 import core.models from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('core', '0005_recipe'), ] operations = [ migrations.AddField( model_name='recipe', name='image', field=models.ImageField(null=True, upload_to=core.models.recipe_image_file_path), ), ]
fold_button.rs
#![allow(unused)] use makepad_render::*; use crate::button_logic::*; live_register!{ use makepad_render::shader::std::*; FoldButton: {{FoldButton}} { bg_quad: { debug_id: fold_button, instance opened: 0.0 instance hover: 0.0 uniform fade: 0.0 fn pixel(self) -> vec4 { let sz = 3.; let c = vec2(5.0, 0.5 * self.rect_size.y); let sdf = Sdf2d::viewport(self.pos * self.rect_size); sdf.clear(vec4(0.)); // we have 3 points, and need to rotate around its center sdf.rotate(self.opened * 0.5 * PI + 0.5 * PI, c.x, c.y); sdf.move_to(c.x - sz, c.y + sz); sdf.line_to(c.x, c.y - sz); sdf.line_to(c.x + sz, c.y + sz); sdf.close_path(); sdf.fill(mix(#a, #f, self.hover)); return sdf.result * self.fade; } } abs_size: vec2(32, 12) abs_offset: vec2(4., 0.) walk: Walk { width: Width::Fixed(15), height: Height::Fixed(12), margin: Margin {l: 1.0, r: 1.0, t: 1.0, b: 1.0}, } default_state: { duration: 0.1 apply: {bg_quad: {hover: 0.0}} } hover_state: { duration: 0.0 apply: {bg_quad: {hover: 1.0}} } closed_state: { track: zoom from: {all: Play::Exp {speed1: 0.96, speed2: 0.97}} redraw: true apply: { opened: [{time: 0.0, value: 1.0}, {time: 1.0, value: 0.0}] bg_quad: {opened: (opened)} } } opened_state: { track: zoom from: {all: Play::Exp {speed1: 0.98, speed2: 0.95}} redraw: true apply: {opened: [{time: 0.0, value: 0.0}, {time: 1.0, value: 1.0}]} } /* closed_state: { track: open duration: 0.2 ease: Ease::OutExp apply: { opened: 0.0, bg_quad: {opened: (opened)} } } opened_state: { track: open, duration: 0.2 ease: Ease::OutExp apply: {opened: 1.0,} }*/ } } #[derive(Live, LiveHook)] pub struct
{ #[rust] pub button_logic: ButtonLogic, #[default_state(default_state, closed_state)] pub animator: Animator, default_state: Option<LivePtr>, hover_state: Option<LivePtr>, closed_state: Option<LivePtr>, opened_state: Option<LivePtr>, opened: f32, bg_quad: DrawQuad, abs_size: Vec2, abs_offset: Vec2, walk: Walk, } pub enum FoldButtonAction { None, Opening, Closing, Animating(f32) } impl FoldButton { pub fn handle_event( &mut self, cx: &mut Cx, event: &mut Event, dispatch_action: &mut dyn FnMut(&mut Cx, FoldButtonAction), ) { if self.animator_handle_event(cx, event).is_animating() { if self.animator.is_track_of_animating(cx, self.closed_state) { dispatch_action(cx, FoldButtonAction::Animating(self.opened)) } }; let res = self.button_logic.handle_event(cx, event, self.bg_quad.draw_vars.area); match res.state { ButtonState::Pressed => { if self.opened > 0.2 { self.animate_to(cx, self.closed_state); dispatch_action(cx, FoldButtonAction::Closing) } else { self.animate_to(cx, self.opened_state); dispatch_action(cx, FoldButtonAction::Opening) } } ButtonState::Default => self.animate_to(cx, self.default_state), ButtonState::Hover => self.animate_to(cx, self.hover_state), _ => () }; } pub fn set_is_opened(&mut self, cx: &mut Cx, is_opened: bool, animate: Animate) { self.toggle_animator(cx, is_opened, animate, self.opened_state, self.closed_state) } pub fn draw(&mut self, cx: &mut Cx) { self.bg_quad.draw_walk(cx, self.walk); } pub fn draw_abs(&mut self, cx: &mut Cx, pos: Vec2, fade: f32) { self.bg_quad.apply_over(cx, live!{fade: (fade)}); self.bg_quad.draw_abs(cx, Rect { pos: pos + self.abs_offset, size: self.abs_size }); } }
FoldButton
grpc_query_test.go
package keeper_test import ( gocontext "context" "fmt" "testing" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/cosmos/cosmos-sdk/x/nft" ) func
(t *testing.T) { suite.Run(t, new(TestSuite)) } func (suite *TestSuite) TestBalance() { var ( req *nft.QueryBalanceRequest ) testCases := []struct { msg string malleate func(index int, require *require.Assertions) expError string balance uint64 postTest func(index int, require *require.Assertions, res *nft.QueryBalanceResponse, expBalance uint64) }{ { "fail empty ClassId", func(index int, require *require.Assertions) { req = &nft.QueryBalanceRequest{} }, "invalid class id", 0, func(index int, require *require.Assertions, res *nft.QueryBalanceResponse, expBalance uint64) {}, }, { "fail invalid Owner addr", func(index int, require *require.Assertions) { req = &nft.QueryBalanceRequest{ ClassId: testClassID, Owner: "owner", } }, "decoding bech32 failed", 0, func(index int, require *require.Assertions, res *nft.QueryBalanceResponse, expBalance uint64) {}, }, { "Success", func(index int, require *require.Assertions) { suite.TestMint() req = &nft.QueryBalanceRequest{ ClassId: testClassID, Owner: suite.addrs[0].String(), } }, "", 1, func(index int, require *require.Assertions, res *nft.QueryBalanceResponse, expBalance uint64) { require.Equal(res.Amount, expBalance, "the error occurred on:%d", index) }, }, } for index, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { require := suite.Require() tc.malleate(index, require) result, err := suite.queryClient.Balance(gocontext.Background(), req) if tc.expError == "" { require.NoError(err) } else { require.Error(err) require.Contains(err.Error(), tc.expError) } tc.postTest(index, require, result, tc.balance) }) } } func (suite *TestSuite) TestOwner() { var ( req *nft.QueryOwnerRequest owner string ) testCases := []struct { msg string malleate func(index int, require *require.Assertions) expError string postTest func(index int, require *require.Assertions, res *nft.QueryOwnerResponse) }{ { "fail empty ClassId", func(index int, require *require.Assertions) { req = &nft.QueryOwnerRequest{ Id: testID, } }, "invalid class id", func(index int, require *require.Assertions, res *nft.QueryOwnerResponse) {}, }, { "fail empty nft id", func(index int, require *require.Assertions) { req = &nft.QueryOwnerRequest{ ClassId: testClassID, } }, "invalid nft id", func(index int, require *require.Assertions, res *nft.QueryOwnerResponse) {}, }, { "success but nft id not exist", func(index int, require *require.Assertions) { req = &nft.QueryOwnerRequest{ ClassId: testClassID, Id: "kitty2", } }, "", func(index int, require *require.Assertions, res *nft.QueryOwnerResponse) { require.Equal(res.Owner, owner, "the error occurred on:%d", index) }, }, { "success but class id not exist", func(index int, require *require.Assertions) { req = &nft.QueryOwnerRequest{ ClassId: "kitty1", Id: testID, } }, "", func(index int, require *require.Assertions, res *nft.QueryOwnerResponse) { require.Equal(res.Owner, owner, "the error occurred on:%d", index) }, }, { "Success", func(index int, require *require.Assertions) { suite.TestMint() req = &nft.QueryOwnerRequest{ ClassId: testClassID, Id: testID, } owner = suite.addrs[0].String() }, "", func(index int, require *require.Assertions, res *nft.QueryOwnerResponse) { require.Equal(res.Owner, owner, "the error occurred on:%d", index) }, }, } for index, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { require := suite.Require() tc.malleate(index, require) result, err := suite.queryClient.Owner(gocontext.Background(), req) if tc.expError == "" { require.NoError(err) } else { require.Error(err) require.Contains(err.Error(), tc.expError) } tc.postTest(index, require, result) }) } } func (suite *TestSuite) TestSupply() { var ( req *nft.QuerySupplyRequest ) testCases := []struct { msg string malleate func(index int, require *require.Assertions) expError string supply uint64 postTest func(index int, require *require.Assertions, res *nft.QuerySupplyResponse, supply uint64) }{ { "fail empty ClassId", func(index int, require *require.Assertions) { req = &nft.QuerySupplyRequest{} }, "invalid class id", 0, func(index int, require *require.Assertions, res *nft.QuerySupplyResponse, supply uint64) {}, }, { "success but class id not exist", func(index int, require *require.Assertions) { req = &nft.QuerySupplyRequest{ ClassId: "kitty1", } }, "", 0, func(index int, require *require.Assertions, res *nft.QuerySupplyResponse, supply uint64) { require.Equal(res.Amount, supply, "the error occurred on:%d", index) }, }, { "success but supply equal zero", func(index int, require *require.Assertions) { req = &nft.QuerySupplyRequest{ ClassId: testClassID, } suite.TestSaveClass() }, "", 0, func(index int, require *require.Assertions, res *nft.QuerySupplyResponse, supply uint64) { require.Equal(res.Amount, supply, "the error occurred on:%d", index) }, }, { "Success", func(index int, require *require.Assertions) { n := nft.NFT{ ClassId: testClassID, Id: testID, Uri: testURI, } err := suite.app.NFTKeeper.Mint(suite.ctx, n, suite.addrs[0]) require.NoError(err, "the error occurred on:%d", index) req = &nft.QuerySupplyRequest{ ClassId: testClassID, } }, "", 1, func(index int, require *require.Assertions, res *nft.QuerySupplyResponse, supply uint64) { require.Equal(res.Amount, supply, "the error occurred on:%d", index) }, }, } for index, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { require := suite.Require() tc.malleate(index, require) result, err := suite.queryClient.Supply(gocontext.Background(), req) if tc.expError == "" { require.NoError(err) } else { require.Error(err) require.Contains(err.Error(), tc.expError) } tc.postTest(index, require, result, tc.supply) }) } } func (suite *TestSuite) TestNFTsOfClass() { var ( req *nft.QueryNFTsOfClassRequest nfts []*nft.NFT ) testCases := []struct { msg string malleate func(index int, require *require.Assertions) expError string postTest func(index int, require *require.Assertions, res *nft.QueryNFTsOfClassResponse) }{ { "fail empty ClassId", func(index int, require *require.Assertions) { req = &nft.QueryNFTsOfClassRequest{} }, "invalid class id", func(index int, require *require.Assertions, res *nft.QueryNFTsOfClassResponse) {}, }, { "success, no nft", func(index int, require *require.Assertions) { req = &nft.QueryNFTsOfClassRequest{ ClassId: testClassID, } suite.TestSaveClass() }, "", func(index int, require *require.Assertions, res *nft.QueryNFTsOfClassResponse) { require.Len(res.Nfts, 0, "the error occurred on:%d", index) }, }, { "success, class id not exist", func(index int, require *require.Assertions) { req = &nft.QueryNFTsOfClassRequest{ ClassId: "kitty1", } n := nft.NFT{ ClassId: testClassID, Id: testID, Uri: testURI, } err := suite.app.NFTKeeper.Mint(suite.ctx, n, suite.addrs[0]) require.NoError(err, "the error occurred on:%d", index) }, "", func(index int, require *require.Assertions, res *nft.QueryNFTsOfClassResponse) { require.Len(res.Nfts, 0, "the error occurred on:%d", index) }, }, { "success, owner not exist", func(index int, require *require.Assertions) { req = &nft.QueryNFTsOfClassRequest{ ClassId: testClassID, Owner: suite.addrs[1].String(), } }, "", func(index int, require *require.Assertions, res *nft.QueryNFTsOfClassResponse) { require.Len(res.Nfts, 0, "the error occurred on:%d", index) }, }, { "Success, query by classId", func(index int, require *require.Assertions) { req = &nft.QueryNFTsOfClassRequest{ ClassId: testClassID, } nfts = []*nft.NFT{ { ClassId: testClassID, Id: testID, Uri: testURI, }, } }, "", func(index int, require *require.Assertions, res *nft.QueryNFTsOfClassResponse) { require.Equal(res.Nfts, nfts, "the error occurred on:%d", index) }, }, { "Success,query by classId and owner", func(index int, require *require.Assertions) { req = &nft.QueryNFTsOfClassRequest{ ClassId: testClassID, Owner: suite.addrs[0].String(), } nfts = []*nft.NFT{ { ClassId: testClassID, Id: testID, Uri: testURI, }, } }, "", func(index int, require *require.Assertions, res *nft.QueryNFTsOfClassResponse) { require.Equal(res.Nfts, nfts, "the error occurred on:%d", index) }, }, } for index, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { require := suite.Require() tc.malleate(index, require) result, err := suite.queryClient.NFTsOfClass(gocontext.Background(), req) if tc.expError == "" { require.NoError(err) } else { require.Error(err) require.Contains(err.Error(), tc.expError) } tc.postTest(index, require, result) }) } } func (suite *TestSuite) TestNFT() { var ( req *nft.QueryNFTRequest expNFT nft.NFT ) testCases := []struct { msg string malleate func(index int, require *require.Assertions) expError string postTest func(index int, require *require.Assertions, res *nft.QueryNFTResponse) }{ { "fail empty ClassId", func(index int, require *require.Assertions) { req = &nft.QueryNFTRequest{} }, "invalid class id", func(index int, require *require.Assertions, res *nft.QueryNFTResponse) {}, }, { "fail empty nft id", func(index int, require *require.Assertions) { req = &nft.QueryNFTRequest{ ClassId: testClassID, } }, "invalid nft id", func(index int, require *require.Assertions, res *nft.QueryNFTResponse) {}, }, { "fail ClassId not exist", func(index int, require *require.Assertions) { req = &nft.QueryNFTRequest{ ClassId: "kitty1", Id: testID, } suite.TestMint() }, "not found nft", func(index int, require *require.Assertions, res *nft.QueryNFTResponse) {}, }, { "fail nft id not exist", func(index int, require *require.Assertions) { req = &nft.QueryNFTRequest{ ClassId: testClassID, Id: "kitty2", } }, "not found nft", func(index int, require *require.Assertions, res *nft.QueryNFTResponse) {}, }, { "success", func(index int, require *require.Assertions) { req = &nft.QueryNFTRequest{ ClassId: testClassID, Id: testID, } expNFT = nft.NFT{ ClassId: testClassID, Id: testID, Uri: testURI, } }, "", func(index int, require *require.Assertions, res *nft.QueryNFTResponse) { require.Equal(*res.Nft, expNFT, "the error occurred on:%d", index) }, }, } for index, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { require := suite.Require() tc.malleate(index, require) result, err := suite.queryClient.NFT(gocontext.Background(), req) if tc.expError == "" { require.NoError(err) } else { require.Error(err) require.Contains(err.Error(), tc.expError) } tc.postTest(index, require, result) }) } } func (suite *TestSuite) TestClass() { var ( req *nft.QueryClassRequest class nft.Class ) testCases := []struct { msg string malleate func(index int, require *require.Assertions) expError string postTest func(index int, require *require.Assertions, res *nft.QueryClassResponse) }{ { "fail empty ClassId", func(index int, require *require.Assertions) { req = &nft.QueryClassRequest{} }, "invalid class id", func(index int, require *require.Assertions, res *nft.QueryClassResponse) {}, }, { "fail ClassId not exist", func(index int, require *require.Assertions) { req = &nft.QueryClassRequest{ ClassId: "kitty1", } suite.TestSaveClass() }, "not found class", func(index int, require *require.Assertions, res *nft.QueryClassResponse) {}, }, { "success", func(index int, require *require.Assertions) { class = nft.Class{ Id: testClassID, Name: testClassName, Symbol: testClassSymbol, Description: testClassDescription, Uri: testClassURI, UriHash: testClassURIHash, } req = &nft.QueryClassRequest{ ClassId: testClassID, } }, "", func(index int, require *require.Assertions, res *nft.QueryClassResponse) { require.Equal(*res.Class, class, "the error occurred on:%d", index) }, }, } for index, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { require := suite.Require() tc.malleate(index, require) result, err := suite.queryClient.Class(gocontext.Background(), req) if tc.expError == "" { require.NoError(err) } else { require.Error(err) require.Contains(err.Error(), tc.expError) } tc.postTest(index, require, result) }) } } func (suite *TestSuite) TestClasses() { var ( req *nft.QueryClassesRequest classes []nft.Class ) testCases := []struct { msg string malleate func(index int, require *require.Assertions) expError string postTest func(index int, require *require.Assertions, res *nft.QueryClassesResponse) }{ { "success Class not exist", func(index int, require *require.Assertions) { req = &nft.QueryClassesRequest{} }, "", func(index int, require *require.Assertions, res *nft.QueryClassesResponse) { require.Len(res.Classes, 0) }, }, { "success", func(index int, require *require.Assertions) { req = &nft.QueryClassesRequest{} classes = []nft.Class{ { Id: testClassID, Name: testClassName, Symbol: testClassSymbol, Description: testClassDescription, Uri: testClassURI, UriHash: testClassURIHash, }, } suite.TestSaveClass() }, "", func(index int, require *require.Assertions, res *nft.QueryClassesResponse) { require.Len(res.Classes, 1, "the error occurred on:%d", index) require.Equal(*res.Classes[0], classes[0], "the error occurred on:%d", index) }, }, } for index, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { require := suite.Require() tc.malleate(index, require) result, err := suite.queryClient.Classes(gocontext.Background(), req) if tc.expError == "" { require.NoError(err) } else { require.Error(err) require.Contains(err.Error(), tc.expError) } tc.postTest(index, require, result) }) } }
TestGRPCQuery
routing.ts
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; /* With bottom tabs */ /* const routes: Routes = [ { path: '', loadChildren: './pages/menu/menu.module#MenuPageModule'}, ]; */ /* Without bottom tabs */ const routes: Routes = [ { path: 'home', loadChildren: () => import('./pages/home/home.module').then(m => m.HomeModule) }, { path: 'settings', loadChildren: () => import('./pages/settings/settings.module').then(m => m.SettingsModule) }, { path: 'new', loadChildren: () => import('./pages/new-packet/new-packet.module').then(m => m.NewPacketModule) }, { path: 'pay', loadChildren: () => import('./pages/pay/pay.module').then(m => m.PayModule) }, { path: 'packet-details', loadChildren: () => import('./pages/packet-details/packet-details.module').then(m => m.PacketDetailsPageModule) }, { path: 'my-packets', loadChildren: () => import('./pages/my-packets/my-packets.module').then(m => m.MyPacketsModule) },
{ path: 'opened-packets', loadChildren: () => import('./pages/opened-packets/opened-packets.module').then(m => m.OpenedPacketsModule) }, { path: 'public-packets', loadChildren: () => import('./pages/public-packets/public-packets.module').then(m => m.PublicPacketsModule) } ]; @NgModule({ imports: [ RouterModule.forChild(routes) ], exports: [RouterModule] }) export class RedPacketsRoutingModule { }
qnspsa.py
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The QN-SPSA optimizer.""" from typing import Any, Iterator, Optional, Union, Callable, Dict import numpy as np from qiskit.providers import Backend from qiskit.circuit import ParameterVector, QuantumCircuit from qiskit.opflow import StateFn, CircuitSampler, ExpectationBase from qiskit.utils import QuantumInstance from .spsa import SPSA, CALLBACK, TERMINATIONCHECKER, _batch_evaluate # the function to compute the fidelity FIDELITY = Callable[[np.ndarray, np.ndarray], float] class QNSPSA(SPSA):
r"""The Quantum Natural SPSA (QN-SPSA) optimizer. The QN-SPSA optimizer [1] is a stochastic optimizer that belongs to the family of gradient descent methods. This optimizer is based on SPSA but attempts to improve the convergence by sampling the **natural gradient** instead of the vanilla, first-order gradient. It achieves this by approximating Hessian of the ``fidelity`` of the ansatz circuit. Compared to natural gradients, which require :math:`\mathcal{O}(d^2)` expectation value evaluations for a circuit with :math:`d` parameters, QN-SPSA only requires :math:`\mathcal{O}(1)` and can therefore significantly speed up the natural gradient calculation by sacrificing some accuracy. Compared to SPSA, QN-SPSA requires 4 additional function evaluations of the fidelity. The stochastic approximation of the natural gradient can be systematically improved by increasing the number of ``resamplings``. This leads to a Monte Carlo-style convergence to the exact, analytic value. .. note:: This component has some function that is normally random. If you want to reproduce behavior then you should set the random number generator seed in the algorithm_globals (``qiskit.utils.algorithm_globals.random_seed = seed``). Examples: This short example runs QN-SPSA for the ground state calculation of the ``Z ^ Z`` observable where the ansatz is a ``PauliTwoDesign`` circuit. .. code-block:: python import numpy as np from qiskit.algorithms.optimizers import QNSPSA from qiskit.circuit.library import PauliTwoDesign from qiskit.opflow import Z, StateFn ansatz = PauliTwoDesign(2, reps=1, seed=2) observable = Z ^ Z initial_point = np.random.random(ansatz.num_parameters) def loss(x): bound = ansatz.bind_parameters(x) return np.real((StateFn(observable, is_measurement=True) @ StateFn(bound)).eval()) fidelity = QNSPSA.get_fidelity(ansatz) qnspsa = QNSPSA(fidelity, maxiter=300) result = qnspsa.optimize(ansatz.num_parameters, loss, initial_point=initial_point) References: [1] J. Gacon et al, "Simultaneous Perturbation Stochastic Approximation of the Quantum Fisher Information", `arXiv:2103.09232 <https://arxiv.org/abs/2103.09232>`_ """ def __init__( self, fidelity: FIDELITY, maxiter: int = 100, blocking: bool = True, allowed_increase: Optional[float] = None, learning_rate: Optional[Union[float, Callable[[], Iterator]]] = None, perturbation: Optional[Union[float, Callable[[], Iterator]]] = None, last_avg: int = 1, resamplings: Union[int, Dict[int, int]] = 1, perturbation_dims: Optional[int] = None, regularization: Optional[float] = None, hessian_delay: int = 0, lse_solver: Optional[Callable[[np.ndarray, np.ndarray], np.ndarray]] = None, initial_hessian: Optional[np.ndarray] = None, callback: Optional[CALLBACK] = None, termination_checker: Optional[TERMINATIONCHECKER] = None, ) -> None: r""" Args: fidelity: A function to compute the fidelity of the ansatz state with itself for two different sets of parameters. maxiter: The maximum number of iterations. Note that this is not the maximal number of function evaluations. blocking: If True, only accepts updates that improve the loss (up to some allowed increase, see next argument). allowed_increase: If ``blocking`` is ``True``, this argument determines by how much the loss can increase with the proposed parameters and still be accepted. If ``None``, the allowed increases is calibrated automatically to be twice the approximated standard deviation of the loss function. learning_rate: The update step is the learning rate is multiplied with the gradient. If the learning rate is a float, it remains constant over the course of the optimization. It can also be a callable returning an iterator which yields the learning rates for each optimization step. If ``learning_rate`` is set ``perturbation`` must also be provided. perturbation: Specifies the magnitude of the perturbation for the finite difference approximation of the gradients. Can be either a float or a generator yielding the perturbation magnitudes per step. If ``perturbation`` is set ``learning_rate`` must also be provided. last_avg: Return the average of the ``last_avg`` parameters instead of just the last parameter values. resamplings: The number of times the gradient (and Hessian) is sampled using a random direction to construct a gradient estimate. Per default the gradient is estimated using only one random direction. If an integer, all iterations use the same number of resamplings. If a dictionary, this is interpreted as ``{iteration: number of resamplings per iteration}``. perturbation_dims: The number of perturbed dimensions. Per default, all dimensions are perturbed, but a smaller, fixed number can be perturbed. If set, the perturbed dimensions are chosen uniformly at random. regularization: To ensure the preconditioner is symmetric and positive definite, the identity times a small coefficient is added to it. This generator yields that coefficient. hessian_delay: Start multiplying the gradient with the inverse Hessian only after a certain number of iterations. The Hessian is still evaluated and therefore this argument can be useful to first get a stable average over the last iterations before using it as preconditioner. lse_solver: The method to solve for the inverse of the Hessian. Per default an exact LSE solver is used, but can e.g. be overwritten by a minimization routine. initial_hessian: The initial guess for the Hessian. By default the identity matrix is used. callback: A callback function passed information in each iteration step. The information is, in this order: the parameters, the function value, the number of function evaluations, the stepsize, whether the step was accepted. termination_checker: A callback function executed at the end of each iteration step. The arguments are, in this order: the parameters, the function value, the number of function evaluations, the stepsize, whether the step was accepted. If the callback returns True, the optimization is terminated. To prevent additional evaluations of the objective method, if the objective has not yet been evaluated, the objective is estimated by taking the mean of the objective evaluations used in the estimate of the gradient. """ super().__init__( maxiter, blocking, allowed_increase, # trust region *must* be false for natural gradients to work trust_region=False, learning_rate=learning_rate, perturbation=perturbation, resamplings=resamplings, callback=callback, second_order=True, hessian_delay=hessian_delay, lse_solver=lse_solver, regularization=regularization, perturbation_dims=perturbation_dims, initial_hessian=initial_hessian, termination_checker=termination_checker, ) self.fidelity = fidelity def _point_sample(self, loss, x, eps, delta1, delta2): loss_points = [x + eps * delta1, x - eps * delta1] fidelity_points = [ (x, x + eps * delta1), (x, x - eps * delta1), (x, x + eps * (delta1 + delta2)), (x, x + eps * (-delta1 + delta2)), ] self._nfev += 6 loss_values = _batch_evaluate(loss, loss_points, self._max_evals_grouped) fidelity_values = _batch_evaluate(self.fidelity, fidelity_points, self._max_evals_grouped) # compute the gradient approximation and additionally return the loss function evaluations gradient_estimate = (loss_values[0] - loss_values[1]) / (2 * eps) * delta1 # compute the preconditioner point estimate diff = fidelity_values[2] - fidelity_values[0] diff -= fidelity_values[3] - fidelity_values[1] diff /= 2 * eps**2 rank_one = np.outer(delta1, delta2) # -0.5 factor comes from the fact that we need -0.5 * fidelity hessian_estimate = -0.5 * diff * (rank_one + rank_one.T) / 2 return np.mean(loss_values), gradient_estimate, hessian_estimate @property def settings(self) -> Dict[str, Any]: """The optimizer settings in a dictionary format.""" # re-use serialization from SPSA settings = super().settings settings.update({"fidelity": self.fidelity}) # remove SPSA-specific arguments not in QNSPSA settings.pop("trust_region") settings.pop("second_order") return settings @staticmethod def get_fidelity( circuit: QuantumCircuit, backend: Optional[Union[Backend, QuantumInstance]] = None, expectation: Optional[ExpectationBase] = None, ) -> Callable[[np.ndarray, np.ndarray], float]: r"""Get a function to compute the fidelity of ``circuit`` with itself. Let ``circuit`` be a parameterized quantum circuit performing the operation :math:`U(\theta)` given a set of parameters :math:`\theta`. Then this method returns a function to evaluate .. math:: F(\theta, \phi) = \big|\langle 0 | U^\dagger(\theta) U(\phi) |0\rangle \big|^2. The output of this function can be used as input for the ``fidelity`` to the :class:~`qiskit.algorithms.optimizers.QNSPSA` optimizer. Args: circuit: The circuit preparing the parameterized ansatz. backend: A backend of quantum instance to evaluate the circuits. If None, plain matrix multiplication will be used. expectation: An expectation converter to specify how the expected value is computed. If a shot-based readout is used this should be set to ``PauliExpectation``. Returns: A handle to the function :math:`F`. """ params_x = ParameterVector("x", circuit.num_parameters) params_y = ParameterVector("y", circuit.num_parameters) expression = ~StateFn(circuit.assign_parameters(params_x)) @ StateFn( circuit.assign_parameters(params_y) ) if expectation is not None: expression = expectation.convert(expression) if backend is None: def fidelity(values_x, values_y): value_dict = dict( zip(params_x[:] + params_y[:], values_x.tolist() + values_y.tolist()) ) return np.abs(expression.bind_parameters(value_dict).eval()) ** 2 else: sampler = CircuitSampler(backend) def fidelity(values_x, values_y=None): if values_y is not None: # no batches value_dict = dict( zip(params_x[:] + params_y[:], values_x.tolist() + values_y.tolist()) ) else: value_dict = {p: [] for p in params_x[:] + params_y[:]} for values_xy in values_x: for value_x, param_x in zip(values_xy[0, :], params_x): value_dict[param_x].append(value_x) for value_y, param_y in zip(values_xy[1, :], params_y): value_dict[param_y].append(value_y) return np.abs(sampler.convert(expression, params=value_dict).eval()) ** 2 return fidelity
mod.rs
//! Scripts audio events with precise timing. //! //! ## Creating and starting sequences //! //! To create a sequence, use `Sequence::new()` and then add //! the actions you want to take in order: //! //! ```no_run //! # use kira::{ //! # instance::{InstanceSettings, StopInstanceSettings}, //! # manager::{AudioManager, AudioManagerSettings}, //! # sequence::{Sequence, SequenceSettings, SequenceInstanceSettings}, //! # sound::Sound, //! # Duration, Tempo, //! # }; //! # let mut audio_manager = AudioManager::new(Default::default())?; //! # let sound_handle = audio_manager.add_sound(Sound::from_file("loop.ogg", Default::default())?)?; //! let mut sequence = Sequence::<()>::new(SequenceSettings::default()); //! // play a sound //! let instance_id = sequence.play(&sound_handle, InstanceSettings::default()); //! // wait 2 seconds //! sequence.wait(Duration::Seconds(2.0)); //! // stop the sound //! sequence.stop_instance(instance_id, StopInstanceSettings::default()); //! # audio_manager.start_sequence(sequence, SequenceInstanceSettings::default())?; //! # Ok::<(), Box<dyn std::error::Error>>(()) //! ``` //! //! To start the sequence, use `AudioManager::start_sequence()`: //! //! ```no_run //! # use kira::{ //! # instance::InstanceSettings, //! # manager::{AudioManager, AudioManagerSettings}, //! # sequence::{Sequence, SequenceSettings, SequenceInstanceSettings}, //! # sound::Sound, //! # Duration, Tempo, //! # }; //! # let mut audio_manager = AudioManager::new(Default::default())?; //! # let sound_handle = audio_manager.add_sound(Sound::from_file("loop.ogg", Default::default())?)?; //! # let mut sequence = Sequence::<()>::new(SequenceSettings::default()); //! audio_manager.start_sequence(sequence, SequenceInstanceSettings::default())?; //! # Ok::<(), Box<dyn std::error::Error>>(()) //! ``` //! //! ## Timing events //! //! Sequences provide two ways of timing events: //! - waiting for specific amounts of time //! - waiting for a certain metronome interval //! //! This sequence will play a sound at the beginning of a measure //! (assuming a measure is 4 beats long): //! //! ```no_run //! # use kira::{ //! # instance::InstanceSettings, //! # manager::{AudioManager, AudioManagerSettings}, //! # sequence::{Sequence, SequenceSettings, SequenceInstanceSettings}, //! # sound::Sound, //! # Duration, Tempo, //! # }; //! # let mut audio_manager = AudioManager::new(Default::default())?; //! # let sound_handle = audio_manager.add_sound(Sound::from_file("loop.ogg", Default::default())?)?; //! # let mut sequence = Sequence::<()>::new(SequenceSettings::default()); //! sequence.wait_for_interval(4.0); //! sequence.play(&sound_handle, InstanceSettings::default()); //! # audio_manager.start_sequence(sequence, SequenceInstanceSettings::default())?; //! # Ok::<(), Box<dyn std::error::Error>>(()) //! ``` //! //! Note that the metronome has to be running for the interval to work. //! //! ## Looping sequences //! //! You can create looping sequences by setting the loop start point. The //! following example will wait for the start of a measure and then //! play a sound every beat: //! //! ```no_run //! # use kira::{ //! # instance::InstanceSettings, //! # manager::{AudioManager, AudioManagerSettings}, //! # sequence::{Sequence, SequenceSettings, SequenceInstanceSettings}, //! # sound::Sound, //! # Duration, Tempo, //! # }; //! # let mut audio_manager = AudioManager::new(Default::default())?; //! # let sound_handle = audio_manager.add_sound(Sound::from_file("loop.ogg", Default::default())?)?; //! # let mut sequence = Sequence::<()>::new(SequenceSettings::default()); //! sequence.wait_for_interval(4.0); //! sequence.start_loop(); //! // when the sequence finishes, it will loop back to this step //! sequence.play(&sound_handle, InstanceSettings::default()); //! sequence.wait(Duration::Beats(1.0)); //! # audio_manager.start_sequence(sequence, SequenceInstanceSettings::default())?; //! # Ok::<(), Box<dyn std::error::Error>>(()) //! ``` //! //! ## Custom events //! //! Sequences can emit custom events that you can receive on the main //! thread, which is useful for syncing gameplay events to music events: //! //! ```no_run //! # use kira::{ //! # instance::InstanceSettings, //! # manager::{AudioManager, AudioManagerSettings}, //! # sequence::{Sequence, SequenceSettings, SequenceInstanceSettings}, //! # sound::Sound, //! # Duration, Tempo, //! # }; //! #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] //! enum CustomEvent { //! Beat, //! } //! //! # let mut audio_manager = AudioManager::new(Default::default())?; //! # let sound_handle = audio_manager.add_sound(Sound::from_file("loop.ogg", Default::default())?)?; //! # let mut sequence = Sequence::<CustomEvent>::new(SequenceSettings::default()); //! sequence.wait_for_interval(4.0); //! sequence.start_loop(); //! sequence.emit(CustomEvent::Beat); //! sequence.wait(Duration::Beats(1.0)); //! //! let mut sequence_instance_handle = //! audio_manager.start_sequence(sequence, SequenceInstanceSettings::default())?; //! # Ok::<(), Box<dyn std::error::Error>>(()) //! ``` //! //! You can retrieve events that the sequence emits using the //! [`SequenceInstanceHandle`](handle::SequenceInstanceHandle). //! //! ```no_run //! # use kira::{ //! # instance::InstanceSettings, //! # manager::{AudioManager, AudioManagerSettings}, //! # sequence::{Sequence, SequenceSettings, SequenceInstanceSettings}, //! # sound::Sound, //! # Duration, Tempo, //! # }; //! # #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] //! # enum CustomEvent { //! # Beat, //! # } //! # //! # let mut audio_manager = AudioManager::new(Default::default())?; //! # let sound_handle = audio_manager.add_sound(Sound::from_file("loop.ogg", Default::default())?)?; //! # let mut sequence = Sequence::<CustomEvent>::new(SequenceSettings::default()); //! # sequence.wait_for_interval(4.0); //! # sequence.start_loop(); //! # sequence.emit(CustomEvent::Beat); //! # sequence.wait(Duration::Beats(1.0)); //! # let mut sequence_instance_handle = audio_manager.start_sequence(sequence, SequenceInstanceSettings::default())?; //! while let Some(event) = sequence_instance_handle.pop_event()? { //! println!("{:?}", event); //! } //! # Ok::<(), Box<dyn std::error::Error>>(()) //! ``` pub mod error; pub mod handle; mod instance; #[cfg(test)] mod tests; use error::SequenceError; use handle::SequenceInstanceHandle; pub(crate) use instance::SequenceInstance; pub use instance::{SequenceInstanceId, SequenceInstanceState}; use indexmap::IndexSet; use ringbuf::RingBuffer; use std::{hash::Hash, vec}; use crate::{ command::producer::CommandProducer, group::{groups::Groups, GroupId, GroupSet}, instance::{ InstanceId, InstanceSettings, PauseInstanceSettings, ResumeInstanceSettings, StopInstanceSettings, }, metronome::MetronomeId, parameter::{tween::Tween, ParameterId}, playable::PlayableId, Duration, Tempo, Value, }; /// Settings for an instance of a [`Sequence`]. #[derive(Debug, Copy, Clone)] #[cfg_attr( feature = "serde_support", derive(serde::Serialize, serde::Deserialize), serde(default) )] pub struct SequenceInstanceSettings { /// The ID of the sequence instance. pub id: Option<SequenceInstanceId>, /// The metronome this sequence should sync to. pub metronome: Option<MetronomeId>, /// How many events can be queued at a time. pub event_queue_capacity: usize, } impl SequenceInstanceSettings { /// Creates a new `SequenceInstanceSettings` with the default settings. pub fn new() -> Self { Self::default() } /// Sets the ID of the sequence instance. pub fn id(self, id: impl Into<SequenceInstanceId>) -> Self { Self { id: Some(id.into()), ..self } } /// Sets the metronome that the sequence instance should sync to. pub fn metronome(self, metronome: impl Into<MetronomeId>) -> Self { Self { metronome: Some(metronome.into()), ..self } } /// Sets how many events can be queued at a time. pub fn event_queue_capacity(self, event_queue_capacity: usize) -> Self { Self { event_queue_capacity, ..self } } } impl Default for SequenceInstanceSettings { fn default() -> Self { Self { id: None, metronome: None, event_queue_capacity: 10, } } } #[derive(Debug, Copy, Clone)] #[cfg_attr( feature = "serde_support", derive(serde::Serialize, serde::Deserialize) )] pub(crate) enum SequenceOutputCommand { PlaySound(PlayableId, InstanceId, InstanceSettings), SetInstanceVolume(InstanceId, Value<f64>), SetInstancePlaybackRate(InstanceId, Value<f64>), SetInstancePanning(InstanceId, Value<f64>), PauseInstance(InstanceId, PauseInstanceSettings), ResumeInstance(InstanceId, ResumeInstanceSettings), StopInstance(InstanceId, StopInstanceSettings), PauseInstancesOf(PlayableId, PauseInstanceSettings), ResumeInstancesOf(PlayableId, ResumeInstanceSettings), StopInstancesOf(PlayableId, StopInstanceSettings), PauseSequence(SequenceInstanceId), ResumeSequence(SequenceInstanceId), StopSequence(SequenceInstanceId), PauseInstancesOfSequence(SequenceInstanceId, PauseInstanceSettings), ResumeInstancesOfSequence(SequenceInstanceId, ResumeInstanceSettings), StopInstancesOfSequence(SequenceInstanceId, StopInstanceSettings), SetMetronomeTempo(MetronomeId, Value<Tempo>), StartMetronome(MetronomeId), PauseMetronome(MetronomeId), StopMetronome(MetronomeId), SetParameter(ParameterId, f64, Option<Tween>), } #[derive(Debug, Clone)] #[cfg_attr( feature = "serde_support", derive(serde::Serialize, serde::Deserialize), serde(bound( serialize = "CustomEvent: serde::Serialize", deserialize = "CustomEvent: serde::Deserialize<'de>" )) )] pub(crate) enum SequenceStep<CustomEvent: Clone + Eq + Hash> { Wait(Duration), WaitForInterval(f64), RunCommand(SequenceOutputCommand), PlayRandom(Vec<PlayableId>, InstanceId, InstanceSettings), EmitCustomEvent(CustomEvent), } impl<CustomEvent: Clone + Eq + Hash> From<SequenceOutputCommand> for SequenceStep<CustomEvent> { fn from(command: SequenceOutputCommand) -> Self { Self::RunCommand(command) } } /// Settings for a [`Sequence`]. #[derive(Debug, Clone)] #[cfg_attr( feature = "serde_support", derive(serde::Serialize, serde::Deserialize), serde(default) )] pub struct SequenceSettings { /// The groups this sequence will belong to. pub groups: GroupSet, } impl SequenceSettings { /// Creates a new `SequenceSettings` with the default settings. pub fn new() -> Self { Self::default() } /// Sets the groups this sequence will belong to. pub fn groups(self, groups: impl Into<GroupSet>) -> Self { Self { groups: groups.into(), ..self } } } impl Default for SequenceSettings { fn default() -> Self { Self { groups: GroupSet::new(), } } } /// A series of steps to execute at certain times. #[derive(Debug, Clone)] #[cfg_attr( feature = "serde_support", derive(serde::Serialize, serde::Deserialize), serde(default), serde(bound( serialize = "CustomEvent: serde::Serialize", deserialize = "CustomEvent: serde::Deserialize<'de>" )) )] pub struct Sequence<CustomEvent: Clone + Eq + Hash = ()> { steps: Vec<SequenceStep<CustomEvent>>, loop_point: Option<usize>, groups: GroupSet, } impl<CustomEvent: Clone + Eq + Hash> Sequence<CustomEvent> { /// Creates a new sequence. pub fn new(settings: SequenceSettings) -> Self { Self { steps: vec![], loop_point: None, groups: settings.groups, } } fn with_components( steps: Vec<SequenceStep<CustomEvent>>, loop_point: Option<usize>, groups: GroupSet, ) -> Self { Self { steps, loop_point, groups, } } /// Gets the groups this sequence belongs to. pub fn groups(&self) -> &GroupSet { &self.groups } /// Adds a step to wait for a certain length of time /// before moving to the next step. pub fn wait(&mut self, duration: Duration) { self.steps.push(SequenceStep::Wait(duration)); } /// Adds a step to wait for a certain metronome interval /// (in beats) to be passed before moving to the next step. pub fn wait_for_interval(&mut self, interval: f64) { self.steps.push(SequenceStep::WaitForInterval(interval)); } /// Marks the point the sequence will loop back to /// after it finishes the last step. pub fn start_loop(&mut self) { self.loop_point = Some(self.steps.len()) } /// Adds a step to play a sound or arrangement. pub fn play<P: Into<PlayableId>>( &mut self, playable: P, settings: InstanceSettings, ) -> InstanceId { let id = settings.id.unwrap_or(InstanceId::new()); self.steps .push(SequenceOutputCommand::PlaySound(playable.into(), id, settings).into()); id } /// Adds a step to play a random sound or arrangement from a /// list of choices. pub fn play_random( &mut self, choices: Vec<PlayableId>, settings: InstanceSettings, ) -> InstanceId { let id = settings.id.unwrap_or(InstanceId::new()); self.steps .push(SequenceStep::PlayRandom(choices, id, settings).into()); id } /// Adds a step to set the volume of an instance. pub fn set_instance_volume(&mut self, id: impl Into<InstanceId>, volume: Value<f64>) { self.steps .push(SequenceOutputCommand::SetInstanceVolume(id.into(), volume).into()); } /// Adds a step to set the playback rate of an instance. pub fn set_instance_playback_rate( &mut self, id: impl Into<InstanceId>, playback_rate: Value<f64>, ) { self.steps .push(SequenceOutputCommand::SetInstancePlaybackRate(id.into(), playback_rate).into()); } /// Adds a step to set the panning of an instance. pub fn set_instance_panning(&mut self, id: impl Into<InstanceId>, panning: Value<f64>) { self.steps .push(SequenceOutputCommand::SetInstancePanning(id.into(), panning).into()); } /// Adds a step to pause an instance. pub fn pause_instance(&mut self, id: impl Into<InstanceId>, settings: PauseInstanceSettings) { self.steps .push(SequenceOutputCommand::PauseInstance(id.into(), settings).into()); } /// Adds a step to resume an instance. pub fn resume_instance(&mut self, id: impl Into<InstanceId>, settings: ResumeInstanceSettings) { self.steps .push(SequenceOutputCommand::ResumeInstance(id.into(), settings).into()); } /// Adds a step to stop an instance. pub fn stop_instance(&mut self, id: impl Into<InstanceId>, settings: StopInstanceSettings) { self.steps .push(SequenceOutputCommand::StopInstance(id.into(), settings).into()); } /// Adds a step to pause all instances of a sound or arrangement. pub fn pause_instances_of( &mut self, playable: impl Into<PlayableId>, settings: PauseInstanceSettings, ) { self.steps .push(SequenceOutputCommand::PauseInstancesOf(playable.into(), settings).into()); } /// Adds a step to resume all instances of a sound or arrangement. pub fn resume_instances_of( &mut self, playable: impl Into<PlayableId>, settings: ResumeInstanceSettings, ) { self.steps .push(SequenceOutputCommand::ResumeInstancesOf(playable.into(), settings).into()); } /// Adds a step to stop all instances of a sound or arrangement. pub fn stop_instances_of( &mut self, playable: impl Into<PlayableId>, settings: StopInstanceSettings, ) { self.steps .push(SequenceOutputCommand::StopInstancesOf(playable.into(), settings).into()); } /// Adds a step to pause a sequence. pub fn pause_sequence(&mut self, id: impl Into<SequenceInstanceId>) { self.steps .push(SequenceOutputCommand::PauseSequence(id.into()).into()); } /// Adds a step to resume a sequence. pub fn resume_sequence(&mut self, id: impl Into<SequenceInstanceId>) { self.steps .push(SequenceOutputCommand::ResumeSequence(id.into()).into()); } /// Adds a step to stop a sequence. pub fn stop_sequence(&mut self, id: impl Into<SequenceInstanceId>) { self.steps .push(SequenceOutputCommand::StopSequence(id.into()).into()); } /// Adds a step to pause a sequence and all instances played by it. pub fn pause_sequence_and_instances( &mut self, id: impl Into<SequenceInstanceId>, settings: PauseInstanceSettings, ) { let id: SequenceInstanceId = id.into(); self.steps .push(SequenceOutputCommand::PauseSequence(id).into()); self.steps .push(SequenceOutputCommand::PauseInstancesOfSequence(id, settings).into()); } /// Adds a step to resume a sequence and all instances played by it. pub fn resume_sequence_and_instances( &mut self, id: impl Into<SequenceInstanceId>, settings: ResumeInstanceSettings, ) { let id: SequenceInstanceId = id.into(); self.steps .push(SequenceOutputCommand::ResumeSequence(id).into()); self.steps .push(SequenceOutputCommand::ResumeInstancesOfSequence(id, settings).into()); } /// Adds a step to stop a sequence and all instances played by it. pub fn stop_sequence_and_instances( &mut self, id: impl Into<SequenceInstanceId>, settings: StopInstanceSettings, ) { let id: SequenceInstanceId = id.into(); self.steps .push(SequenceOutputCommand::StopSequence(id).into()); self.steps .push(SequenceOutputCommand::StopInstancesOfSequence(id, settings).into()); } /// Adds a step to set the tempo of the metronome. pub fn set_metronome_tempo( &mut self, id: impl Into<MetronomeId>, tempo: impl Into<Value<Tempo>>, )
/// Adds a step to start the metronome. pub fn start_metronome(&mut self, id: impl Into<MetronomeId>) { self.steps .push(SequenceOutputCommand::StartMetronome(id.into()).into()); } /// Adds a step to pause the metronome. pub fn pause_metronome(&mut self, id: impl Into<MetronomeId>) { self.steps .push(SequenceOutputCommand::PauseMetronome(id.into()).into()); } /// Adds a step to stop the metronome. pub fn stop_metronome(&mut self, id: impl Into<MetronomeId>) { self.steps .push(SequenceOutputCommand::StopMetronome(id.into()).into()); } /// Adds a step to set a parameter. pub fn set_parameter(&mut self, id: impl Into<ParameterId>, target: f64, tween: Option<Tween>) { self.steps .push(SequenceOutputCommand::SetParameter(id.into(), target, tween).into()); } /// Adds a step to emit a custom event. pub fn emit(&mut self, event: CustomEvent) { self.steps.push(SequenceStep::EmitCustomEvent(event)); } /// Makes sure nothing's wrong with the sequence that would make /// it unplayable. /// /// Currently, this only checks that the looping portion of a /// sequence (if there is one) contains at least one wait command /// (to prevent infinite loops). pub(crate) fn validate(&self) -> Result<(), SequenceError> { if let Some(loop_point) = self.loop_point { for step in self.steps.iter().skip(loop_point) { match step { SequenceStep::Wait(_) | SequenceStep::WaitForInterval(_) => { return Ok(()); } _ => {} } } Err(SequenceError::InfiniteLoop) } else { Ok(()) } } /// Gets a set of all of the events this sequence can emit. fn all_events(&self) -> IndexSet<CustomEvent> { let mut events = IndexSet::new(); for step in &self.steps { if let SequenceStep::EmitCustomEvent(event) = step { events.insert(event.clone()); } } events } /// Converts this sequence into a sequence where the custom events /// are indices corresponding to an event. Returns both the sequence /// and a mapping of indices to events. fn into_raw_sequence(&self) -> (RawSequence, IndexSet<CustomEvent>) { let events = self.all_events(); let raw_steps = self .steps .iter() .map(|step| match step { SequenceStep::Wait(duration) => SequenceStep::Wait(*duration), SequenceStep::WaitForInterval(interval) => SequenceStep::WaitForInterval(*interval), SequenceStep::RunCommand(command) => SequenceStep::RunCommand(*command), SequenceStep::PlayRandom(choices, id, settings) => { SequenceStep::PlayRandom(choices.clone(), *id, *settings) } SequenceStep::EmitCustomEvent(event) => { SequenceStep::EmitCustomEvent(events.get_index_of(event).unwrap()) } }) .collect(); ( Sequence::with_components(raw_steps, self.loop_point, self.groups.clone()), events, ) } pub(crate) fn create_instance( &self, id: SequenceInstanceId, settings: SequenceInstanceSettings, command_producer: CommandProducer, ) -> (SequenceInstance, SequenceInstanceHandle<CustomEvent>) { let (raw_sequence, events) = self.into_raw_sequence(); let (event_producer, event_consumer) = RingBuffer::new(settings.event_queue_capacity).split(); let instance = SequenceInstance::new(raw_sequence, event_producer, settings.metronome); let handle = SequenceInstanceHandle::new( id, instance.public_state(), command_producer, event_consumer, events, ); (instance, handle) } /// Returns if this sequence is in the group with the given ID. pub(crate) fn is_in_group(&self, id: GroupId, all_groups: &Groups) -> bool { self.groups.has_ancestor(id, all_groups) } } impl<CustomEvent: Clone + Eq + Hash> Default for Sequence<CustomEvent> { fn default() -> Self { Self { steps: vec![], loop_point: None, groups: GroupSet::new(), } } } pub(crate) type RawSequence = Sequence<usize>; impl RawSequence { fn convert_ids(steps: &mut Vec<SequenceStep<usize>>, old_id: InstanceId, new_id: InstanceId) { for step in steps { match step { SequenceStep::RunCommand(command) => match command { SequenceOutputCommand::PlaySound(_, id, _) => { if *id == old_id { *id = new_id; } } SequenceOutputCommand::SetInstanceVolume(id, _) => { if *id == old_id { *id = new_id; } } SequenceOutputCommand::SetInstancePlaybackRate(id, _) => { if *id == old_id { *id = new_id; } } SequenceOutputCommand::SetInstancePanning(id, _) => { if *id == old_id { *id = new_id; } } SequenceOutputCommand::PauseInstance(id, _) => { if *id == old_id { *id = new_id; } } SequenceOutputCommand::ResumeInstance(id, _) => { if *id == old_id { *id = new_id; } } SequenceOutputCommand::StopInstance(id, _) => { if *id == old_id { *id = new_id; } } _ => {} }, SequenceStep::PlayRandom(_, id, _) => { if *id == old_id { *id = new_id; } } _ => {} } } } /// Assigns new instance IDs to each PlaySound command and updates /// other sequence commands to use the new instance ID. This allows /// the sequence to play sounds with fresh instance IDs on each loop /// while still correctly pausing instances, setting their parameters, /// etc. fn update_instance_ids(&mut self) { for i in 0..self.steps.len() { match &self.steps[i] { SequenceStep::RunCommand(command) => match command { SequenceOutputCommand::PlaySound(_, id, _) => { let old_id = *id; Self::convert_ids(&mut self.steps, old_id, InstanceId::new()); } _ => {} }, SequenceStep::PlayRandom(_, id, _) => { let old_id = *id; Self::convert_ids(&mut self.steps, old_id, InstanceId::new()); } _ => {} } } } }
{ self.steps .push(SequenceOutputCommand::SetMetronomeTempo(id.into(), tempo.into()).into()); }
point_get.go
// Copyright 2018 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package executor import ( "github.com/pingcap/tidb/expression" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/model" "github.com/pingcap/tidb/mysql" "github.com/pingcap/tidb/plan" "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/table" "github.com/pingcap/tidb/table/tables" "github.com/pingcap/tidb/tablecodec" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" "github.com/pingcap/tidb/util/codec" "github.com/pkg/errors" "golang.org/x/net/context" ) func (b *executorBuilder) buildPointGet(p *plan.PointGetPlan) Executor { return &PointGetExecutor{ ctx: b.ctx, schema: p.Schema(), tblInfo: p.TblInfo, idxInfo: p.IndexInfo, idxVals: p.IndexValues, handle: p.Handle, startTS: b.getStartTS(), } } // PointGetExecutor executes point select query. type PointGetExecutor struct { ctx sessionctx.Context schema *expression.Schema tps []*types.FieldType tblInfo *model.TableInfo handle int64 idxInfo *model.IndexInfo idxVals []types.Datum startTS uint64 snapshot kv.Snapshot done bool } // Open implements the Executor interface. func (e *PointGetExecutor) Open(context.Context) error { return nil } // Close implements the Executor interface. func (e *PointGetExecutor) Close() error { return nil } // Next implements the Executor interface. func (e *PointGetExecutor) Next(ctx context.Context, chk *chunk.Chunk) error { chk.Reset() if e.done { return nil } e.done = true var err error e.snapshot, err = e.ctx.GetStore().GetSnapshot(kv.Version{Ver: e.startTS}) if err != nil { return errors.Trace(err) } if e.idxInfo != nil { idxKey, err1 := e.encodeIndexKey() if err1 != nil { return errors.Trace(err1) } handleVal, err1 := e.get(idxKey) if err1 != nil && !kv.ErrNotExist.Equal(err1) { return errors.Trace(err1) } if len(handleVal) == 0 { return nil } e.handle, err1 = tables.DecodeHandle(handleVal) if err1 != nil { return errors.Trace(err1) } } key := tablecodec.EncodeRowKeyWithHandle(e.tblInfo.ID, e.handle) val, err := e.get(key) if err != nil && !kv.ErrNotExist.Equal(err) { return errors.Trace(err) } if len(val) == 0 { if e.idxInfo != nil { return kv.ErrNotExist.GenWithStack("inconsistent extra index %s, handle %d not found in table", e.idxInfo.Name.O, e.handle) } return nil } return e.decodeRowValToChunk(val, chk) } func (e *PointGetExecutor) encodeIndexKey() ([]byte, error) { for i := range e.idxVals { colInfo := e.tblInfo.Columns[e.idxInfo.Columns[i].Offset] casted, err := table.CastValue(e.ctx, e.idxVals[i], colInfo) if err != nil { return nil, errors.Trace(err) } e.idxVals[i] = casted } encodedIdxVals, err := codec.EncodeKey(e.ctx.GetSessionVars().StmtCtx, nil, e.idxVals...) if err != nil { return nil, errors.Trace(err) } return tablecodec.EncodeIndexSeekKey(e.tblInfo.ID, e.idxInfo.ID, encodedIdxVals), nil } func (e *PointGetExecutor) get(key kv.Key) (val []byte, err error) { txn := e.ctx.Txn() if txn != nil && txn.Valid() && !txn.IsReadOnly() { return txn.Get(key) } return e.snapshot.Get(key) } func (e *PointGetExecutor) decodeRowValToChunk(rowVal []byte, chk *chunk.Chunk) error { colIDs := make(map[int64]int, e.schema.Len()) for i, col := range e.schema.Columns { colIDs[col.ID] = i } colVals, err := tablecodec.CutRowNew(rowVal, colIDs) if err != nil { return errors.Trace(err) } decoder := codec.NewDecoder(chk, e.ctx.GetSessionVars().Location()) for id, offset := range colIDs { if e.tblInfo.PKIsHandle && mysql.HasPriKeyFlag(e.schema.Columns[offset].RetType.Flag)
if id == model.ExtraHandleID { chk.AppendInt64(offset, e.handle) continue } colVal := colVals[offset] if len(colVal) == 0 { colInfo := getColInfoByID(e.tblInfo, id) d, err1 := table.GetColOriginDefaultValue(e.ctx, colInfo) if err1 != nil { return errors.Trace(err1) } chk.AppendDatum(offset, &d) continue } _, err = decoder.DecodeOne(colVals[offset], offset, e.schema.Columns[offset].RetType) if err != nil { return errors.Trace(err) } } return nil } func getColInfoByID(tbl *model.TableInfo, colID int64) *model.ColumnInfo { for _, col := range tbl.Columns { if col.ID == colID { return col } } return nil } // Schema implements the Executor interface. func (e *PointGetExecutor) Schema() *expression.Schema { return e.schema } func (e *PointGetExecutor) retTypes() []*types.FieldType { if e.tps == nil { e.tps = make([]*types.FieldType, e.schema.Len()) for i := range e.schema.Columns { e.tps[i] = e.schema.Columns[i].RetType } } return e.tps } func (e *PointGetExecutor) newChunk() *chunk.Chunk { return chunk.NewChunkWithCapacity(e.retTypes(), 1) }
{ chk.AppendInt64(offset, e.handle) continue }
switchscene.go
package main import ( "errors" "strings" obsws "github.com/DanceNgine/go-obs-websocket" "github.com/spf13/cobra" ) var switchSceneCmd = &cobra.Command{ Use: "switch-scene", Short: "Switch to a different OBS scene", RunE: func(cmd *cobra.Command, args []string) error { if len(args) < 1
return switchScene(strings.Join(args, " ")) }, } func switchScene(scene string) error { req := obsws.NewSetCurrentSceneRequest(scene) return req.Send(*client) } func init() { rootCmd.AddCommand(switchSceneCmd) }
{ return errors.New("switch-scene requires a scene name as argument") }
serve.py
class TCPServer(socketserver.TCPServer): allow_reuse_address = True def serve(root, port): class Handler(http.server.SimpleHTTPRequestHandler): def __init__(self, *args, **kwargs): super().__init__(*args, directory=root, **kwargs) print("Listening for requests on http://localhost:{}/".format(port)) with TCPServer(("", port), Handler) as httpd: try: httpd.serve_forever() except KeyboardInterrupt: httpd.shutdown() httpd.server_close()
import http.server import socketserver
invalid_for8.go
package main func
() { for { } // "While" loop for x < 10 { } for ; x > 10; x-- { } for i := 0; i < 10 i ++ { } }
main
Qzone.py
import time import re import random import requests from urllib import parse import qq_init as qq import pymongo from selenium import webdriver from selenium.webdriver.chrome.options import Options class Spider(object): def __init__(self): ''' 初始化 ''' chrome_options = Options() # chrome_options.add_argument('--headless') # chrome_options.add_argument('--disable-gpu') self.driver = webdriver.Chrome(chrome_options=chrome_options) self.driver.get('https://i.qq.com/') self.__username = qq.USERNAME self.__password = qq.PASSWORD self.headers = { 'host': 'h5.qzone.qq.com', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.8', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36', 'connection': 'keep-alive' } self.req = requests.Session() self.cookies = {} self.client = pymongo.MongoClient(host=qq.HOST, port=qq.PORT) self.db = self.client[qq.DB] def login(self): ''' 登录、调用get_g_tk()、get_friends()函数 :return: ''' self.driver.switch_to.frame('login_frame') self.driver.find_element_by_id('switcher_plogin').click() self.driver.find_element_by_id('u').clear() self.driver.find_element_by_id('u').send_keys(self.__username) self.driver.find_element_by_id('p').clear() self.driver.find_element_by_id('p').send_keys(self.__password) self.driver.find_element_by_id('login_button').click() time.sleep(7) self.driver.get('http://user.qzone.qq.com/{}'.format(self.__username)) cookie = '' for item in self.driver.get_cookies(): cookie += item["name"] + '=' + item['value'] + ';' self.cookies = cookie self.get_g_tk() self.headers['Cookie'] = self.cookies self.get_friends() self.driver.quit() def get_friends(self): ''' 获取全部好友 :return: qq, name ''' url = 'https://user.qzone.qq.com/proxy/domain/r.qzone.qq.com/cgi-bin/tfriend/friend_hat_get.cgi?' params = { 'uin': self.__username, 'fupdate': 1, 'g_tk': self.g_tk } url = url + parse.urlencode(params) friends = self.req.get(url, headers=self.headers).text name, qq_num = [], [] for _qq, _name in zip(re.findall('"\d+"', friends), re.findall('"realname":.*"', friends)): name.append(re.sub('"|realname|:', '', _name)) qq_num.append(re.sub('"', '', _qq)) self.name, self.qq_num = name, qq_num def get_g_tk(self): ''' 获取g_tk() :return: 生成的g_tk ''' p_skey = self.cookies[self.cookies.find('p_skey=') + 7: self.cookies.find(';', self.cookies.find('p_skey='))] if len(p_skey) > 50: self.driver.quit() raise BaseException( '登录出错' ) h = 5381 for i in p_skey: h += (h << 5) + ord(i) print('g_tk', h & 2147483647) self.g_tk = h & 2147483647 def get_mood(self): ''' 构造说说请求链接 对所有好友进行请求 获取点赞好友信息 正则解析 存入数据库 设置时长 5 秒,防封号 :return: ''' url = 'https://h5.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6?' params = { 'inCharset': 'utf-8', 'outCharset': 'utf-8', 'sort': 0, 'num': 20, 'repllyunm': 100, 'cgi_host': 'http://taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6', 'callback': '_preloadCallback', 'code_version': 1, 'format': 'jsonp', 'need_private_comment': 1, 'g_tk': self.g_tk } url = url + parse.urlencode(params) for q in self.qq_num: num = 0 t1, pos = True, 0 url_ = url + '&uin=' + str(q) black, shuoshuo = self.db['black'], self.db['mood'] while(t1): url__ = url_ + '&pos=' + str(pos) mood = self.req.get(url=url__, headers=self.headers) if '\"msglist\":null' in mood.text or "\"message\":\"对不起,主人设置了保密,您没有权限查看\"" in mood.text: t1 = False if '\"message\":\"对不起,主人设置了保密,您没有权限查看\"' in mood.text: data = { 'name': self.name[self.qq_num.index(q)], 'qq': q } black.insert(data) else: created_time = re.findall('created_time":\d+', mood.text) source = re.findall('source_appid":".*?"source_name":".*?"', mood.text) contents = re.findall('],"content":".*?"', mood.text) forword = re.findall('fwdnum":\d+', mood.text) comment_content = re.findall('commentlist":(null|.*?],)', mood.text) comments = re.findall('cmtnum":\d+', mood.text) pics = re.findall('","pic(_template|".*?])', mood.text) like_url = 'https://user.qzone.qq.com/proxy/domain/users.qzone.qq.com/cgi-bin/likes/get_like_list_app?' tids = re.findall('tid":".*?"', mood.text) for _time, _source, _content, _forword, _comment_content, _comment, _pic, _tid in \ zip(created_time, source, contents, forword, comment_content, comments, pics, tids): param = { 'uin': self.__username, 'unikey': 'http://user.qzone.qq.com/{}/mood/'.format(q)+re.sub('tid":"|"', '', _tid)+'.1', 'begin_uin': 0, 'query_count': 60, 'if_first_page': 1, 'g_tk': self.g_tk } like_url_current = like_url + parse.urlencode(param) like = self.req.get(url=like_url_current, headers=self.headers) likers = like.text.encode(like.encoding).decode('utf-8') if likers is None: likers = [] fuin, nick, sex, constellation, address = re.findall('fuin":\d+', likers), re.findall('nick":".*?"', likers), re.findall('gender":".*?"', likers), re.findall('tion":".*?"', likers), re.findall('addr":".*?"', likers) infos = [] # 点赞信息 for _fuin, _nick, _sex, _constellation, _address in zip(fuin, nick, sex, constellation, address): info = { 'fuin': re.sub('fuin":', '', _fuin), 'nick': re.sub('nick":"|"', '', _nick), 'sex': re.sub('gender":"|"', '', _sex), 'constellation': re.sub('tion":"|"', '', _constellation), 'address': re.sub('addr":"|"', '', _address) } infos.append(info) num = num + 1 print(num) data = { # '_id': str(q) + '_' + str(random.random() * 10).replace('.', ''), '_id': str(q) + '_' + str(num), 'name': self.name[self.qq_num.index(q)], 'CreateTime': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(re.sub('created_time":', '', _time)))), 'source': re.sub('source_appid":".*?"source_name":"|"', '', _source), 'content': re.sub('],"content":"|"', '', _content), 'forward': re.sub('fwdnum":', '', _forword), 'comment_content': re.sub('null|commentlist":', '', _comment_content) if 'null' in _comment_content else str([(re.sub('content":"|"', '', x), re.sub('createTime2":"|"', '', y), re.sub('name":"|"', '', z), re.sub('uin":', '', zz)) for x, y, z, zz in zip(re.findall('content":".*?"', _comment_content), re.findall('createTime2":".*?"', _comment_content), re.findall('name":".*?"', _comment_content), re.findall('uin":\d+', _comment_content))]), 'comment': re.sub('cmtnum":', '', _comment), 'pic': [] if 'template' in _pic else [re.sub('url2":|"', '', i) for i in re.findall('url2":".*?"', _pic)], 'lick_url' : like_url_current } try: data['like'] = re.sub('number":', '', re.search('number":\d+', likers).group()) except Exception as identifier: print(identifier) data['like'] = 0 data['likers'] = infos if shuoshuo.insert(data): print('%s 的说说写入到数据库成功!' % self.name[self.qq_num.index(q)]) else: with open('filed', 'a+', encoding='utf-8') as f: f.write('%s 的说说爬取失败!\n' % self.name[self.qq_num.index(q)]) print('%s 的说说写入到数据库成功!' % self.name[self.qq_num.index(q)]) pos += 20 time.sleep(4) def get_board(self): ''' 获取留言, 与获取说说大同小异 :return: ''' url = 'https://user.qzone.qq.com/proxy/domain/m.qzone.qq.com/cgi-bin/new/get_msgb?' params = { 'uin': self.__username, 'num': 10, 'hostword': 0, 'essence': 1, 'inCharset': 'utf-8', 'outCharset': 'utf-8', 'format': 'jsonp', 'g_tk': self.g_tk } url = url + parse.urlencode(params) for q in self.qq_num: num = 0 t2 = True url_ = url + '&hostUin=' + str(q) start = 0 boardb = self.db['board'] while(t2): url__ = url_ + '&start=' + str(start) board = self.req.get(url=url__, headers=self.headers) if '\"message":"空间主人设置了访问权限,您无法进行操作\"' in board.text or '\"message\":\"空间未开通\"' in board.text or '\"commentList\":[]' in board.text or '\"total\":0' in board.text: t2 = False else: text = board.text ids, nickname, uin, pubtime, content, replyList = \ re.findall('id":"\d+', text), re.findall('nickname":".*?"', text), re.findall('uin":\d+,\n"nick', text),\ re.findall('pubtime":".*?"', text), re.findall('ubbContent":".*?"', text), re.findall('"replyList":(\[\]|.*?\}\])', text, re.S) for _id, _nickname, _uin, _time, _content, _reply in zip(ids, nickname, uin, pubtime, content, replyList): num = num + 1 print(num) data = { # '_id': str(q) + '_' + re.sub('id":"', '', _id), '_id': str(q) + '_' + str(num), 'owner': self.name[self.qq_num.index(q)], 'total': re.sub('total":', '', re.search('total":\d+', board.text).group()), 'name': re.sub('nickname":"|"', '', _nickname), 'qq': re.sub('uin":|,\n"nick', '', _uin), 'time': re.sub('pubtime":"|"', '', _time), 'content': re.sub('ubbContent":"|"', '', _content), # 下行需要改动 'replyList': [] if '[]' in _reply else str([re.sub('nick":"|"', '', name) + re.sub('content"|"', '', con) for name, con in zip(re.findall('nick":".*?"', _reply), re.findall('content":".*?"', _reply))]) } if boardb.insert(data): print('%s 的留言存储到Mongodb成功!' % self.name[self.qq_num.index(q)]) start += 10 def get_information(self): '''
url = 'https://h5.qzone.qq.com/proxy/domain/base.qzone.qq.com/cgi-bin/user/cgi_userinfo_get_all?' params = { 'vuin': self.__username, 'fupdate': 1, 'g_tk': self.g_tk } url = url + parse.urlencode(params) table = self.db['information'] for q in self.qq_num: t3 = True url_ = url + '&uin=' + str(q) while(t3): info = self.req.get(url=url_, headers=self.headers) if '\"message\":\"您无权访问\"' in info.text: t3 = False else: text = info.text sex = ['其他', '男', '女'] constellation = ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座', '未填写'] data = { '_id': str(q) + '_' + str(random.random() * 10).replace('.', ''), 'nickname': re.sub('nickname":"|"', '', re.search('nickname":".*?"', text).group()), 'spacename': re.sub('spacename":"|"', '', re.search('spacename":".*?"', text).group()), 'desc': re.sub('desc":"|"', '', re.search('desc":".*?"', text).group()), 'signature': re.sub('signature":"|"', '', re.search('signature":".*?"', text).group()), 'sex': sex[int(re.sub('sex":', '', re.search('sex":\d+', text).group()))], 'age': re.sub('"age":', '', re.search('"age":\d+', text).group()), 'birthday': re.sub('birthyear":', '', re.search('birthyear":\d+', text).group()) + '-' + re.sub('birthday":"|"', '', re.search('birthday":".*"', text).group()), 'constellation': constellation[int(re.sub('constellation":|,', '', re.search('constellation":.*,', text).group()).replace('-1', '12'))], 'country': re.sub('country":"|"', '', re.search('country":".*"', text).group()), 'province': re.sub('province":"|"', '', re.search('province":".*?"', text).group()), 'city': re.sub('city":"|"', '', re.search('city":".*?"', text).group()), 'hometown': re.sub('hco":"|"|,|\n|hc|hp|:', '', re.search('hco":".*\n".*\n".*', text).group()), # 'marriage': marriage[int(re.sub('marriage":', '', re.search('marriage":\d', text).group()))], 'career': re.sub('career":"|"', '', re.search('career":".*?"', text).group()), 'address': re.sub('cb":"|"', '', re.search('cb":".*?"', text).group()) } if table.insert(data): print('%s 的信息写入到数据库成功!' % self.name[self.qq_num.index(q)]) t3 = False if __name__ == '__main__': sp = Spider() sp.login() sp.get_information() t = time.perf_counter() sp.get_board() sp.get_mood() End = time.perf_counter() - t print('所有内容爬取完成!总用时%s!' % End)
构造请求,正则解析 :return: '''
mod.rs
pub mod api; use crate::gl::context::GLContext; use crate::gl::feature::EntryGLFn; pub use api::*; impl GL21 for GLContext { unsafe fn entry(&self) -> &EntryGLFn
}
{ &self.entry }
graph_shortestpath_1.py
""" 单源点最短路径算法,所有顶点对之间的最短路径算法 """ from prioqueue import PrioQueue # , PrioQueueError from graph import * # Find nearest pathes from a single vertex to other reachable # vertices using Dijkstra algorithm. # Use a loop to find next nearest vertex, time O(V^2), space O(V) def dijkstra_shortest_paths(graph, v0): vnum = graph.vertex_num() assert vnum > 0 and 0 <= v0 < vnum count, paths = 0, [None]*vnum cands = [(inf, v0, i) for i in range(graph.vertex_num())] cands[v0] = (0, v0, v0) vmin = v0 while vmin > -1: plen = cands[vmin][0] paths[vmin] = (cands[vmin][1], plen) cands[vmin] = None count += 1 for v, w in graph.out_edges(vmin): if cands[v] and plen + w < cands[v][0]: # Shorter path, update cands[v] = (plen + w, vmin, v) vmin, plen = -1, inf for i in range(vnum): if cands[i] and cands[i][0] < plen: vmin, plen = i, cands[i][0] return paths # Find nearest pathes from a single vertex to other reachable # vertices using Dijkstra algorithm. # Use an priority queue to fine the nearest vertex, time O(E), space O(E) def dijkstra_shortest_paths_0(graph, v0): vnum = graph.vertex_num() assert 0 <= v0 < vnum count, paths = 0, [None]*vnum cands = PrioQueue([(0, v0, v0)]) while count < vnum and not cands.is_empty(): plen, u, vmin = cands.dequeue() if paths[vmin]: continue paths[vmin] = (u, plen) for v, w in graph.out_edges(vmin): if not paths[v]: cands.enqueue((plen + w, vmin, v)) count += 1 return paths def test_dijkstra(): paths00 = dijkstra_shortest_paths(g1, 0) paths01 = dijkstra_shortest_paths_0(g1, 0) # paths10 = dijkstra_shortest_paths(g1, 1) # paths11 = dijkstra_shortest_paths_0(g1, 1) # paths2 = dijkstra_shortest_paths(g1, 2) # paths3 = dijkstra_shortest_paths(g1, 3) # paths4 = dijkstra_shortest_paths(g1, 4) # paths5 = dijkstra_shortest_paths(g1, 5) # if (paths0 != [(0, 0), (3, 41), (0, 10), (2, 25), (0, 45), None] or # paths1 != [(2, 35), (1, 0), (1, 15), (2, 30), (1, 5), None] or # paths2 != [(2, 20), (3, 31), (2, 0), (2, 15), (1, 36), None] or # paths3 != [(2, 51), (3, 16), (1, 31), (3, 0), (1, 21), None] or
# # print("Some result are not correct.") print("start v0:", paths00) print("start v0:", paths01) # print("start v1:", paths10) # print("start v1:", paths11) # print("start v4:", paths4) # print("start v5:", paths5) # end test_dijkstra() if __name__ == '__main__': g1 = GraphAL(gmat4, inf) test_dijkstra()
# paths4 != [(2, 81), (3, 46), (1, 61), (4, 30), (4, 0), None] or # paths5 != [(2, 54), (3, 19), (1, 34), (5, 3), (1, 24), (5, 0)]):
mod.rs
//! Exchanges Handle incoming messages and forward them to other exhanges //! or queues. Each exchange is a lightweight process and handle messages //! through a channel. When a client is publishing to an exchange it should //! clone the exchange channel, so the messages will be handled serially. pub mod handler; pub mod manager; use crate::client::{self, ConnectionError}; use crate::Result; use metalmq_codec::frame::{self, ExchangeDeclareArgs, ExchangeDeclareFlags}; use serde_derive::Serialize; use std::str::FromStr; #[derive(Clone, Debug, PartialEq, Serialize)] pub enum ExchangeType { Direct, Topic, Fanout, Headers, } /// Descriptive information of the exchanges #[derive(Clone, Debug, PartialEq, Serialize)] pub struct Exchange { name: String, exchange_type: ExchangeType, durable: bool, auto_delete: bool, internal: bool, }
impl FromStr for ExchangeType { type Err = (); fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { match s { "direct" => Ok(ExchangeType::Direct), "topic" => Ok(ExchangeType::Topic), "fanout" => Ok(ExchangeType::Fanout), "headers" => Ok(ExchangeType::Headers), _ => Err(()), } } } pub fn validate_exchange_type(exchange_type: &str) -> Result<()> { match ExchangeType::from_str(exchange_type) { Ok(_) => Ok(()), Err(_) => client::connection_error( frame::EXCHANGE_DECLARE, ConnectionError::CommandInvalid, "COMMAND_INVALID - Exchange type is invalid", ), } } impl Default for Exchange { fn default() -> Exchange { Exchange { name: "default".to_string(), exchange_type: ExchangeType::Direct, durable: false, auto_delete: false, internal: false, } } } impl From<ExchangeDeclareArgs> for Exchange { fn from(f: ExchangeDeclareArgs) -> Self { Exchange { name: f.exchange_name, exchange_type: ExchangeType::from_str(&f.exchange_type).unwrap(), durable: ExchangeDeclareFlags::contains(&f.flags, ExchangeDeclareFlags::DURABLE), auto_delete: ExchangeDeclareFlags::contains(&f.flags, ExchangeDeclareFlags::AUTO_DELETE), internal: ExchangeDeclareFlags::contains(&f.flags, ExchangeDeclareFlags::INTERNAL), } } }
/// Convert String to ExchangeType
top-navigation-bar-back-button.component.tsx
import { useRouter } from 'next/router';
import styles from './top-navigation-bar-back-button.module.scss'; interface Props { goBackToPathname: string | null; isDisplayed: boolean; } export default function TopNavigationBarButton({ goBackToPathname, isDisplayed, }: Props): JSX.Element { const router = useRouter(); return ( <IconButton className={styles['iconButton']} style={!isDisplayed ? { display: 'none' } : {}} onClick={() => { if (goBackToPathname) router.push(goBackToPathname); }} data-testid="top-navigation-bar-back-button" > <FontAwesomeIcon className={styles['icon']} icon={{ prefix: 'far', iconName: 'caret-square-left' }} size="1x" /> </IconButton> ); }
import { IconButton } from '@mui/material'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
f1416.go
package internal func
(ctx *Context, l0 int32, l1 int32) int32 { var s0i32 int32 _ = s0i32 s0i32 = 29096 return s0i32 }
f1416
index.ts
import { onMounted, ref, Ref } from 'vue' import ace from 'ace-builds' import type { Ace } from 'ace-builds/ace'
ace.config.set('basePath', 'https://cdn.jsdelivr.net/npm/[email protected]/src-noconflict/') export enum Mode { hjson = 'ace/mode/hjson', go = 'ace/mode/golang' } export function useEditor(id: string, mode?: Mode) { const editor = ref<any>(null) onMounted(() => { editor.value = ace.edit(id, { useWorker: false }) editor.value.setTheme('ace/theme/tomorrow') if (mode) { editor.value.session.setMode(mode) } }) return { editor: editor as Ref<Ace.Editor> } }
plusplus_model.py
from peewee import SqliteDatabase, Model, CharField, IntegerField db = SqliteDatabase("plusplus.db") class Plusplus(Model): name = CharField(primary_key=True) # fields
database = db db.connect() db.create_tables([Plusplus], safe=True)
counter = IntegerField(default=0) class Meta:
LocalStorage.ts
import { ISyncAdapter, Maybe } from '../'; export default class
<T> implements ISyncAdapter<T> { public key: string; constructor(key: string) { this.key = key; } public read(): Maybe<T> { const value = localStorage.getItem(this.key); if (value === null) { return null; } return JSON.parse(value); } public write(data: Maybe<T>): void { localStorage.setItem(this.key, JSON.stringify(data)); } }
LocalStorage
webpack.config.js
/* eslint @typescript-eslint/no-var-requires: 0 */ const config = require("./webpack.config.dev.js");
resolve: { extensions: config.resolve.extensions, // Reset resolution back to defaults. Required for 'dist' mode. We want everything to be loaded from 'node_modules', // like it would in the end-user's app, with the exception of the source files for this example project. // modules: ...webpack defaults... alias: { "@upload.io/uploader-examples": config.resolve.alias["@upload.io/uploader-examples"] } } };
module.exports = { ...config,
rchttp_client.go
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/methods/go-methods-lib/common (interfaces: RCHTTPClienter) // Package mock_common is a generated GoMock package. package mock_common import ( context "context" io "io" http "net/http" url "net/url" reflect "reflect" time "time" gomock "github.com/golang/mock/gomock" ) // MockRCHTTPClienter is a mock of RCHTTPClienter interface type MockRCHTTPClienter struct { ctrl *gomock.Controller recorder *MockRCHTTPClienterMockRecorder } // MockRCHTTPClienterMockRecorder is the mock recorder for MockRCHTTPClienter type MockRCHTTPClienterMockRecorder struct { mock *MockRCHTTPClienter } // NewMockRCHTTPClienter creates a new mock instance func NewMockRCHTTPClienter(ctrl *gomock.Controller) *MockRCHTTPClienter
// EXPECT returns an object that allows the caller to indicate expected use func (m *MockRCHTTPClienter) EXPECT() *MockRCHTTPClienterMockRecorder { return m.recorder } // Do mocks base method func (m *MockRCHTTPClienter) Do(arg0 context.Context, arg1 *http.Request) (*http.Response, error) { ret := m.ctrl.Call(m, "Do", arg0, arg1) ret0, _ := ret[0].(*http.Response) ret1, _ := ret[1].(error) return ret0, ret1 } // Do indicates an expected call of Do func (mr *MockRCHTTPClienterMockRecorder) Do(arg0, arg1 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Do", reflect.TypeOf((*MockRCHTTPClienter)(nil).Do), arg0, arg1) } // Get mocks base method func (m *MockRCHTTPClienter) Get(arg0 context.Context, arg1 string) (*http.Response, error) { ret := m.ctrl.Call(m, "Get", arg0, arg1) ret0, _ := ret[0].(*http.Response) ret1, _ := ret[1].(error) return ret0, ret1 } // Get indicates an expected call of Get func (mr *MockRCHTTPClienterMockRecorder) Get(arg0, arg1 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockRCHTTPClienter)(nil).Get), arg0, arg1) } // GetMaxRetries mocks base method func (m *MockRCHTTPClienter) GetMaxRetries() int { ret := m.ctrl.Call(m, "GetMaxRetries") ret0, _ := ret[0].(int) return ret0 } // GetMaxRetries indicates an expected call of GetMaxRetries func (mr *MockRCHTTPClienterMockRecorder) GetMaxRetries() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMaxRetries", reflect.TypeOf((*MockRCHTTPClienter)(nil).GetMaxRetries)) } // Head mocks base method func (m *MockRCHTTPClienter) Head(arg0 context.Context, arg1 string) (*http.Response, error) { ret := m.ctrl.Call(m, "Head", arg0, arg1) ret0, _ := ret[0].(*http.Response) ret1, _ := ret[1].(error) return ret0, ret1 } // Head indicates an expected call of Head func (mr *MockRCHTTPClienterMockRecorder) Head(arg0, arg1 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Head", reflect.TypeOf((*MockRCHTTPClienter)(nil).Head), arg0, arg1) } // Post mocks base method func (m *MockRCHTTPClienter) Post(arg0 context.Context, arg1, arg2 string, arg3 io.Reader) (*http.Response, error) { ret := m.ctrl.Call(m, "Post", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(*http.Response) ret1, _ := ret[1].(error) return ret0, ret1 } // Post indicates an expected call of Post func (mr *MockRCHTTPClienterMockRecorder) Post(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Post", reflect.TypeOf((*MockRCHTTPClienter)(nil).Post), arg0, arg1, arg2, arg3) } // PostForm mocks base method func (m *MockRCHTTPClienter) PostForm(arg0 context.Context, arg1 string, arg2 url.Values) (*http.Response, error) { ret := m.ctrl.Call(m, "PostForm", arg0, arg1, arg2) ret0, _ := ret[0].(*http.Response) ret1, _ := ret[1].(error) return ret0, ret1 } // PostForm indicates an expected call of PostForm func (mr *MockRCHTTPClienterMockRecorder) PostForm(arg0, arg1, arg2 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostForm", reflect.TypeOf((*MockRCHTTPClienter)(nil).PostForm), arg0, arg1, arg2) } // Put mocks base method func (m *MockRCHTTPClienter) Put(arg0 context.Context, arg1, arg2 string, arg3 io.Reader) (*http.Response, error) { ret := m.ctrl.Call(m, "Put", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(*http.Response) ret1, _ := ret[1].(error) return ret0, ret1 } // Put indicates an expected call of Put func (mr *MockRCHTTPClienterMockRecorder) Put(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Put", reflect.TypeOf((*MockRCHTTPClienter)(nil).Put), arg0, arg1, arg2, arg3) } // SetAuthToken mocks base method func (m *MockRCHTTPClienter) SetAuthToken(arg0 string) { m.ctrl.Call(m, "SetAuthToken", arg0) } // SetAuthToken indicates an expected call of SetAuthToken func (mr *MockRCHTTPClienterMockRecorder) SetAuthToken(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetAuthToken", reflect.TypeOf((*MockRCHTTPClienter)(nil).SetAuthToken), arg0) } // SetDownloadServiceToken mocks base method func (m *MockRCHTTPClienter) SetDownloadServiceToken(arg0 string) { m.ctrl.Call(m, "SetDownloadServiceToken", arg0) } // SetDownloadServiceToken indicates an expected call of SetDownloadServiceToken func (mr *MockRCHTTPClienterMockRecorder) SetDownloadServiceToken(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDownloadServiceToken", reflect.TypeOf((*MockRCHTTPClienter)(nil).SetDownloadServiceToken), arg0) } // SetMaxRetries mocks base method func (m *MockRCHTTPClienter) SetMaxRetries(arg0 int) { m.ctrl.Call(m, "SetMaxRetries", arg0) } // SetMaxRetries indicates an expected call of SetMaxRetries func (mr *MockRCHTTPClienterMockRecorder) SetMaxRetries(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetMaxRetries", reflect.TypeOf((*MockRCHTTPClienter)(nil).SetMaxRetries), arg0) } // SetTimeout mocks base method func (m *MockRCHTTPClienter) SetTimeout(arg0 time.Duration) { m.ctrl.Call(m, "SetTimeout", arg0) } // SetTimeout indicates an expected call of SetTimeout func (mr *MockRCHTTPClienterMockRecorder) SetTimeout(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimeout", reflect.TypeOf((*MockRCHTTPClienter)(nil).SetTimeout), arg0) }
{ mock := &MockRCHTTPClienter{ctrl: ctrl} mock.recorder = &MockRCHTTPClienterMockRecorder{mock} return mock }
renderer.rs
use std::{io, mem::size_of}; use fj_math::{Aabb, Point}; use thiserror::Error; use tracing::debug; use wgpu::util::DeviceExt as _; use wgpu_glyph::ab_glyph::InvalidFont; use winit::dpi::PhysicalSize; use crate::{camera::Camera, window::Window}; use super::{ config_ui::ConfigUi, draw_config::DrawConfig, drawables::Drawables, geometries::Geometries, pipelines::Pipelines, transform::Transform, uniforms::Uniforms, vertices::Vertices, DEPTH_FORMAT, }; #[derive(Debug)] pub struct Renderer { surface: wgpu::Surface, device: wgpu::Device, queue: wgpu::Queue, surface_config: wgpu::SurfaceConfiguration, depth_view: wgpu::TextureView, uniform_buffer: wgpu::Buffer, bind_group: wgpu::BindGroup, geometries: Geometries, pipelines: Pipelines, config_ui: ConfigUi, } impl Renderer { pub async fn new(window: &Window) -> Result<Self, InitError> { let instance = wgpu::Instance::new(wgpu::Backends::PRIMARY); // This is sound, as `window` is an object to create a surface upon. let surface = unsafe { instance.create_surface(window.inner()) }; let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, force_fallback_adapter: false, compatible_surface: Some(&surface), }) .await .ok_or(InitError::RequestAdapter)?; let (device, queue) = adapter .request_device( &wgpu::DeviceDescriptor { label: None, // Don't just blindly assume that we can request this // feature. If it isn't available, that might cause a panic, // or an error to be returned here. // // See this issue: // https://github.com/hannobraun/fornjot/issues/33 features: wgpu::Features::POLYGON_MODE_LINE, limits: wgpu::Limits::default(), }, None, ) .await?; let color_format = surface .get_preferred_format(&adapter) .expect("Error determining preferred color format"); let surface_config = wgpu::SurfaceConfiguration { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format: color_format, width: window.width(), height: window.height(), present_mode: wgpu::PresentMode::Mailbox, }; surface.configure(&device, &surface_config); let depth_view = Self::create_depth_buffer(&device, &surface_config);
let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: None, contents: bytemuck::cast_slice(&[Uniforms::default()]), usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, }); let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::all(), ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: wgpu::BufferSize::new(size_of::< Uniforms, >( ) as u64), }, count: None, }], label: None, }); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &uniform_buffer, offset: 0, size: None, }), }], label: None, }); let geometries = Geometries::new( &device, &Vertices::empty(), &Vertices::empty(), Aabb { min: Point::from([0.0, 0.0, 0.0]), max: Point::from([0.0, 0.0, 0.0]), }, ); let pipelines = Pipelines::new(&device, &bind_group_layout, color_format); let config_ui = ConfigUi::new(&device, color_format)?; Ok(Self { surface, device, queue, surface_config, depth_view, uniform_buffer, bind_group, geometries, pipelines, config_ui, }) } pub fn update_geometry( &mut self, mesh: Vertices, lines: Vertices, aabb: Aabb<3>, ) { self.geometries = Geometries::new(&self.device, &mesh, &lines, aabb); } pub fn handle_resize(&mut self, size: PhysicalSize<u32>) { self.surface_config.width = size.width; self.surface_config.height = size.height; self.surface.configure(&self.device, &self.surface_config); let depth_view = Self::create_depth_buffer(&self.device, &self.surface_config); self.depth_view = depth_view; } pub fn draw( &mut self, camera: &Camera, config: &DrawConfig, ) -> Result<(), DrawError> { let aspect_ratio = self.surface_config.width as f64 / self.surface_config.height as f64; let uniforms = Uniforms { transform: Transform::for_vertices(camera, aspect_ratio), transform_normals: Transform::for_normals(camera), }; self.queue.write_buffer( &self.uniform_buffer, 0, bytemuck::cast_slice(&[uniforms]), ); let surface_texture = self.surface.get_current_texture()?; let color_view = surface_texture .texture .create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = self.device.create_command_encoder( &wgpu::CommandEncoderDescriptor { label: None }, ); self.clear_views(&mut encoder, &color_view); let drawables = Drawables::new(&self.geometries, &self.pipelines); if config.draw_model { drawables.model.draw( &mut encoder, &color_view, &self.depth_view, &self.bind_group, ); } if config.draw_mesh { drawables.mesh.draw( &mut encoder, &color_view, &self.depth_view, &self.bind_group, ); } if config.draw_debug { drawables.lines.draw( &mut encoder, &color_view, &self.depth_view, &self.bind_group, ); } self.config_ui .draw( &self.device, &mut encoder, &color_view, &self.surface_config, &self.geometries.aabb, config, ) .map_err(DrawError::Text)?; let command_buffer = encoder.finish(); self.queue.submit(Some(command_buffer)); debug!("Presenting..."); surface_texture.present(); debug!("Finished drawing."); Ok(()) } fn create_depth_buffer( device: &wgpu::Device, surface_config: &wgpu::SurfaceConfiguration, ) -> wgpu::TextureView { let texture = device.create_texture(&wgpu::TextureDescriptor { label: None, size: wgpu::Extent3d { width: surface_config.width, height: surface_config.height, depth_or_array_layers: 1, }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: DEPTH_FORMAT, usage: wgpu::TextureUsages::RENDER_ATTACHMENT, }); texture.create_view(&wgpu::TextureViewDescriptor::default()) } fn clear_views( &self, encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView, ) { encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: None, color_attachments: &[wgpu::RenderPassColorAttachment { view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::WHITE), store: true, }, }], depth_stencil_attachment: Some( wgpu::RenderPassDepthStencilAttachment { view: &self.depth_view, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: true, }), stencil_ops: None, }, ), }); } } #[derive(Error, Debug)] pub enum InitError { #[error("I/O error: {0}")] Io(#[from] io::Error), #[error("Error request adapter")] RequestAdapter, #[error("Error requesting device: {0}")] RequestDevice(#[from] wgpu::RequestDeviceError), #[error("Error loading font: {0}")] InvalidFont(#[from] InvalidFont), } #[derive(Error, Debug)] pub enum DrawError { #[error("Error acquiring output surface: {0}")] Surface(#[from] wgpu::SurfaceError), #[error("Error drawing text: {0}")] Text(String), }
append_to_array_with_comp.py
from array import array from random import randint import sys @profile def create_data():
def proc(): cnt = 0 data = create_data() for i in range(100000): if randint(1, 10000000) in data: cnt += 1 if __name__ == '__main__': print(sys.argv[0]) # print(sys.version_info) # import timeit # print(timeit.timeit("proc()", setup="from __main__ import proc", number=3)) # [proc() for i in range(3)] create_data()
return array('i', [randint(1, 10000000) for i in range(100000)])
mod.rs
// Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Local state for known snapshots. use chrono; use db; use hash; use std::sync::Arc; use tags; pub struct SnapshotIndex { index: Arc<db::Index>, } impl SnapshotIndex { pub fn new(idx: Arc<db::Index>) -> SnapshotIndex { SnapshotIndex { index: idx } } /// Delete snapshot. pub fn delete(&self, info: db::SnapshotInfo) { self.index.lock().snapshot_delete(info); } /// Lookup exact snapshot info from family and snapshot id. pub fn lookup( &mut self, family_name: &str, snapshot_id: u64, ) -> Option<(db::SnapshotInfo, hash::Hash, Option<hash::tree::HashRef>)> { self.index.lock().snapshot_lookup(family_name, snapshot_id) } pub fn reserve(&mut self, family: String) -> db::SnapshotInfo { self.index.lock().snapshot_reserve(family) } /// Update existing snapshot. pub fn update( &mut self, snapshot: &db::SnapshotInfo, hash: &hash::Hash, hash_ref: &hash::tree::HashRef, ) { self.index.lock().snapshot_update( snapshot, "anonymous", hash, hash_ref, ); } /// ReadyCommit. pub fn ready_commit(&mut self, snapshot: &db::SnapshotInfo)
/// Register a new snapshot by its family name, hash and persistent reference. pub fn commit(&mut self, snapshot: &db::SnapshotInfo) { self.index.lock().snapshot_set_tag( snapshot, tags::Tag::Done, ) } /// We are deleting this snapshot. pub fn will_delete(&mut self, snapshot: &db::SnapshotInfo) { self.index.lock().snapshot_set_tag( snapshot, tags::Tag::WillDelete, ) } /// We are ready to delete of this snapshot. pub fn ready_delete(&mut self, snapshot: &db::SnapshotInfo) { self.index.lock().snapshot_set_tag( snapshot, tags::Tag::ReadyDelete, ) } /// Extract latest snapshot data for family. pub fn latest( &mut self, family: &str, ) -> Option<(db::SnapshotInfo, hash::Hash, Option<hash::tree::HashRef>)> { self.index.lock().snapshot_latest(family) } fn list(&mut self, skip_tag: Option<tags::Tag>) -> Vec<db::SnapshotStatus> { self.index.lock().snapshot_list(skip_tag) } /// List incomplete snapshots (either committing or deleting). pub fn list_not_done(&mut self) -> Vec<db::SnapshotStatus> { self.list(Some(tags::Tag::Done) /* not_tag */) } /// List all snapshots. pub fn list_all(&mut self) -> Vec<db::SnapshotStatus> { self.list(None) } /// Recover snapshot information. pub fn recover( &mut self, snapshot_id: u64, family: &str, created: chrono::DateTime<chrono::Utc>, msg: &str, hash_ref: &hash::tree::HashRef, work_opt: Option<db::SnapshotWorkStatus>, ) { self.index.lock().snapshot_recover( snapshot_id, family, created, msg, hash_ref, work_opt, ) } /// Flush the hash index to clear internal buffers and commit the underlying database. pub fn flush(&mut self) { self.index.lock().flush() } }
{ self.index.lock().snapshot_set_tag( snapshot, tags::Tag::Complete, ) }
tree.py
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2020, empress development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import warnings from skbio import TreeNode import numpy as np from bp import BP, from_skbio_treenode class TreeFormatWarning(Warning): pass class Tree: """ Attributes ---------- length leafcount height depth Notes ----- `length` refers to the branch length of a node to its parent. `leafcount` is the number of tips within a subtree. `height` refers to the longest path from root to the deepst leaf in that subtree. `depth` is the number of nodes found in the longest path. """ def __init__(self, bp_tree): """ Constructs a Dendrogram object for visualization. Parameters ---------- bp_tree: bp.BP BP tree object Returns ------- """ self.bp_tree = bp_tree self.B = self.bp_tree.B self.leafcounts = np.zeros(self.B.size, np.int) self.depths = np.zeros(self.B.size, np.double) self.heights = np.zeros(self.B.size, np.double) self.yr = np.zeros(self.B.size, np.double) self.xr = np.zeros(self.B.size, np.double) self.highest_child_yr = np.zeros(self.B.size, np.float) self.lowest_child_yr = np.zeros(self.B.size, np.float) self.clangle = np.zeros(self.B.size, np.double) self.clradius = np.zeros(self.B.size, np.double) self.xc0 = np.zeros(self.B.size, np.double) self.yc0 = np.zeros(self.B.size, np.double) self.xc1 = np.zeros(self.B.size, np.double) self.yc1 = np.zeros(self.B.size, np.double) self.highest_child_clangle = np.zeros(self.B.size, np.float) self.lowest_child_clangle = np.zeros(self.B.size, np.float) self.arcx0 = np.zeros(self.B.size, np.double) self.arcy0 = np.zeros(self.B.size, np.double) self.arcx1 = np.zeros(self.B.size, np.double) self.arcy1 = np.zeros(self.B.size, np.double) self.x1 = np.zeros(self.B.size, np.double) self.y1 = np.zeros(self.B.size, np.double) self.x2 = np.zeros(self.B.size, np.double) self.y2 = np.zeros(self.B.size, np.double) self.angle = np.zeros(self.B.size, np.double) self.childRem = -1 @classmethod def from_tree(cls, tree, use_lengths=True): """ Creates an Tree object from a skbio tree. Parameters ---------- tree : skbio.TreeNode Input skbio tree use_lengths: Boolean Specify if the branch length should be incorporated into the geometry calculations for visualization. Returns ------- Tree: bp.BP """ bp_tree = from_skbio_treenode(tree) if sum(bp_tree.B) <= 1: raise ValueError("Tree must contain at least 2 nodes.") # While traversing the tree, record tip / internal node names # (Nodes without names are ignored, since we'll assign those later # using tools.fill_missing_node_names()) tip_names = [] internal_node_names = [] max_branch_length = 0 for i in range(sum(bp_tree.B)): node_idx = bp_tree.postorderselect(i) name = bp_tree.name(node_idx) length = bp_tree.length(node_idx) if name is not None: # NOTE: This should eventually be taken out when # fill_missing_node_names() is refactored. However, for now, # this makes sure that users can't accidentally break things by # naming nodes identical to our default names for missing nodes if name.startswith("EmpressNode"): raise ValueError( 'Node names can\'t start with "EmpressNode".' ) if isleaf(bp_tree, node_idx): tip_names.append(name) else: internal_node_names.append(name) if length is None: raise ValueError( "Non-root branches of the tree must have lengths." ) if length < 0: raise ValueError( "Non-root branches of the tree must have nonnegative " "lengths." ) max_branch_length = max(length, max_branch_length) # We didn't consider the root node in the above traversal since we # don't care about its length. However, we do care about its name, # so we add the root's name to internal_node_names. if max_branch_length == 0: raise ValueError( "At least one non-root branch of the tree must have a " "positive length." ) unique_tip_name_set = set(tip_names) if len(unique_tip_name_set) != len(tip_names): raise ValueError("Tip names in the tree must be unique.") unique_internal_node_name_set = set(internal_node_names) if len(unique_tip_name_set & unique_internal_node_name_set) > 0: raise ValueError( "Tip names in the tree cannot overlap with internal node " "names." ) if len(unique_internal_node_name_set) != len(internal_node_names): warnings.warn( "Internal node names in the tree are not unique.", TreeFormatWarning ) bp_tree = Tree(bp_tree) bp_tree.update_geometry(use_lengths) return bp_tree def postorder(self, include_self=True): e = sum(self.B) if include_self else sum(self.B) - 1 for i in range(e): node_idx = self.bp_tree.postorderselect(i) yield node_idx def preorder(self, include_self=True): s = 0 if include_self else 1 for i in range(s, sum(self.B)): node_idx = self.bp_tree.preorderselect(i) yield node_idx def bp_tree_tips(self): """ Extracts tip names in the tree, ignoring unnamed tips. Parameters ---------- bp_tree : bp.BP Input BP tree Returns ------- tips : list of strings list of tip names in the tree """ tips = [] # Iterate through all open and closing parentheses and extract tip names for i in range(self.B.size): pos_name = self.bp_tree.name(i) # Check if this is a leaf node with a label if self.isleaf(i) and (pos_name is not None): tips.append(pos_name) return tips def bp_tree_non_tips(self): """ Extracts internal node names in the tree, ignoring unnamed nodes. Parameters ---------- bp_tree : bp.BP Input BP tree Returns ------- non_tips : list of strings list of internal node names in the tree """ non_tips = [] for i in range(self.B.size): pos_name = self.bp_tree.name(i) # Check if this is an opening parenthesis, is not a leaf, and # has a node label if self.B[i] and not self.isleaf(i) and pos_name is not None: non_tips.append(pos_name) return non_tips def update_geometry(self, use_lengths, depth=None): """Calculate tree node attributes such as height and depth. Parameters ---------- use_lengths: bool Specify if the branch length should be incorporated into the geometry calculations for visualization. depth: int The number of nodes in the longest path from root to leaf. This is agnostic to scale and orientation. """ new_heights = np.zeros(self.B.size, dtype=np.double) new_leaf_count = np.zeros(self.B.size, dtype=np.int) new_depths = np.zeros(self.B.size, dtype=np.double) for node_idx in self.postorder(): length = self.bp_tree.length(node_idx) if length is None or not use_lengths: if not use_lengths: if self.isleaf(node_idx): length = 5 else: length = 1 else: length = 0 new_depths[node_idx] = (depth or 0) + length if self.isleaf(node_idx): new_heights[node_idx] = length new_leaf_count[node_idx] = 1 else: idx = self.bp_tree.fchild(node_idx) height = 0 leafcount = 0 while idx: height = max(height, new_heights[idx]) leafcount += new_leaf_count[idx] idx = self.bp_tree.nsibling(idx) height += length new_heights[node_idx] = height new_leaf_count[node_idx] = leafcount self.leafcounts = new_leaf_count self.heights = new_heights self.depths = new_depths def coords(self, height, width): """ Computes the coordinates of nodes to be rendered in plot. This runs multiple layout algorithms and saves all of the resulting coordinates for each node, so that layout algorithms can be rapidly toggled between in the JS interface. Also adds on .highest_child_yr and .lowest_child_yr attributes to internal nodes so that vertical bars for these nodes can be drawn in the rectangular layout. Parameters ---------- height : int The height of the canvas. width : int The width of the canvas. Returns ------- dict: Mapping between layout and the coordinate suffix. str: Name of the default layout. """ layout_to_coordsuffix = {} layout_algs = ( self.layout_unrooted, self.layout_rectangular, self.layout_circular, ) # We set the default layout to whatever the first layout in # layout_algs is, but this behavior is of course modifiable default_layout = None for alg in layout_algs: name, suffix = alg(width, height) layout_to_coordsuffix[name] = suffix self.alter_coordinates_relative_to_root(suffix) if name == "Circular": self.alter_coordinates_relative_to_root("c0") if default_layout is None: default_layout = name # Determine highest and lowest child y-position for internal nodes in # the rectangular layout; used to draw vertical lines for these nodes. # # NOTE / TODO: This will have the effect of drawing vertical lines even # for nodes with only 1 child -- in this case lowest_child_yr == # highest_child_yr for this node, so all of the stuff drawn in WebGL # for this vertical line shouldn't show up. I don't think this should # cause any problems, but it may be worth detecting these cases and not # drawing vertical lines for them in the future. for node_idx in self.preorder(): if not self.isleaf(node_idx): # wow, child does not look like a word any more self.highest_child_yr[node_idx] = float("-inf") self.lowest_child_yr[node_idx] = float("inf") for c_idx in self.children(node_idx): if self.yr[c_idx] > self.highest_child_yr[node_idx]: self.highest_child_yr[node_idx] = self.yr[c_idx] if self.yr[c_idx] < self.lowest_child_yr[node_idx]: self.lowest_child_yr[node_idx] = self.yr[c_idx] return layout_to_coordsuffix, default_layout def alter_coordinates_relative_to_root(self, suffix): """ Subtracts the root node's x- and y- coords from all nodes' coords. This was previously done within coords(), but I moved it here so that this logic can be used after arbitrary layout computations. Parameters ---------- suffix : str The suffix of the x- and y-coordinates to adjust. For example, this is "2" for the unrooted layout since coordinates are stored in the x2 and y2 attributes for every node; and it's "r" for the rectangular layout since the coordinate attributes are now xr and yr. """ xname = "x" + suffix yname = "y" + suffix centersX = getattr(self, xname) centersY = getattr(self, yname) centerX = centersX[0] centerY = centersY[0] for node_idx in self.postorder(): # This code might look sort of intimidating, but it's really just # another way to write out: # node.x2 = node.x2 - centerX # node.y2 = node.y2 - centerY # ...when we don't know what "x2" or "y2" will be named beforehand. centersX[node_idx] = centersX[node_idx] - centerX centersY[node_idx] = centersY[node_idx] - centerY setattr(self, xname, centersX) setattr(self, yname, centersY) def isleaf(self, i): """ Checks if node at position i belongs to a leaf node or not Parameters ---------- bp_tree : bp.BP Input BP tree i : int The query node index Returns ------- bool True if this is a leaf node, False otherwise """ return self.B[i] and (not self.B[i + 1]) def children(self, i): children = [] child = self.bp_tree.fchild(i) while child > 0: children.append(child) child = self.bp_tree.nsibling(child) return children def layout_rectangular(self, width, height): """ Rectangular layout. In this sort of layout, each tip has a distinct y-position, and parent y-positions are centered over their descendant tips' positions. x-positions are computed based on nodes' branch lengths. Following this algorithm, nodes' rectangular layout coordinates are accessible at [node].xr and [node].yr. For a simple tree, this layout should look something like: __ ___| ___| |__ | |___ | ___ |___| |___ Parameters ---------- width : float width of the canvas height : float height of the canvas References ---------- https://rachel53461.wordpress.com/2014/04/20/algorithm-for-drawing-trees/ Clear explanation of Reingold-Tilford that I used a lot https://github.com/qiime/Topiary-Explorer/blob/master/src/topiaryexplorer/TreeVis.java Derived from the "Rectangular" layout algorithm code. """ # NOTE: This doesn't draw a horizontal line leading to the root "node" # of the graph. See https://github.com/biocore/empress/issues/141 for # context. max_width = 0 max_height = 0 prev_y = 0 for node_idx in self.postorder(): if self.isleaf(node_idx): self.yr[node_idx] = prev_y prev_y += 1 if self.yr[node_idx] > max_height: max_height = self.yr[node_idx] else: # Center internal nodes above their children # We could also center them above their tips, but (IMO) this # looks better ;) children = self.children(node_idx) self.yr[node_idx] = sum([self.yr[c_idx] for c_idx in children]) / len(children) for node_idx in self.preorder(include_self=False): self.xr[node_idx] = self.xr[self.bp_tree.parent(node_idx)] + \ self.bp_tree.length(node_idx) if self.xr[node_idx] > max_width: max_width = self.xr[node_idx] # We don't check if max_width == 0 here, because we check when # constructing an Empress tree that it has at least one positive # branch length and no negative branch lengths. (And if this is the # case, then max_width must be > 0.) x_scaling_factor = width / max_width if max_height > 0: # Having a max_height of 0 could actually happen, in the funky case # where the entire tree is a straight line (e.g. A -> B -> C). In # this case our "rectangular layout" drawing places all nodes on # the same y-coordinate (0), resulting in max_height = 0. # ... So, that's why we only do y-scaling if this *isn't* the case. y_scaling_factor = height / max_height else: # Since this will be multiplied by 0 for every node, we can set # this to any real number and get the intended "effect" of keeping # every node's y-coordinate at 0. y_scaling_factor = 1 for node_idx in self.preorder(): self.xr[node_idx] *= x_scaling_factor self.yr[node_idx] *= y_scaling_factor # Now we have the layout! In the JS we'll need to draw each internal # node as a vertical line ranging from its lowest child y-position to # its highest child y-position, and then draw horizontal lines from # this line to all of its child nodes (where the length of the # horizontal line is proportional to the node length in question). return "Rectangular", "r" def layout_circular(self, width, height): """ Circular layout version of the rectangular layout. Works analogously to the rectangular layout: -Each tip is assigned a unique angle from the "center"/root of the tree (out of the range [0, 2pi] in radians), and internal nodes are set to an angle equal to the average of their children's. This mirrors the assignment of y-coordinates for the rectangular layout. -All nodes are then assigned a radius equal to the sum of their branch lengths descending from the root (but not including the root's branch length, if provided -- the root is represented as just a single point in the center of the layout). This mirrors the assignment of x-coordinates for the rectangular layout. -Lastly, we'll draw arcs for every internal node (except for the root) connecting the "start points" of the child nodes of that node with the minimum and maximum angle. (These points should occur at the radius equal to the "end" of the given internal node.) We don't draw this arc for the root node because we don't draw the root the same way we do the other nodes in the tree: the root is represented as just a single point at the center of the layout. Due to this, there isn't a way to draw an arc from the root, since the root's "end" is at the same point as its beginning (so the arc wouldn't be visible). Following this algorithm, nodes' circular layout coordinates are accessible at [node].xc and [node].yc. Angles will also be available at [node].clangle, and radii will be available at [node].clradius; and for non-root internal nodes, arc start and end coordinates will be available at [node].arcx0, [node].arcy0, [node].arcx1, & [node].arcy1. Parameters ---------- width : float width of the canvas height : float height of the canvas References ---------- https://github.com/qiime/Topiary-Explorer/blob/master/src/topiaryexplorer/TreeVis.java Description above + the implementation of this algorithm derived from the Polar layout algorithm code. """ anglepernode = (2 * np.pi) / self.leafcounts[0] prev_clangle = 0 for node_idx in self.postorder(): if self.isleaf(node_idx): self.clangle[node_idx] = prev_clangle prev_clangle += anglepernode else: # Center internal nodes at an angle above their children children = self.children(node_idx) child_clangle_sum = sum([self.clangle[c_idx] for c_idx in children]) self.clangle[node_idx] = child_clangle_sum / len(children) max_clradius = 0 for node_idx in self.preorder(include_self=False): self.clradius[node_idx] = self.clradius[self.bp_tree.parent(node_idx)] + \ self.bp_tree.length(node_idx) if self.clradius[node_idx] > max_clradius: max_clradius = self.clradius[node_idx] # Now that we have the polar coordinates of the nodes, convert these # coordinates to normal x/y coordinates. # NOTE that non-root nodes will actually have two x/y coordinates we # need to keep track of: one for the "end" of the node's line, and # another for the "start" of the node's line. The latter of these is # needed because the node's line begins at the parent node's radius but # the child node's angle, if that makes sense -- and since converting # from polar to x/y and back is annoying, it's easiest to just compute # this in python. max_x = max_y = float("-inf") min_x = min_y = float("inf") for node_idx in self.postorder(): self.xc1[node_idx] = self.clradius[node_idx] * \ np.cos(self.clangle[node_idx]) self.yc1[node_idx] = self.clradius[node_idx] * \ np.sin(self.clangle[node_idx]) if self.isleaf(node_idx): # NOTE that the root has a clradius of 0 (since it's just # represented as a point at the center of the layout). We don't # even bother drawing the root in the Empress JS code, but for # the purposes of alter_coordinates_relative_to_root() we need # to explicitly position the root at (0, 0). self.xc0[node_idx] = 0 self.yc0[node_idx] = 0 else: self.xc0[node_idx] = self.clradius[ self.bp_tree.parent(node_idx)] *\ np.cos(self.clangle[node_idx]) self.yc0[node_idx] = self.clradius[ self.bp_tree.parent(node_idx)] *\ np.sin(self.clangle[node_idx]) # NOTE: We don't bother testing the xc0 / yc0 coordinates as # "extrema" because they should always be further "within" the # tree than the xc1 / yc1 coordinates. # TODO: verify that the "tree is a line" case doesn't mess this up. if self.xc1[node_idx] > max_x: max_x = self.xc1[node_idx] if self.yc1[node_idx] > max_y: max_y = self.yc1[node_idx] if self.xc1[node_idx] < min_x: min_x = self.xc1[node_idx] if self.yc1[node_idx] < min_y: min_y = self.yc1[node_idx] # TODO: raise error if the maximum and minimum are same for x or y. # may happen if the tree is a straight line. # set scaling factors # normalize the coordinate based on the largest dimension width_scale = width / (max_x - min_x) height_scale = height / (max_y - min_y) scale_factor = width_scale if width_scale > height_scale else \ height_scale x_scaling_factor = scale_factor y_scaling_factor = scale_factor for node_idx in self.preorder(): self.xc0[node_idx] *= x_scaling_factor self.yc0[node_idx] *= y_scaling_factor self.xc1[node_idx] *= x_scaling_factor self.yc1[node_idx] *= y_scaling_factor if not self.isleaf(node_idx) and (node_idx != 0): self.highest_child_clangle[node_idx] = float("-inf") self.lowest_child_clangle[node_idx] = float("inf") for c_idx in self.children(node_idx): if self.clangle[c_idx] >\ self.highest_child_clangle[node_idx]: self.highest_child_clangle[node_idx] =\ self.clangle[c_idx] if self.clangle[c_idx] < \ self.lowest_child_clangle[node_idx]: self.lowest_child_clangle[node_idx] =\ self.clangle[c_idx] # Figure out "arc" endpoints for the circular layout # NOTE: As with the "vertical lines" for internal nodes in the # rectangular layout, these arcs will be drawn for nodes with # only one child. Here, this case would mean that the # highest_child_clangle would equal the lowest_child_clangle, # so arcx0 would equal arcx1 and arcy0 would equal arcy1. So # nothing should show up (but it may be worth addressing this # in the future). self.arcx0[node_idx] = self.clradius[node_idx] * \ np.cos( self.highest_child_clangle[node_idx]) self.arcy0[node_idx] = self.clradius[node_idx] * \ np.sin( self.highest_child_clangle[node_idx]) self.arcx1[node_idx] = self.clradius[node_idx] * \ np.cos( self.lowest_child_clangle[node_idx]) self.arcy1[node_idx] = self.clradius[node_idx] * \ np.sin( self.lowest_child_clangle[node_idx]) self.arcx0[node_idx] *= x_scaling_factor self.arcy0[node_idx] *= y_scaling_factor self.arcx1[node_idx] *= x_scaling_factor self.arcy1[node_idx] *= y_scaling_factor return "Circular", "c1" def layout_unrooted(self, width, height): """ Find best scaling factor for fitting the tree in the figure. This method will find the best orientation and scaling possible to fit the tree within the dimensions specified by width and height, using an unrooted layout algorithm. Following this algorithm, nodes' unrooted layout coordinates are accessible at [node].x2 and [node].y2. Parameters ---------- width : float width of the canvas height : float height of the canvas Returns ------- best_scaling : float largest scaling factor in which the tree can fit in the canvas. Notes ----- """ # Recall that 360 degrees is equal to (2 * pi) radians. # You can think of this variable as "the maximum angle we can 'give' to # each leaf of the tree". angle = (2 * np.pi) / self.leafcounts[0] best_scale = 0 for i in range(60): direction = i / 60.0 * np.pi (max_x, min_x, max_y, min_y) = self.update_unrooted_coords( 1.0, 0, 0, direction, angle) x_diff = max_x - min_x width_min = 0 if x_diff != 0: width_min = float(width) / x_diff y_diff = max_y - min_y height_min = 0 if y_diff != 0: height_min = float(height) / y_diff scale = min(width_min, height_min) scale *= 0.95 # extra margin for labels if scale >= best_scale: best_scale = scale mid_x = width / 2 - ((max_x + min_x) / 2) * scale mid_y = height / 2 - ((max_y + min_y) / 2) * scale best_args = (scale, mid_x, mid_y, direction, angle) self.update_unrooted_coords(*best_args) return "Unrooted", "2" def update_unrooted_coords(self, s, x1, y1, a, da): """ Update x, y coordinates of tree nodes in canvas. This function will update the x1, y1, x2, y2, and angle attributes for all of the nodes within the tree. Note that (once the unrooted layout has finished) all that is really used are the x2 and y2 attributes. In a server-based version of Empress, this could be applied when the tree becomes modified (i.e. pruning or collapsing) and the resulting coordinates would be modified to reflect the changes to the tree structure. (In practice, we just run this once on the Python side of things in order to precompute the layout.) Parameters ---------- s : float scaling x1 : float x midpoint y1 : float y midpoint a : float angle (degrees) da : float angle resolution (degrees) Returns ------- points : list of tuple 2D coordinates of all of the nodes. """ max_x = float('-inf') min_x = float('inf') max_y = float('-inf') min_y = float('inf') # calculates self coords/angle # Constant angle algorithm. Should add maximum daylight step. x2 = x1 + self.bp_tree.length(0) * s * np.sin(a) y2 = y1 + self.bp_tree.length(0) * s * np.cos(a) (self.x1[0], self.y1[0], self.x2[0], self.y2[0], self.angle[0]) = \ (x1, y1, x2, y2, a) node_indices = [node_idx for node_idx in self.postorder(include_self=False)] node_indices.reverse() # for node in self.preorder(include_self=False): for node_idx in node_indices: x1 = self.x2[self.bp_tree.parent(node_idx)] y1 = self.y2[self.bp_tree.parent(node_idx)] # init a a = self.angle[self.bp_tree.parent(node_idx)] # same modify across nodes a = a - self.leafcounts[self.bp_tree.parent(node_idx)] * da / 2 # check for conditional higher order for sib_idx in self.children(self.bp_tree.parent(node_idx)): if sib_idx != node_idx: a += self.leafcounts[sib_idx] * da else: a += (self.leafcounts[node_idx] * da) / 2 break # Constant angle algorithm. Should add maximum daylight step. x2 = x1 + self.bp_tree.length(node_idx) * s * np.sin(a) y2 = y1 + self.bp_tree.length(node_idx) * s * np.cos(a) (self.x1[node_idx], self.y1[node_idx], self.x2[node_idx], self.y2[node_idx], self.angle[node_idx]) = (x1, y1, x2, y2, a) max_x, min_x = max(max_x, x2), min(min_x, x2) max_y, min_y = max(max_y, y2), min(min_y, y2) return (max_x, min_x, max_y, min_y) def
(bp_tree, i): """ Checks if node at position i belongs to a leaf node or not Parameters ---------- bp_tree : bp.BP Input BP tree i : int The query node index Returns ------- bool True if this is a leaf node, False otherwise """ return bp_tree.B[i] and (not bp_tree.B[i + 1])
isleaf
gltf2_blender_extract.py
# Copyright 2018-2021 The glTF-Blender-IO authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np from mathutils import Vector from . import gltf2_blender_export_keys from ...io.com.gltf2_io_debug import print_console from io_scene_gltf2.blender.exp import gltf2_blender_gather_skins def extract_primitives(glTF, blender_mesh, library, blender_object, blender_vertex_groups, modifiers, export_settings): """Extract primitives from a mesh.""" print_console('INFO', 'Extracting primitive: ' + blender_mesh.name) use_normals = export_settings[gltf2_blender_export_keys.NORMALS] if use_normals: blender_mesh.calc_normals_split() use_tangents = False if use_normals and export_settings[gltf2_blender_export_keys.TANGENTS]: if blender_mesh.uv_layers.active and len(blender_mesh.uv_layers) > 0: try: blender_mesh.calc_tangents() use_tangents = True except Exception: print_console('WARNING', 'Could not calculate tangents. Please try to triangulate the mesh first.') tex_coord_max = 0 if export_settings[gltf2_blender_export_keys.TEX_COORDS]: if blender_mesh.uv_layers.active: tex_coord_max = len(blender_mesh.uv_layers) color_max = 0 if export_settings[gltf2_blender_export_keys.COLORS]: color_max = len(blender_mesh.vertex_colors) armature = None skin = None if blender_vertex_groups and export_settings[gltf2_blender_export_keys.SKINS]: if modifiers is not None: modifiers_dict = {m.type: m for m in modifiers} if "ARMATURE" in modifiers_dict: modifier = modifiers_dict["ARMATURE"] armature = modifier.object # Skin must be ignored if the object is parented to a bone of the armature # (This creates an infinite recursive error) # So ignoring skin in that case is_child_of_arma = ( armature and blender_object and blender_object.parent_type == "BONE" and blender_object.parent.name == armature.name ) if is_child_of_arma: armature = None if armature: skin = gltf2_blender_gather_skins.gather_skin(armature, export_settings) if not skin: armature = None use_morph_normals = use_normals and export_settings[gltf2_blender_export_keys.MORPH_NORMAL] use_morph_tangents = use_morph_normals and use_tangents and export_settings[gltf2_blender_export_keys.MORPH_TANGENT] key_blocks = [] if blender_mesh.shape_keys and export_settings[gltf2_blender_export_keys.MORPH]: key_blocks = [ key_block for key_block in blender_mesh.shape_keys.key_blocks if not (key_block == key_block.relative_key or key_block.mute) ] use_materials = export_settings[gltf2_blender_export_keys.MATERIALS] # Fetch vert positions and bone data (joint,weights) locs, morph_locs = __get_positions(blender_mesh, key_blocks, armature, blender_object, export_settings) if skin: vert_bones, num_joint_sets = __get_bone_data(blender_mesh, skin, blender_vertex_groups) # In Blender there is both per-vert data, like position, and also per-loop # (loop=corner-of-poly) data, like normals or UVs. glTF only has per-vert # data, so we need to split Blender verts up into potentially-multiple glTF # verts. # # First, we'll collect a "dot" for every loop: a struct that stores all the # attributes at that loop, namely the vertex index (which determines all # per-vert data), and all the per-loop data like UVs, etc. # # Each unique dot will become one unique glTF vert. # List all fields the dot struct needs. dot_fields = [('vertex_index', np.uint32)] if use_normals: dot_fields += [('nx', np.float32), ('ny', np.float32), ('nz', np.float32)] if use_tangents: dot_fields += [('tx', np.float32), ('ty', np.float32), ('tz', np.float32), ('tw', np.float32)] for uv_i in range(tex_coord_max): dot_fields += [('uv%dx' % uv_i, np.float32), ('uv%dy' % uv_i, np.float32)] for col_i in range(color_max): dot_fields += [ ('color%dr' % col_i, np.float32), ('color%dg' % col_i, np.float32), ('color%db' % col_i, np.float32), ('color%da' % col_i, np.float32), ] if use_morph_normals: for morph_i, _ in enumerate(key_blocks): dot_fields += [ ('morph%dnx' % morph_i, np.float32), ('morph%dny' % morph_i, np.float32), ('morph%dnz' % morph_i, np.float32), ] dots = np.empty(len(blender_mesh.loops), dtype=np.dtype(dot_fields)) vidxs = np.empty(len(blender_mesh.loops)) blender_mesh.loops.foreach_get('vertex_index', vidxs) dots['vertex_index'] = vidxs del vidxs if use_normals: kbs = key_blocks if use_morph_normals else [] normals, morph_normals = __get_normals( blender_mesh, kbs, armature, blender_object, export_settings ) dots['nx'] = normals[:, 0] dots['ny'] = normals[:, 1] dots['nz'] = normals[:, 2] del normals for morph_i, ns in enumerate(morph_normals): dots['morph%dnx' % morph_i] = ns[:, 0] dots['morph%dny' % morph_i] = ns[:, 1] dots['morph%dnz' % morph_i] = ns[:, 2] del morph_normals if use_tangents: tangents = __get_tangents(blender_mesh, armature, blender_object, export_settings) dots['tx'] = tangents[:, 0] dots['ty'] = tangents[:, 1] dots['tz'] = tangents[:, 2] del tangents signs = __get_bitangent_signs(blender_mesh, armature, blender_object, export_settings) dots['tw'] = signs del signs for uv_i in range(tex_coord_max): uvs = __get_uvs(blender_mesh, uv_i) dots['uv%dx' % uv_i] = uvs[:, 0] dots['uv%dy' % uv_i] = uvs[:, 1] del uvs for col_i in range(color_max): colors = __get_colors(blender_mesh, col_i) dots['color%dr' % col_i] = colors[:, 0] dots['color%dg' % col_i] = colors[:, 1] dots['color%db' % col_i] = colors[:, 2] dots['color%da' % col_i] = colors[:, 3] del colors # Calculate triangles and sort them into primitives. blender_mesh.calc_loop_triangles() loop_indices = np.empty(len(blender_mesh.loop_triangles) * 3, dtype=np.uint32) blender_mesh.loop_triangles.foreach_get('loops', loop_indices) prim_indices = {} # maps material index to TRIANGLES-style indices into dots if use_materials == "NONE": # Only for None. For placeholder and export, keep primitives # Put all vertices into one primitive prim_indices[-1] = loop_indices else: # Bucket by material index. tri_material_idxs = np.empty(len(blender_mesh.loop_triangles), dtype=np.uint32) blender_mesh.loop_triangles.foreach_get('material_index', tri_material_idxs) loop_material_idxs = np.repeat(tri_material_idxs, 3) # material index for every loop unique_material_idxs = np.unique(tri_material_idxs) del tri_material_idxs for material_idx in unique_material_idxs: prim_indices[material_idx] = loop_indices[loop_material_idxs == material_idx] # Create all the primitives. primitives = [] for material_idx, dot_indices in prim_indices.items(): # Extract just dots used by this primitive, deduplicate them, and # calculate indices into this deduplicated list. prim_dots = dots[dot_indices] prim_dots, indices = np.unique(prim_dots, return_inverse=True) if len(prim_dots) == 0: continue # Now just move all the data for prim_dots into attribute arrays attributes = {} blender_idxs = prim_dots['vertex_index'] attributes['POSITION'] = locs[blender_idxs] for morph_i, vs in enumerate(morph_locs): attributes['MORPH_POSITION_%d' % morph_i] = vs[blender_idxs] if use_normals: normals = np.empty((len(prim_dots), 3), dtype=np.float32) normals[:, 0] = prim_dots['nx'] normals[:, 1] = prim_dots['ny'] normals[:, 2] = prim_dots['nz'] attributes['NORMAL'] = normals if use_tangents: tangents = np.empty((len(prim_dots), 4), dtype=np.float32) tangents[:, 0] = prim_dots['tx'] tangents[:, 1] = prim_dots['ty'] tangents[:, 2] = prim_dots['tz'] tangents[:, 3] = prim_dots['tw'] attributes['TANGENT'] = tangents if use_morph_normals: for morph_i, _ in enumerate(key_blocks): ns = np.empty((len(prim_dots), 3), dtype=np.float32) ns[:, 0] = prim_dots['morph%dnx' % morph_i] ns[:, 1] = prim_dots['morph%dny' % morph_i] ns[:, 2] = prim_dots['morph%dnz' % morph_i] attributes['MORPH_NORMAL_%d' % morph_i] = ns if use_morph_tangents: attributes['MORPH_TANGENT_%d' % morph_i] = __calc_morph_tangents(normals, ns, tangents) for tex_coord_i in range(tex_coord_max): uvs = np.empty((len(prim_dots), 2), dtype=np.float32) uvs[:, 0] = prim_dots['uv%dx' % tex_coord_i] uvs[:, 1] = prim_dots['uv%dy' % tex_coord_i] attributes['TEXCOORD_%d' % tex_coord_i] = uvs for color_i in range(color_max): colors = np.empty((len(prim_dots), 4), dtype=np.float32) colors[:, 0] = prim_dots['color%dr' % color_i] colors[:, 1] = prim_dots['color%dg' % color_i] colors[:, 2] = prim_dots['color%db' % color_i] colors[:, 3] = prim_dots['color%da' % color_i] attributes['COLOR_%d' % color_i] = colors if skin: joints = [[] for _ in range(num_joint_sets)] weights = [[] for _ in range(num_joint_sets)] for vi in blender_idxs: bones = vert_bones[vi] for j in range(0, 4 * num_joint_sets): if j < len(bones): joint, weight = bones[j] else: joint, weight = 0, 0.0 joints[j//4].append(joint) weights[j//4].append(weight) for i, (js, ws) in enumerate(zip(joints, weights)): attributes['JOINTS_%d' % i] = js attributes['WEIGHTS_%d' % i] = ws primitives.append({ 'attributes': attributes, 'indices': indices, 'material': material_idx, }) if export_settings['gltf_loose_edges']: # Find loose edges loose_edges = [e for e in blender_mesh.edges if e.is_loose] blender_idxs = [vi for e in loose_edges for vi in e.vertices] if blender_idxs: # Export one glTF vert per unique Blender vert in a loose edge blender_idxs = np.array(blender_idxs, dtype=np.uint32) blender_idxs, indices = np.unique(blender_idxs, return_inverse=True) attributes = {} attributes['POSITION'] = locs[blender_idxs] for morph_i, vs in enumerate(morph_locs): attributes['MORPH_POSITION_%d' % morph_i] = vs[blender_idxs] if skin: joints = [[] for _ in range(num_joint_sets)] weights = [[] for _ in range(num_joint_sets)] for vi in blender_idxs: bones = vert_bones[vi] for j in range(0, 4 * num_joint_sets): if j < len(bones): joint, weight = bones[j] else: joint, weight = 0, 0.0 joints[j//4].append(joint) weights[j//4].append(weight) for i, (js, ws) in enumerate(zip(joints, weights)): attributes['JOINTS_%d' % i] = js attributes['WEIGHTS_%d' % i] = ws primitives.append({ 'attributes': attributes, 'indices': indices, 'mode': 1, # LINES 'material': 0, }) if export_settings['gltf_loose_points']: # Find loose points verts_in_edge = set(vi for e in blender_mesh.edges for vi in e.vertices) blender_idxs = [ vi for vi, _ in enumerate(blender_mesh.vertices) if vi not in verts_in_edge ] if blender_idxs: blender_idxs = np.array(blender_idxs, dtype=np.uint32) attributes = {} attributes['POSITION'] = locs[blender_idxs] for morph_i, vs in enumerate(morph_locs): attributes['MORPH_POSITION_%d' % morph_i] = vs[blender_idxs] if skin: joints = [[] for _ in range(num_joint_sets)] weights = [[] for _ in range(num_joint_sets)] for vi in blender_idxs: bones = vert_bones[vi] for j in range(0, 4 * num_joint_sets): if j < len(bones): joint, weight = bones[j] else: joint, weight = 0, 0.0 joints[j//4].append(joint) weights[j//4].append(weight) for i, (js, ws) in enumerate(zip(joints, weights)): attributes['JOINTS_%d' % i] = js attributes['WEIGHTS_%d' % i] = ws primitives.append({ 'attributes': attributes, 'mode': 0, # POINTS 'material': 0, }) print_console('INFO', 'Primitives created: %d' % len(primitives)) return primitives def __get_positions(blender_mesh, key_blocks, armature, blender_object, export_settings): locs = np.empty(len(blender_mesh.vertices) * 3, dtype=np.float32) source = key_blocks[0].relative_key.data if key_blocks else blender_mesh.vertices source.foreach_get('co', locs) locs = locs.reshape(len(blender_mesh.vertices), 3) morph_locs = [] for key_block in key_blocks: vs = np.empty(len(blender_mesh.vertices) * 3, dtype=np.float32) key_block.data.foreach_get('co', vs) vs = vs.reshape(len(blender_mesh.vertices), 3) morph_locs.append(vs) # Transform for skinning if armature and blender_object: apply_matrix = armature.matrix_world.inverted_safe() @ blender_object.matrix_world loc_transform = armature.matrix_world @ apply_matrix loc_transform = blender_object.matrix_world locs[:] = __apply_mat_to_all(loc_transform, locs) for vs in morph_locs: vs[:] = __apply_mat_to_all(loc_transform, vs) # glTF stores deltas in morph targets for vs in morph_locs: vs -= locs if export_settings[gltf2_blender_export_keys.YUP]: __zup2yup(locs) for vs in morph_locs: __zup2yup(vs) return locs, morph_locs def __get_normals(blender_mesh, key_blocks, armature, blender_object, export_settings): """Get normal for each loop.""" if key_blocks: normals = key_blocks[0].relative_key.normals_split_get() normals = np.array(normals, dtype=np.float32) else: normals = np.empty(len(blender_mesh.loops) * 3, dtype=np.float32) blender_mesh.calc_normals_split() blender_mesh.loops.foreach_get('normal', normals) normals = normals.reshape(len(blender_mesh.loops), 3) morph_normals = [] for key_block in key_blocks: ns = np.array(key_block.normals_split_get(), dtype=np.float32) ns = ns.reshape(len(blender_mesh.loops), 3) morph_normals.append(ns) # Transform for skinning if armature and blender_object: apply_matrix = (armature.matrix_world.inverted_safe() @ blender_object.matrix_world) apply_matrix = apply_matrix.to_3x3().inverted_safe().transposed() normal_transform = armature.matrix_world.to_3x3() @ apply_matrix normals[:] = __apply_mat_to_all(normal_transform, normals) __normalize_vecs(normals) for ns in morph_normals: ns[:] = __apply_mat_to_all(normal_transform, ns) __normalize_vecs(ns) for ns in [normals, *morph_normals]: # Replace zero normals with the unit UP vector. # Seems to happen sometimes with degenerate tris? is_zero = ~ns.any(axis=1) ns[is_zero, 2] = 1 # glTF stores deltas in morph targets for ns in morph_normals: ns -= normals if export_settings[gltf2_blender_export_keys.YUP]: __zup2yup(normals) for ns in morph_normals: __zup2yup(ns) return normals, morph_normals def __get_tangents(blender_mesh, armature, blender_object, export_settings): """Get an array of the tangent for each loop.""" tangents = np.empty(len(blender_mesh.loops) * 3, dtype=np.float32) blender_mesh.loops.foreach_get('tangent', tangents) tangents = tangents.reshape(len(blender_mesh.loops), 3) # Transform for skinning if armature and blender_object: apply_matrix = armature.matrix_world.inverted_safe() @ blender_object.matrix_world tangent_transform = apply_matrix.to_quaternion().to_matrix() tangents = __apply_mat_to_all(tangent_transform, tangents) __normalize_vecs(tangents) if export_settings[gltf2_blender_export_keys.YUP]: __zup2yup(tangents) return tangents def __get_bitangent_signs(blender_mesh, armature, blender_object, export_settings): signs = np.empty(len(blender_mesh.loops), dtype=np.float32) blender_mesh.loops.foreach_get('bitangent_sign', signs) # Transform for skinning if armature and blender_object: # Bitangent signs should flip when handedness changes # TODO: confirm apply_matrix = armature.matrix_world.inverted_safe() @ blender_object.matrix_world tangent_transform = apply_matrix.to_quaternion().to_matrix() flipped = tangent_transform.determinant() < 0 if flipped: signs *= -1 # No change for Zup -> Yup return signs def __calc_morph_tangents(normals, morph_normal_deltas, tangents): # TODO: check if this works morph_tangent_deltas = np.empty((len(normals), 3), dtype=np.float32) for i in range(len(normals)): n = Vector(normals[i]) morph_n = n + Vector(morph_normal_deltas[i]) # convert back to non-delta t = Vector(tangents[i, :3]) rotation = morph_n.rotation_difference(n) t_morph = Vector(t) t_morph.rotate(rotation) morph_tangent_deltas[i] = t_morph - t # back to delta return morph_tangent_deltas def __get_uvs(blender_mesh, uv_i): layer = blender_mesh.uv_layers[uv_i] uvs = np.empty(len(blender_mesh.loops) * 2, dtype=np.float32) layer.data.foreach_get('uv', uvs) uvs = uvs.reshape(len(blender_mesh.loops), 2) # Blender UV space -> glTF UV space # u,v -> u,1-v uvs[:, 1] *= -1 uvs[:, 1] += 1 return uvs def __get_colors(blender_mesh, color_i): layer = blender_mesh.vertex_colors[color_i] colors = np.empty(len(blender_mesh.loops) * 4, dtype=np.float32) layer.data.foreach_get('color', colors) colors = colors.reshape(len(blender_mesh.loops), 4) # sRGB -> Linear rgb = colors[:, :-1] not_small = rgb >= 0.04045 small_result = np.where(rgb < 0.0, 0.0, rgb * (1.0 / 12.92)) large_result = np.power((rgb + 0.055) * (1.0 / 1.055), 2.4, where=not_small) rgb[:] = np.where(not_small, large_result, small_result) return colors def __get_bone_data(blender_mesh, skin, blender_vertex_groups): joint_name_to_index = {joint.name: index for index, joint in enumerate(skin.joints)} group_to_joint = [joint_name_to_index.get(g.name) for g in blender_vertex_groups] # List of (joint, weight) pairs for each vert vert_bones = [] max_num_influences = 0 for vertex in blender_mesh.vertices: bones = [] if vertex.groups: for group_element in vertex.groups: weight = group_element.weight if weight <= 0.0: continue try: joint = group_to_joint[group_element.group] except Exception: continue if joint is None: continue bones.append((joint, weight)) bones.sort(key=lambda x: x[1], reverse=True) if not bones: bones = ((0, 1.0),) # HACK for verts with zero weight (#308) vert_bones.append(bones) if len(bones) > max_num_influences: max_num_influences = len(bones) # How many joint sets do we need? 1 set = 4 influences num_joint_sets = (max_num_influences + 3) // 4 return vert_bones, num_joint_sets def __zup2yup(array): # x,y,z -> x,z,-y array[:, [1,2]] = array[:, [2,1]] # x,z,y array[:, 2] *= -1 # x,z,-y def __apply_mat_to_all(matrix, vectors): """Given matrix m and vectors [v1,v2,...], computes [m@v1,m@v2,...]""" # Linear part m = matrix.to_3x3() if len(matrix) == 4 else matrix res = np.matmul(vectors, np.array(m.transposed())) # Translation part if len(matrix) == 4:
return res def __normalize_vecs(vectors): norms = np.linalg.norm(vectors, axis=1, keepdims=True) np.divide(vectors, norms, out=vectors, where=norms != 0)
res += np.array(matrix.translation)
models.py
from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. # from itsdangerous import Serializer from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData from mall import settings from utils.models import BaseModel class User(AbstractUser): mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号') email_active = models.BooleanField(default=False, verbose_name='邮箱验证状态') default_address = models.ForeignKey('Address', related_name='users', null=True, blank=True, on_delete=models.SET_NULL, verbose_name='默认地址') class Meta: db_table = 'tb_users' verbose_name = '用户' verbose_name_plural = verbose_name def generate_verify_email_url(self
erializer(settings.SECRET_KEY, 3600) # 加载用户信息 token = serializer.dumps({'user_id': self.id, 'email': self.email}) # 注意拼接的过程中对 token进行decode操作 verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token.decode() return verify_url @staticmethod def check_verify_email_token(token): serializer = Serializer(settings.SECRET_KEY, 3600) try: # 加载token result = serializer.loads(token) except BadData: return None else: user_id = result.get('user_id') email = result.get('email') try: user = User.objects.get(id=user_id, email=email) except User.DoesNotExist: user = None return user # @classmethod # def check_active_mail_token(cls, token): # # serializer = Serializer(settings.SECRET_KEY, 3600) # # try: # result = serializer.loads(token) # except BadData: # return None # else: # # id = result.get('id') # email = result.get('email') # try: # user = User.objects.get(id=id, email=email) # except User.DoesNotExist: # user = None # # return user class Address(BaseModel): """ 用户地址 """ user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='addresses', verbose_name='用户') title = models.CharField(max_length=20, verbose_name='地址名称') receiver = models.CharField(max_length=20, verbose_name='收货人') province = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='province_addresses', verbose_name='省') city = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='city_addresses', verbose_name='市') district = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='district_addresses', verbose_name='区') place = models.CharField(max_length=50, verbose_name='地址') mobile = models.CharField(max_length=11, verbose_name='手机') tel = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name='固定电话') email = models.CharField(max_length=30, null=True, blank=True, default='', verbose_name='电子邮箱') is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除') class Meta: db_table = 'tb_address' verbose_name = '用户地址' verbose_name_plural = verbose_name ordering = ['-update_time']
): serializer = S
doc.go
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by protoc-gen-go_gapic. DO NOT EDIT. // Package budgets is an auto-generated package for the // Cloud Billing Budget API. // // The Cloud Billing Budget API stores Cloud Billing budgets, which define a // budget plan and the rules to execute as spend is tracked against that // plan. // // NOTE: This package is in beta. It is not stable, and may be subject to changes. // // Example usage // // To get started with this package, create a client. // ctx := context.Background() // c, err := budgets.NewBudgetClient(ctx) // if err != nil { // // TODO: Handle error. // } // defer c.Close() // // The client will use your default application credentials. Clients should be reused instead of created as needed. // The methods of Client are safe for concurrent use by multiple goroutines. // The returned client must be Closed when it is done being used. // // Using the Client // // The following is an example of making an API call with the newly created client. // // ctx := context.Background() // c, err := budgets.NewBudgetClient(ctx) // if err != nil { // // TODO: Handle error. // } // defer c.Close() // // req := &budgetspb.CreateBudgetRequest{ // // TODO: Fill request struct fields. // // See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/billing/budgets/v1beta1#CreateBudgetRequest. // } // resp, err := c.CreateBudget(ctx, req) // if err != nil { // // TODO: Handle error. // } // // TODO: Use resp. // _ = resp // // Use of Context // // The ctx passed to NewClient is used for authentication requests and // for creating the underlying connection, but is not used for subsequent calls. // Individual methods on the client use the ctx given to them. // // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more // please visit https://pkg.go.dev/cloud.google.com/go. package budgets // import "cloud.google.com/go/billing/budgets/apiv1beta1" import ( "context" "os" "runtime" "strconv" "strings" "unicode" "google.golang.org/api/option" "google.golang.org/grpc/metadata" ) // For more information on implementing a client constructor hook, see // https://github.com/googleapis/google-cloud-go/wiki/Customizing-constructors. type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) const versionClient = "20211030" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) out = out.Copy() for _, md := range mds { for k, v := range md { out[k] = append(out[k], v...) } } return metadata.NewOutgoingContext(ctx, out) } func checkDisableDeadlines() (bool, error) { raw, ok := os.LookupEnv("GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE") if !ok { return false, nil } b, err := strconv.ParseBool(raw) return b, err } // DefaultAuthScopes reports the default set of authentication scopes to use with this package. func DefaultAuthScopes() []string { return []string{ "https://www.googleapis.com/auth/cloud-billing", "https://www.googleapis.com/auth/cloud-platform", } } // versionGo returns the Go runtime version. The returned string // has no whitespace, suitable for reporting in header. func versionGo() string { const develPrefix = "devel +" s := runtime.Version() if strings.HasPrefix(s, develPrefix) { s = s[len(develPrefix):] if p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 { s = s[:p] } return s } notSemverRune := func(r rune) bool { return !strings.ContainsRune("0123456789.", r) } if strings.HasPrefix(s, "go1") { s = s[2:] var prerelease string if p := strings.IndexFunc(s, notSemverRune); p >= 0 { s, prerelease = s[:p], s[p:] } if strings.HasSuffix(s, ".") { s += "0" } else if strings.Count(s, ".") < 2
if prerelease != "" { s += "-" + prerelease } return s } return "UNKNOWN" }
{ s += ".0" }
sqrt.go
// Package newmath is a trivial example package. package newmath // Sqrt returns an approximation to the square root of x. func Sqrt(x float64) float64
{ z := 1.0 for i := 0; i < 1000; i++ { z -= (z*z - x) / (2 * z) } return z }
a4.rs
#[doc = "Reader of register A4"] pub type R = crate::R<u32, super::A4>; #[doc = "Reader of field `A`"] pub type A_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:11 - A (slope definition) register"] #[inline(always)] pub fn
(&self) -> A_R { A_R::new((self.bits & 0x0fff) as u16) } }
a
render.go
package actions import ( "encoding/json" "html/template" "strings" "time" "github.com/gobuffalo/buffalo/render" "github.com/gobuffalo/packr/v2" "github.com/monarko/piia/helpers" "github.com/monarko/piia/models" ) var r *render.Engine var assetsBox = packr.New("../public", "../public") // var assetsBox = packr.NewBox("../public") func
() { r = render.New(render.Options{ // HTML layout to be used for all HTML requests: HTMLLayout: "application.html", // Box containing all of the templates: TemplatesBox: packr.New("../templates", "../templates"), AssetsBox: assetsBox, // Add template helpers here: Helpers: render.Helpers{ // uncomment for non-Bootstrap form helpers: // "form": plush.FormHelper, // "form_for": plush.FormForHelper, "csrf": func() template.HTML { return template.HTML("<input name=\"authenticity_token\" value=\"<%= authenticity_token %>\" type=\"hidden\">") }, "ageHelper": func(d time.Time) string { return helpers.Age(d) }, "genderHelper": func(s string) string { if s == "M" { return "Male" } else if s == "F" { return "Female" } else { return "Other" } }, "stringInSlice": func(s string, sa []string) bool { if i := helpers.IndexInSlice(sa, s); i >= 0 { return true } return false }, "lastElement": func(s string, sep string) string { ss := strings.Split(s, sep) last := ss[len(ss)-1] return last }, "currentDate": func(calendar string) string { return helpers.CurrentDateInFormat(calendar, "2006-01-02") }, "currentDateInFormat": func(calendar, format string) string { return helpers.CurrentDateInFormat(calendar, format) }, "languageDate": func(gregorianDate time.Time, format, calendar string) string { return helpers.LanguageDate(gregorianDate, format, calendar) }, "changeDate": func(givenDate time.Time, format, fromCalendar, toCalendar string) string { return helpers.ChangeDate(givenDate, format, fromCalendar, toCalendar) }, "arrayStringView": func(s string) string { if len(s) > 0 { return helpers.SliceStringToCommaSeparatedValue(s) } return "" }, "trimText": func(s string) string { return strings.TrimSpace(s) }, "appendIfNotFound": func(s, toAdd string) string { if strings.Contains(s, toAdd) { return s } return strings.Join([]string{s, toAdd}, " ") }, "getSite": func(participantID string) string { return participantID[1:2] }, "tolower": func(s string) string { return strings.ToLower(s) }, "matchTimes": func(a time.Time, b time.Time) bool { return helpers.MatchTimes(a, b) }, "getMatchingAudit": func(l models.SystemLog, as []models.Audit) string { for _, a := range as { rType := strings.ToLower(strings.Replace(l.ResourceType, "_", "", -1)) mType := strings.ToLower(strings.Replace(a.ModelType, "_", "", -1)) if helpers.MatchTimes(l.CreatedAt, a.CreatedAt) && (rType == mType) { jsonString, err := json.Marshal(a.Changes) if err == nil { return string(jsonString) } } } return "" }, }, }) }
init
a9_fizzbuzz.py
for num in range(1, 51): if num % 3 == 0 and num % 5 == 0: print("fizzbuzz") elif num % 3 == 0 and num % 5 != 0: print("fizz") elif num % 3 != 0 and num % 5 == 0: print("buzz") else: print(num)
AbilityManager.ts
import { Component, Logger } from "@oasis-engine/core"; import { Oasis } from "./Oasis"; import { Parser } from "./Parser"; import { pluginHook } from "./plugins/PluginManager"; import { scriptAbility } from "./resources"; import { ComponentConfig, Props } from "./types"; import { switchElementsIndex } from "./utils"; export class AbilityManager { private abilityMap: { [id: string]: Component } = {}; constructor(private oasis: Oasis) {} @pluginHook({ after: "abilityAdded", before: "beforeAbilityAdded" }) public add(abilityConfig: ComponentConfig) { const { type, node: nodeId, props, id, index } = abilityConfig; const node = this.oasis.nodeManager.get(nodeId); const AbilityConstructor = this.getCompConstructor(type); if (!AbilityConstructor) { Logger.error(`${type} abiltiy is not defined`); return; } const abilityProps = this.mixPropsToExplicitProps(props); const ability = node.addComponent(AbilityConstructor); const { enabled } = abilityProps; if (enabled !== undefined) { ability.enabled = enabled; } if (type === "Model" || type === "GLTFModel") { // TODO (ability as any).init(abilityProps); } else { for (let k in abilityProps) { if (abilityProps[k] !== null) { ability[k] = abilityProps[k]; } } }
const abilityArray = node._components; const currentIndex = abilityArray.length - 1; switchElementsIndex(abilityArray, currentIndex, index); (ability as any).id = id; this.abilityMap[id] = ability; return ability; } @pluginHook({ before: "beforeAbilityUpdated", after: "abilityUpdated" }) public update(id: string, key: string, value: any) { if (this.get(id).constructor.name === "Model") { // TODO if (value && this.checkIsAsset(value)) { (this.get(id) as any).setProp(key, this.oasis.resourceManager.get(value.id).resource); } else { (this.get(id) as any).setProp(key, value); } } else { if (value && this.checkIsAsset(value)) { this.get(id)[key] = this.oasis.resourceManager.get(value.id).resource; } else { this.get(id)[key] = value; } } return { id, key, value }; } public get(id: string): Component { return this.abilityMap[id]; } @pluginHook({ after: "abilityDeleted", before: "beforeAbilityDeleted" }) public delete(id: string) { const ability = this.abilityMap[id]; ability.destroy(); delete this.abilityMap[id]; return id; } private getCompConstructor(type: string) { const splits = type.split("."); // script if (splits[0] === "script") { return scriptAbility[splits[1]]; } const constructor = Parser._components["o3"][type]; if (!constructor) { throw new Error(`${type} is not defined`); } return constructor; } private mixPropsToExplicitProps(props: Props) { const explicitProps = { ...props }; for (let k in props) { const prop = props[k]; if (prop && this.checkIsAsset(prop)) { const res = this.oasis.resourceManager.get(prop.id); if (res) { explicitProps[k] = res.resource; } else { explicitProps[k] = null; Logger.warn(`AbilityManager: can't get asset "${k}", which id is ${prop.id}`); } } } return explicitProps; } private checkIsAsset(prop: any): boolean { return prop.type === "asset"; } }
//@ts-ignore
d11v2.rs
const MODIFIERS: [fn(usize) -> usize; 3] = [|x: usize| x.wrapping_sub(1), |x| x, |x| x + 1]; fn main()
{ let data = include_str!("day11.txt"); let mut octos: Vec<Vec<usize>> = data .lines() .map(|x| { x.chars() .map(|c| c.to_digit(10).unwrap() as usize) .collect() }) .collect(); let mut step = 0; loop { step += 1; let mut flashing = Vec::new(); octos.iter_mut().enumerate().for_each(|(i, row)| { row.iter_mut().enumerate().for_each(|(j, o)| { *o += 1; if *o % 10 == 0 { flashing.push((i, j)) } }) }); while let Some((i, j)) = flashing.pop() { for fx in MODIFIERS { for fy in MODIFIERS { let x = fx(i); let y = fy(j); if let Some(o) = octos.get_mut(x).and_then(|r| r.get_mut(y)) { if (*o % 10) != 0 { *o += 1; if *o % 10 == 0 { flashing.push((x, y)); } } } } } } if octos.iter().all(|r| r.iter().all(|&x| x % 10 == 0)) { println!("{}", step); break; } } }
map.go
package objects import ( "fmt" "strings" "github.com/d5/tengo/compiler/token" ) // Map represents a map of objects. type Map struct { Value map[string]Object } // TypeName returns the name of the type. func (o *Map) TypeName() string { return "map" } func (o *Map) String() string { var pairs []string for k, v := range o.Value { pairs = append(pairs, fmt.Sprintf("%s: %s", k, v.String())) } return fmt.Sprintf("{%s}", strings.Join(pairs, ", ")) } // BinaryOp returns another object that is the result of // a given binary operator and a right-hand side object. func (o *Map) BinaryOp(op token.Token, rhs Object) (Object, error) { return nil, ErrInvalidOperator } // Copy returns a copy of the type. func (o *Map) Copy() Object { c := make(map[string]Object) for k, v := range o.Value { c[k] = v.Copy() } return &Map{Value: c} } // IsFalsy returns true if the value of the type is falsy. func (o *Map) IsFalsy() bool { return len(o.Value) == 0 } // Get returns the value for the given key. func (o *Map) Get(key string) (Object, bool) { val, ok := o.Value[key] return val, ok } // Set sets the value for the given key. func (o *Map) Set(key string, value Object) { o.Value[key] = value } // Equals returns true if the value of the type // is equal to the value of another object. func (o *Map) Equals(x Object) bool { t, ok := x.(*Map) if !ok
if len(o.Value) != len(t.Value) { return false } for k, v := range o.Value { tv := t.Value[k] if !v.Equals(tv) { return false } } return true }
{ return false }
run_ai_api.py
from ai.api import main
if __name__ == "__main__": main()
error.rs
use std::fmt; use std::fmt::Display; use failure::{Backtrace, Context, Fail}; #[derive(Debug)] pub struct Error { inner: Context<ErrorKind>, } /// Contains all of the different varieties of errors. By using the ErrorKind pattern with the
#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail)] pub enum ErrorKind { #[fail(display = "Unable to create client builder")] WebsocketClientBuilderCreate, #[fail(display = "Received invalid message type over websockets")] InvalidWebsocketMessageType, #[fail(display = "Invalid JSON received on websockets")] ParseJsonFromWebsockets, #[fail(display = "No message type in JSON from websockets")] NoMessageTypeFromWebsockets, #[fail(display = "Failed to parse bytes as UTF8 string")] ParseBytesAsUtf8, #[fail(display = "Unable to bind to http port")] HttpBindToPort, #[fail(display = "Client has not linked to interpreter")] ClientNotLinkedToInterpreter, #[fail(display = "Missing websocket server argument. This is a bug, should be a default")] MissingWebsocketServerArgument, #[fail(display = "Missing bind address argument. This is a bug, should be a default")] MissingBindAddressArgument, #[fail(display = "Missing redis address argument. This is a bug, should be a default")] MissingRedisAddressArgument, #[fail(display = "Missing Lua script argument. This is a bug, should be a default")] MissingLuaScriptArgument, #[fail(display = "Failed to create Redis client")] RedisClientCreate, #[fail(display = "Failed to persist key/value to Redis")] RedisPersist, #[fail(display = "Failed to query key in Redis")] RedisQuery, #[fail(display = "Failed to find matching keys in Redis")] RedisKeys, #[fail(display = "Failed to increment key in Redis")] RedisIncr, #[fail(display = "Could not find Bus userdata in Lua globals")] MissingBusUserData, #[fail(display = "Could not find a file at the provided Lua script path")] LuaScriptNotFound, #[fail(display = "Could not read a Lua script at the provided file path")] ReadLuaScript, #[fail(display = "Could not evaluate Lua script")] EvaluateLuaScript, #[fail(display = "Event handler not found in Lua register")] MissingEventHandlerRegistryValue, #[fail(display = "Rebuild handler not found in Lua register")] MissingRebuildHandlerRegistryValue, #[fail(display = "Receipt handler not found in Lua register")] MissingReceiptHandlerRegistryValue, #[fail(display = "HTTP handler not found in Lua register")] MissingHttpHandlerRegistryValue, #[fail(display = "Failure when running rebuild handler")] FailedRebuildHandler, #[fail(display = "Failure when running event handler")] FailedEventHandler, #[fail(display = "Failure when running HTTP handler")] FailedHttpHandler, #[fail(display = "Invalid return type from HTTP handler")] HttpHandlerInvalidReturnType, #[fail(display = "Failure when parsing result from HTTP handler")] ParseHttpHandlerResult, #[fail(display = "Failure when parsing content from HTTP request")] ParseHttpContent, #[fail(display = "Failed to serialize value to json for sending")] SerializeJsonForSending, #[fail(display = "Failed to deserialize json for Lua conversion")] DeserializeJsonForLua, #[fail(display = "Failed to serialize json to Lua conversion")] SerializeJsonForLua, #[fail(display = "Failed to set temporary global variable for Lua to json conversion")] SetLuaToJsonTemporary, #[fail(display = "Failed to remove temporary global variable for Lua to json conversion")] RemoveLuaToJsonTemporary, #[fail(display = "Failed to evaLuate Lua for Lua to json conversion")] EvaluateLuaToJsonConversion, #[fail(display = "Failed to evaLuate Lua for json to Lua conversion")] EvaluateJsonToLuaConversion, #[fail(display = "Failed to convert nil value in Lua")] NilToLuaConversion, #[fail(display = "Failed to convert Lua string into Rust string")] LuaToStringStrConversion, #[fail(display = "Failed to serialize json into Lua for Lua to string conversion")] SerializeJsonForLuaToString, #[fail(display = "Unable to log Lua value of this type")] UnsupportedLoggingType, #[fail(display = "Invalid type passed as correlation id")] InvalidCorrelationIdType, #[fail(display = "Found implicit consistency in state. This is a bug and should not happen")] ImplicitConsistencyInMap, #[fail(display = "Failed to parse incoming event JSON")] ParseEventMessage, #[fail(display = "Failed to parse incoming receipt JSON")] ParseReceiptMessage, #[fail(display = "Failed to create regex set for router")] RouterCreateRegexSet, #[fail(display = "Failed converting pattern matches to Lua table")] MatchesToLua, #[fail(display = "Failed adding route to router")] AddRoute, #[fail(display = "No timestamp was provided")] NoTimestampProvided, } impl Error { #[allow(dead_code)] pub fn kind(&self) -> ErrorKind { *self.inner.get_context() } } impl Fail for Error { fn cause(&self) -> Option<&Fail> { self.inner.cause() } fn backtrace(&self) -> Option<&Backtrace> { self.inner.backtrace() } } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Display::fmt(&self.inner, f) } } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Self { Self { inner: Context::new(kind) } } } impl From<Context<ErrorKind>> for Error { fn from(inner: Context<ErrorKind>) -> Self { Self { inner: inner } } }
/// failure library, we are able to have a one-to-many mapping with the underlying error types and /// the kind of error. These variants should not carry data.
client_test.go
package tsdb // FIXME: this result in import cycle // //func TestTSDBClientInterface(t *testing.T) { // t.Parallel() // var _ TSDBClient = (*kairosdb.KairosDBHTTPClient)(nil) //}
lib.rs
use { anyhow::{Context as _, Error}, fidl_fuchsia_settings::{ConfigurationInterfaces, LightState, LightValue}, fuchsia_component::client::connect_to_service, structopt::StructOpt, }; pub mod accessibility; pub mod audio; pub mod device; pub mod display; pub mod do_not_disturb; pub mod input; pub mod intl; pub mod light; pub mod night_mode; pub mod privacy; pub mod setup; /// SettingClient exercises the functionality found in SetUI service. Currently, /// action parameters are specified at as individual arguments, but the goal is /// to eventually parse details from a JSON file input. #[derive(StructOpt, Debug)] #[structopt(name = "setui_client", about = "set setting values")] pub enum SettingClient { // Operations that use the new interfaces. #[structopt(name = "accessibility")] Accessibility(AccessibilityOptions), #[structopt(name = "audio")] Audio { #[structopt(flatten)] streams: AudioStreams, }, // Operations that use the Device interface. #[structopt(name = "device")] Device { build_tag: Option<String> }, #[structopt(name = "display")] Display { #[structopt(short = "b", long = "brightness")] brightness: Option<f32>, #[structopt(short = "a", long = "auto_brightness")] auto_brightness: Option<bool>, #[structopt(short = "l", long = "light_sensor")] light_sensor: bool, #[structopt( short = "m", long = "low_light_mode", parse(try_from_str = "str_to_low_light_mode") )] low_light_mode: Option<fidl_fuchsia_settings::LowLightMode>, }, #[structopt(name = "do_not_disturb")] DoNotDisturb { #[structopt(short = "u", long = "user_dnd")] user_dnd: Option<bool>, #[structopt(short = "n", long = "night_mode_dnd")] night_mode_dnd: Option<bool>, }, #[structopt(name = "input")] Input { #[structopt(short = "m", long = "mic_muted")] mic_muted: Option<bool>, }, #[structopt(name = "intl")] Intl { #[structopt(short = "z", long, parse(from_str = "str_to_time_zone"))] time_zone: Option<fidl_fuchsia_intl::TimeZoneId>, #[structopt(short = "u", long, parse(try_from_str = "str_to_temperature_unit"))] // Valid options are Celsius and Fahrenheit, or just "c" and "f". temperature_unit: Option<fidl_fuchsia_intl::TemperatureUnit>, #[structopt(short, long, parse(from_str = "str_to_locale"))] /// List of locales, separated by spaces. locales: Vec<fidl_fuchsia_intl::LocaleId>, #[structopt(short = "h", long, parse(try_from_str = "str_to_hour_cycle"))] hour_cycle: Option<fidl_fuchsia_settings::HourCycle>, #[structopt(long)] /// If set, this flag will set locales as an empty list. Overrides the locales arguments. clear_locales: bool, }, #[structopt(name = "light")] /// To get the value of all light types, omit all arguments. If setting the value for a light group, /// name is required, then only one type of value between simple, brightness, or rgb should be /// specified. Light { #[structopt(flatten)] light_group: LightGroup, }, #[structopt(name = "night_mode")] NightMode { #[structopt(short, long)] night_mode_enabled: Option<bool>, }, #[structopt(name = "privacy")] Privacy { #[structopt(short, long)] user_data_sharing_consent: Option<bool>, }, #[structopt(name = "setup")] Setup { #[structopt(short = "i", long = "interfaces", parse(from_str = "str_to_interfaces"))] configuration_interfaces: Option<ConfigurationInterfaces>, }, } #[derive(StructOpt, Debug, Clone, Copy, Default)] pub struct AccessibilityOptions { #[structopt(short = "a", long)] pub audio_description: Option<bool>, #[structopt(short = "s", long)] pub screen_reader: Option<bool>, #[structopt(short = "i", long)] pub color_inversion: Option<bool>, #[structopt(short = "m", long)] pub enable_magnification: Option<bool>, #[structopt(short = "c", long, parse(try_from_str = "str_to_color_blindness_type"))] pub color_correction: Option<fidl_fuchsia_settings::ColorBlindnessType>, #[structopt(subcommand)] pub caption_options: Option<CaptionCommands>, } #[derive(StructOpt, Debug, Clone, Copy)] pub enum CaptionCommands { #[structopt(name = "captions")] CaptionOptions(CaptionOptions), } #[derive(StructOpt, Debug, Clone, Copy)] pub struct CaptionOptions { #[structopt(short = "m", long)] /// Enable closed captions for media sources of audio. pub for_media: Option<bool>, #[structopt(short = "t", long)] /// Enable closed captions for Text-To-Speech sources of audio. pub for_tts: Option<bool>, #[structopt(short, long, parse(try_from_str = "str_to_color"))] /// Border color used around the closed captions window. Valid options are red, green, or blue, /// or just the first letter of each color (r, g, b). pub window_color: Option<fidl_fuchsia_ui_types::ColorRgba>, #[structopt(short, long, parse(try_from_str = "str_to_color"))] /// Border color used around the closed captions window. Valid options are red, green, or blue, /// or just the first letter of each color (r, g, b). pub background_color: Option<fidl_fuchsia_ui_types::ColorRgba>, #[structopt(flatten)] pub style: CaptionFontStyle, } #[derive(StructOpt, Debug, Clone, Copy)] pub struct CaptionFontStyle { #[structopt(short, long, parse(try_from_str = "str_to_font_family"))] /// Font family for captions, specified by 47 CFR §79.102(k). Valid options are unknown, /// monospaced_serif, proportional_serif, monospaced_sans_serif, proportional_sans_serif, /// casual, cursive, and small_capitals, pub font_family: Option<fidl_fuchsia_settings::CaptionFontFamily>, #[structopt(short = "c", long, parse(try_from_str = "str_to_color"))] /// Color of the closed cpation text. Valid options are red, green, or blue, or just the first /// letter of each color (r, g, b). pub font_color: Option<fidl_fuchsia_ui_types::ColorRgba>, #[structopt(short, long)] /// Size of closed captions text relative to the default captions size. A range of [0.5, 2] is /// guaranteed to be supported (as 47 CFR §79.103(c)(4) establishes). pub relative_size: Option<f32>, #[structopt(short = "e", long, parse(try_from_str = "str_to_edge_style"))] /// Edge style for fonts as specified in 47 CFR §79.103(c)(7), valid options are none, /// drop_shadow, raised, depressed, and outline. pub char_edge_style: Option<fidl_fuchsia_settings::EdgeStyle>, } #[derive(StructOpt, Debug)] pub struct AudioStreams { #[structopt(short = "t", long = "stream", parse(try_from_str = "str_to_audio_stream"))] stream: Option<fidl_fuchsia_media::AudioRenderUsage>, #[structopt(short = "s", long = "source", parse(try_from_str = "str_to_audio_source"))] source: Option<fidl_fuchsia_settings::AudioStreamSettingSource>, #[structopt(flatten)] user_volume: UserVolume, } #[derive(StructOpt, Debug)] struct UserVolume { #[structopt(short = "l", long = "level")] level: Option<f32>, #[structopt(short = "v", long = "volume_muted")] volume_muted: Option<bool>, } #[derive(StructOpt, Debug, Clone)] pub struct LightGroup { #[structopt(short, long)] /// Name of a light group to set values for. Required if setting the value of a light group. pub name: Option<String>, #[structopt(short, long)] /// Repeated parameter for a list of simple on/off values to set for a light group. pub simple: Vec<bool>, #[structopt(short, long)] /// Repeated parameter for a list of integer brightness values from 0-255 inclusive to set for a /// light group. pub brightness: Vec<u8>, #[structopt(short, long, parse(try_from_str = "str_to_rgb"))] /// Repeated parameter for a list of RGB values to set for a light group. Values should be in /// the range of 0-255 inclusive and should be specified as a comma-separated list of the red, /// green, and blue components. Ex. 100,20,23 pub rgb: Vec<fidl_fuchsia_ui_types::ColorRgb>, } impl Into<Vec<LightState>> for LightGroup { fn into(self) -> Vec<LightState> { if self.simple.len() > 0 { return self .simple .clone() .into_iter() .map(|val| LightState { value: Some(LightValue::On(val)) }) .collect::<Vec<_>>(); } if self.brightness.len() > 0 { return self .brightness .clone() .into_iter() .map(|val| LightState { value: Some(LightValue::Brightness(val)) }) .collect::<Vec<_>>(); } if self.rgb.len() > 0 { return self .rgb .clone() .into_iter() .map(|val| LightState { value: Some(LightValue::Color(val)) }) .collect::<Vec<_>>(); } return Vec::new(); } } pub async fn run_command(command: SettingClient) -> Result<(), Error> { match command { SettingClient::Device { build_tag } => { let _build_tag = build_tag.clone(); if let Some(_build_tag_val) = build_tag { panic!("Cannot set device settings"); } let device_service = connect_to_service::<fidl_fuchsia_settings::DeviceMarker>() .context("Failed to connect to device service")?; let output = device::command(device_service).await?; println!("Device: {}", output); } SettingClient::Display { brightness, auto_brightness, light_sensor, low_light_mode } => { let display_service = connect_to_service::<fidl_fuchsia_settings::DisplayMarker>() .context("Failed to connect to display service")?; let output = display::command( display_service, brightness, auto_brightness, light_sensor, low_light_mode, ) .await?; println!("Display: {}", output); } SettingClient::DoNotDisturb { user_dnd, night_mode_dnd } => { let dnd_service = connect_to_service::<fidl_fuchsia_settings::DoNotDisturbMarker>() .context("Failed to connect to do_not_disturb service")?; let output = do_not_disturb::command(dnd_service, user_dnd, night_mode_dnd).await?; println!("DoNotDisturb: {}", output); } SettingClient::Intl { time_zone, temperature_unit, locales, hour_cycle, clear_locales } => { let intl_service = connect_to_service::<fidl_fuchsia_settings::IntlMarker>() .context("Failed to connect to intl service")?; let output = intl::command( intl_service, time_zone, temperature_unit, locales, hour_cycle, clear_locales, ) .await?; println!("Intl: {}", output); } SettingClient::Light { light_group } => { let light_mode_service = connect_to_service::<fidl_fuchsia_settings::LightMarker>() .context("Failed to connect to light service")?; let output = light::command(light_mode_service, light_group).await?; println!("Light: {}", output); } SettingClient::NightMode { night_mode_enabled } => { let night_mode_service = connect_to_service::<fidl_fuchsia_settings::NightModeMarker>() .context("Failed to connect to night mode service")?; let output = night_mode::command(night_mode_service, night_mode_enabled).await?; println!("NightMode: {}", output); } SettingClient::Accessibility(accessibility_options) => { let accessibility_service = connect_to_service::<fidl_fuchsia_settings::AccessibilityMarker>() .context("Failed to connect to accessibility service")?; let output = accessibility::command(accessibility_service, accessibility_options).await?; println!("Accessibility: {}", output); } SettingClient::Privacy { user_data_sharing_consent } => { let privacy_service = connect_to_service::<fidl_fuchsia_settings::PrivacyMarker>() .context("Failed to connect to privacy service")?; let output = privacy::command(privacy_service, user_data_sharing_consent).await?; println!("Privacy: {}", output); } SettingClient::Audio { streams } => { let audio_service = connect_to_service::<fidl_fuchsia_settings::AudioMarker>() .context("Failed to connect to audio service")?; let stream = streams.stream; let source = streams.source; let level = streams.user_volume.level; let volume_muted = streams.user_volume.volume_muted; let output = audio::command(audio_service, stream, source, level, volume_muted).await?; println!("Audio: {}", output); } SettingClient::Input { mic_muted } => { let input_service = connect_to_service::<fidl_fuchsia_settings::InputMarker>() .context("Failed to connect to input service")?; let output = input::command(input_service, mic_muted).await?; println!("Input: {}", output); } SettingClient::Setup { configuration_interfaces } => { let setup_service = connect_to_service::<fidl_fuchsia_settings::SetupMarker>() .context("Failed to connect to setup service")?; let output = setup::command(setup_service, configuration_interfaces).await?; println!("Setup: {}", output); } } Ok(()) } fn str_to_time_zone(src: &&str) -> fidl_fuchsia_intl::TimeZoneId { fidl_fuchsia_intl::TimeZoneId { id: src.to_string() } } fn str_to_locale(src: &str) -> fidl_fuchsia_intl::LocaleId { fidl_fuchsia_intl::LocaleId { id: src.to_string() } } fn str_to_low_light_mode(src: &str) -> Result<fidl_fuchsia_settings::LowLightMode, &str> { if src.contains("enable") { Ok(fidl_fuchsia_settings::LowLightMode::Enable) } else if src.contains("disable") { Ok(fidl_fuchsia_settings::LowLightMode::Disable) } else if src.contains("disableimmediately") { Ok(fidl_fuchsia_settings::LowLightMode::DisableImmediately) } else { Err("Couldn't parse low light mode") } } fn str_to_interfaces(src: &&str) -> ConfigurationInterfaces { let mut interfaces = ConfigurationInterfaces::empty(); for interface in src.split(",") { match interface.to_lowercase().as_str() { "eth" | "ethernet" => { interfaces = interfaces | ConfigurationInterfaces::Ethernet; } "wireless" | "wifi" => { interfaces = interfaces | ConfigurationInterfaces::Wifi; } _ => {} } } return interfaces; } fn str_to_color(src: &str) -> Result<fidl_fuchsia_ui_types::ColorRgba, &str> { Ok(match src.to_lowercase().as_str() { "red" | "r" => { fidl_fuchsia_ui_types::ColorRgba { red: 255.0, green: 0.0, blue: 0.0, alpha: 255.0 } } "green" | "g" => { fidl_fuchsia_ui_types::ColorRgba { red: 0.0, green: 2.055, blue: 0.0, alpha: 255.0 } } "blue" | "b" => { fidl_fuchsia_ui_types::ColorRgba { red: 0.0, green: 0.0, blue: 255.0, alpha: 255.0 } } _ => return Err("Couldn't parse color"), }) } /// Converts a comma-separated string of RGB values into a fidl_fuchsia_ui_types::ColorRgb. fn str_to_rgb(src: &str) -> Result<fidl_fuchsia_ui_types::ColorRgb, &str> { let mut part_iter = src.split(',').map(|p| p.parse::<f32>().map_err(|_| "failed to parse color value")); const WRONG_COUNT: &str = "wrong number of values"; let color = fidl_fuchsia_ui_types::ColorRgb { red: part_iter.next().unwrap_or_else(|| Err(WRONG_COUNT))?, green: part_iter.next().unwrap_or_else(|| Err(WRONG_COUNT))?, blue: part_iter.next().unwrap_or_else(|| Err(WRONG_COUNT))?, }; part_iter.next().map(|_| Err(WRONG_COUNT)).unwrap_or(Ok(color)) } fn str_to_font_family(src: &str) -> Result<fidl_fuchsia_settings::CaptionFontFamily, &str> { Ok(match src.to_lowercase().as_str() { "unknown" => fidl_fuchsia_settings::CaptionFontFamily::Unknown, "monospaced_serif" => fidl_fuchsia_settings::CaptionFontFamily::MonospacedSerif, "proportional_serif" => fidl_fuchsia_settings::CaptionFontFamily::ProportionalSerif, "monospaced_sans_serif" => fidl_fuchsia_settings::CaptionFontFamily::MonospacedSansSerif, "proportional_sans_serif" => { fidl_fuchsia_settings::CaptionFontFamily::ProportionalSansSerif } "casual" => fidl_fuchsia_settings::CaptionFontFamily::Casual, "cursive" => fidl_fuchsia_settings::CaptionFontFamily::Cursive, "small_capitals" => fidl_fuchsia_settings::CaptionFontFamily::SmallCapitals, _ => return Err("Couldn't parse font family"), }) } fn str_to_edge_style(src: &str) -> Result<fidl_fuchsia_settings::EdgeStyle, &str> { Ok(match src.to_lowercase().as_str() { "none" => fidl_fuchsia_settings::EdgeStyle::None, "drop_shadow" => fidl_fuchsia_settings::EdgeStyle::DropShadow, "raised" => fidl_fuchsia_settings::EdgeStyle::Raised, "depressed" => fidl_fuchsia_settings::EdgeStyle::Depressed, "outline" => fidl_fuchsia_settings::EdgeStyle::Outline, _ => return Err("Couldn't parse edge style"), }) } fn str_to_temperature_unit(src: &str) -> Result<fidl_fuchsia_intl::TemperatureUnit, &str> { match src.to_lowercase().as_str() { "c" | "celsius" => Ok(fidl_fuchsia_intl::TemperatureUnit::Celsius), "f" | "fahrenheit" => Ok(fidl_fuchsia_intl::TemperatureUnit::Fahrenheit), _ => Err("Couldn't parse temperature"), } } fn str
c: &str) -> Result<fidl_fuchsia_settings::HourCycle, &str> { match src.to_lowercase().as_str() { "unknown" => Ok(fidl_fuchsia_settings::HourCycle::Unknown), "h11" => Ok(fidl_fuchsia_settings::HourCycle::H11), "h12" => Ok(fidl_fuchsia_settings::HourCycle::H12), "h23" => Ok(fidl_fuchsia_settings::HourCycle::H23), "h24" => Ok(fidl_fuchsia_settings::HourCycle::H24), _ => Err("Couldn't parse hour cycle"), } } fn str_to_color_blindness_type( src: &str, ) -> Result<fidl_fuchsia_settings::ColorBlindnessType, &str> { match src.to_lowercase().as_str() { "none" | "n" => Ok(fidl_fuchsia_settings::ColorBlindnessType::None), "protanomaly" | "p" => Ok(fidl_fuchsia_settings::ColorBlindnessType::Protanomaly), "deuteranomaly" | "d" => Ok(fidl_fuchsia_settings::ColorBlindnessType::Deuteranomaly), "tritanomaly" | "t" => Ok(fidl_fuchsia_settings::ColorBlindnessType::Tritanomaly), _ => Err("Couldn't parse color blindness type"), } } fn str_to_audio_stream(src: &str) -> Result<fidl_fuchsia_media::AudioRenderUsage, &str> { match src.to_lowercase().as_str() { "background" | "b" => Ok(fidl_fuchsia_media::AudioRenderUsage::Background), "media" | "m" => Ok(fidl_fuchsia_media::AudioRenderUsage::Media), "interruption" | "i" => Ok(fidl_fuchsia_media::AudioRenderUsage::Interruption), "system_agent" | "systemagent" | "system agent" | "s" => { Ok(fidl_fuchsia_media::AudioRenderUsage::SystemAgent) } "communication" | "c" => Ok(fidl_fuchsia_media::AudioRenderUsage::Communication), _ => Err("Couldn't parse audio stream type"), } } fn str_to_audio_source(src: &str) -> Result<fidl_fuchsia_settings::AudioStreamSettingSource, &str> { match src.to_lowercase().as_str() { "user" | "u" => Ok(fidl_fuchsia_settings::AudioStreamSettingSource::User), "system" | "s" => Ok(fidl_fuchsia_settings::AudioStreamSettingSource::System), _ => Err("Couldn't parse audio source type"), } } #[cfg(test)] mod tests { use super::*; /// Unit test for str_to_audio_stream. #[test] fn test_str_to_audio_stream() { println!("Running test_str_to_audio_stream"); let test_cases = vec![ "Background", "MEDIA", "interruption", "SYSTEM_AGENT", "SystemAgent", "system agent", "Communication", "unexpected_stream_type", ]; let expected = vec![ Ok(fidl_fuchsia_media::AudioRenderUsage::Background), Ok(fidl_fuchsia_media::AudioRenderUsage::Media), Ok(fidl_fuchsia_media::AudioRenderUsage::Interruption), Ok(fidl_fuchsia_media::AudioRenderUsage::SystemAgent), Ok(fidl_fuchsia_media::AudioRenderUsage::SystemAgent), Ok(fidl_fuchsia_media::AudioRenderUsage::SystemAgent), Ok(fidl_fuchsia_media::AudioRenderUsage::Communication), Err("Couldn't parse audio stream type"), ]; let mut results = vec![]; for test_case in test_cases { results.push(str_to_audio_stream(test_case)); } for (expected, result) in expected.iter().zip(results.iter()) { assert_eq!(expected, result); } } /// Unit test for str_to_audio_source. #[test] fn test_str_to_audio_source() { println!("Running test_str_to_audio_source"); let test_cases = vec!["USER", "system", "unexpected_source_type"]; let expected = vec![ Ok(fidl_fuchsia_settings::AudioStreamSettingSource::User), Ok(fidl_fuchsia_settings::AudioStreamSettingSource::System), Err("Couldn't parse audio source type"), ]; let mut results = vec![]; for test_case in test_cases { results.push(str_to_audio_source(test_case)); } for (expected, result) in expected.iter().zip(results.iter()) { assert_eq!(expected, result); } } }
_to_hour_cycle(sr
plugin.go
package plugin import ( "reflect" "turboengine/core/api" ) var plugins = make(map[string]reflect.Type) func Register(name string, p api.Plugin) { if _, dup := plugins[name]; dup { panic("plugin register twice " + name) } plugins[name] = reflect.TypeOf(p).Elem() } func
(name string) api.Plugin { if p, ok := plugins[name]; ok { inst := reflect.New(p) p := inst.Interface().(api.Plugin) return p } return nil }
NewPlugin
registration.go
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package v20160101 import ( "context" "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Registration information. type Registration struct { pulumi.CustomResourceState // Specifies the billing mode for the Azure Stack registration. BillingModel pulumi.StringPtrOutput `pulumi:"billingModel"` // The identifier of the registered Azure Stack. CloudId pulumi.StringPtrOutput `pulumi:"cloudId"` // The entity tag used for optimistic concurrency when modifying the resource. Etag pulumi.StringPtrOutput `pulumi:"etag"` // The geo-location where the resource lives Location pulumi.StringOutput `pulumi:"location"` // The name of the resource Name pulumi.StringOutput `pulumi:"name"` // The object identifier associated with the Azure Stack connecting to Azure. ObjectId pulumi.StringPtrOutput `pulumi:"objectId"` // Resource tags. Tags pulumi.StringMapOutput `pulumi:"tags"` // The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" Type pulumi.StringOutput `pulumi:"type"` } // NewRegistration registers a new resource with the given unique name, arguments, and options. func NewRegistration(ctx *pulumi.Context, name string, args *RegistrationArgs, opts ...pulumi.ResourceOption) (*Registration, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.RegistrationToken == nil { return nil, errors.New("invalid value for required argument 'RegistrationToken'") } if args.ResourceGroup == nil { return nil, errors.New("invalid value for required argument 'ResourceGroup'") } aliases := pulumi.Aliases([]pulumi.Alias{ { Type: pulumi.String("azure-nextgen:azurestack/v20160101:Registration"), }, { Type: pulumi.String("azure-native:azurestack:Registration"), }, { Type: pulumi.String("azure-nextgen:azurestack:Registration"), }, { Type: pulumi.String("azure-native:azurestack/v20170601:Registration"), }, { Type: pulumi.String("azure-nextgen:azurestack/v20170601:Registration"), }, { Type: pulumi.String("azure-native:azurestack/v20200601preview:Registration"), }, { Type: pulumi.String("azure-nextgen:azurestack/v20200601preview:Registration"), }, }) opts = append(opts, aliases) var resource Registration err := ctx.RegisterResource("azure-native:azurestack/v20160101:Registration", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetRegistration gets an existing Registration resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetRegistration(ctx *pulumi.Context, name string, id pulumi.IDInput, state *RegistrationState, opts ...pulumi.ResourceOption) (*Registration, error) { var resource Registration err := ctx.ReadResource("azure-native:azurestack/v20160101:Registration", name, id, state, &resource, opts...) if err != nil
return &resource, nil } // Input properties used for looking up and filtering Registration resources. type registrationState struct { // Specifies the billing mode for the Azure Stack registration. BillingModel *string `pulumi:"billingModel"` // The identifier of the registered Azure Stack. CloudId *string `pulumi:"cloudId"` // The entity tag used for optimistic concurrency when modifying the resource. Etag *string `pulumi:"etag"` // The geo-location where the resource lives Location *string `pulumi:"location"` // The name of the resource Name *string `pulumi:"name"` // The object identifier associated with the Azure Stack connecting to Azure. ObjectId *string `pulumi:"objectId"` // Resource tags. Tags map[string]string `pulumi:"tags"` // The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" Type *string `pulumi:"type"` } type RegistrationState struct { // Specifies the billing mode for the Azure Stack registration. BillingModel pulumi.StringPtrInput // The identifier of the registered Azure Stack. CloudId pulumi.StringPtrInput // The entity tag used for optimistic concurrency when modifying the resource. Etag pulumi.StringPtrInput // The geo-location where the resource lives Location pulumi.StringPtrInput // The name of the resource Name pulumi.StringPtrInput // The object identifier associated with the Azure Stack connecting to Azure. ObjectId pulumi.StringPtrInput // Resource tags. Tags pulumi.StringMapInput // The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" Type pulumi.StringPtrInput } func (RegistrationState) ElementType() reflect.Type { return reflect.TypeOf((*registrationState)(nil)).Elem() } type registrationArgs struct { // Location of the resource. Location *string `pulumi:"location"` // Name of the Azure Stack registration. RegistrationName *string `pulumi:"registrationName"` // The token identifying registered Azure Stack RegistrationToken string `pulumi:"registrationToken"` // Name of the resource group. ResourceGroup string `pulumi:"resourceGroup"` } // The set of arguments for constructing a Registration resource. type RegistrationArgs struct { // Location of the resource. Location pulumi.StringPtrInput // Name of the Azure Stack registration. RegistrationName pulumi.StringPtrInput // The token identifying registered Azure Stack RegistrationToken pulumi.StringInput // Name of the resource group. ResourceGroup pulumi.StringInput } func (RegistrationArgs) ElementType() reflect.Type { return reflect.TypeOf((*registrationArgs)(nil)).Elem() } type RegistrationInput interface { pulumi.Input ToRegistrationOutput() RegistrationOutput ToRegistrationOutputWithContext(ctx context.Context) RegistrationOutput } func (*Registration) ElementType() reflect.Type { return reflect.TypeOf((*Registration)(nil)) } func (i *Registration) ToRegistrationOutput() RegistrationOutput { return i.ToRegistrationOutputWithContext(context.Background()) } func (i *Registration) ToRegistrationOutputWithContext(ctx context.Context) RegistrationOutput { return pulumi.ToOutputWithContext(ctx, i).(RegistrationOutput) } type RegistrationOutput struct { *pulumi.OutputState } func (RegistrationOutput) ElementType() reflect.Type { return reflect.TypeOf((*Registration)(nil)) } func (o RegistrationOutput) ToRegistrationOutput() RegistrationOutput { return o } func (o RegistrationOutput) ToRegistrationOutputWithContext(ctx context.Context) RegistrationOutput { return o } func init() { pulumi.RegisterOutputType(RegistrationOutput{}) }
{ return nil, err }
bundle.js
!function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={exports:{},id:o,loaded:!1};return e[o].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){e.exports=n(113)},function(e,t){function n(){c=!1,a.length?s=a.concat(s):u=-1,s.length&&o()}function o(){if(!c){var e=setTimeout(n);c=!0;for(var t=s.length;t;){for(a=s,s=[];++u<t;)a&&a[u].run();u=-1,t=s.length}a=null,c=!1,clearTimeout(e)}}function r(e,t){this.fun=e,this.array=t}function i(){}var a,l=e.exports={},s=[],c=!1,u=-1;l.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];s.push(new r(e,t)),1!==s.length||c||setTimeout(o,0)},r.prototype.run=function(){this.fun.apply(null,this.array)},l.title="browser",l.browser=!0,l.env={},l.argv=[],l.version="",l.versions={},l.on=i,l.addListener=i,l.once=i,l.off=i,l.removeListener=i,l.removeAllListeners=i,l.emit=i,l.binding=function(e){throw new Error("process.binding is not supported")},l.cwd=function(){return"/"},l.chdir=function(e){throw new Error("process.chdir is not supported")},l.umask=function(){return 0}},function(e,t,n){(function(t){"use strict";var n=function(e,n,o,r,i,a,l,s){if("production"!==t.env.NODE_ENV&&void 0===n)throw new Error("invariant requires an error message argument");if(!e){var c;if(void 0===n)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[o,r,i,a,l,s],p=0;c=new Error("Invariant Violation: "+n.replace(/%s/g,function(){return u[p++]}))}throw c.framesToPop=1,c}};e.exports=n}).call(t,n(1))},function(e,t){"use strict";function n(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var n=Object(e),o=Object.prototype.hasOwnProperty,r=1;r<arguments.length;r++){var i=arguments[r];if(null!=i){var a=Object(i);for(var l in a)o.call(a,l)&&(n[l]=a[l])}}return n}e.exports=n},function(e,t,n){(function(t){"use strict";var o=n(17),r=o;"production"!==t.env.NODE_ENV&&(r=function(e,t){for(var n=[],o=2,r=arguments.length;r>o;o++)n.push(arguments[o]);if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(t.length<10||/^[s\W]*$/.test(t))throw new Error("The warning format should be able to uniquely identify this warning. Please, use a more descriptive format than: "+t);if(0!==t.indexOf("Failed Composite propType: ")&&!e){var i=0,a="Warning: "+t.replace(/%s/g,function(){return n[i++]});console.warn(a);try{throw new Error(a)}catch(l){}}}),e.exports=r}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e,n){Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:function(){return this._store?this._store[n]:null},set:function(e){"production"!==t.env.NODE_ENV?s(!1,"Don't set the %s property of the React element. Instead, specify the correct value when initially creating the element.",n):null,this._store[n]=e}})}function r(e){try{var t={props:!0};for(var n in t)o(e,n);u=!0}catch(r){}}var i=n(54),a=n(15),l=n(3),s=n(4),c={key:!0,ref:!0},u=!1,p=function(e,n,o,r,i,a){if(this.type=e,this.key=n,this.ref=o,this._owner=r,this._context=i,"production"!==t.env.NODE_ENV){this._store={props:a,originalProps:l({},a)};try{Object.defineProperty(this._store,"validated",{configurable:!1,enumerable:!1,writable:!0})}catch(s){}if(this._store.validated=!1,u)return void Object.freeze(this)}this.props=a};p.prototype={_isReactElement:!0},"production"!==t.env.NODE_ENV&&r(p.prototype),p.createElement=function(e,t,n){var o,r={},l=null,s=null;if(null!=t){s=void 0===t.ref?null:t.ref,l=void 0===t.key?null:""+t.key;for(o in t)t.hasOwnProperty(o)&&!c.hasOwnProperty(o)&&(r[o]=t[o])}var u=arguments.length-2;if(1===u)r.children=n;else if(u>1){for(var d=Array(u),f=0;u>f;f++)d[f]=arguments[f+2];r.children=d}if(e&&e.defaultProps){var h=e.defaultProps;for(o in h)"undefined"==typeof r[o]&&(r[o]=h[o])}return new p(e,l,s,a.current,i.current,r)},p.createFactory=function(e){var t=p.createElement.bind(null,e);return t.type=e,t},p.cloneAndReplaceProps=function(e,n){var o=new p(e.type,e.key,e.ref,e._owner,e._context,n);return"production"!==t.env.NODE_ENV&&(o._store.validated=e._store.validated),o},p.cloneElement=function(e,t,n){var o,r=l({},e.props),i=e.key,s=e.ref,u=e._owner;if(null!=t){void 0!==t.ref&&(s=t.ref,u=a.current),void 0!==t.key&&(i=""+t.key);for(o in t)t.hasOwnProperty(o)&&!c.hasOwnProperty(o)&&(r[o]=t[o])}var d=arguments.length-2;if(1===d)r.children=n;else if(d>1){for(var f=Array(d),h=0;d>h;h++)f[h]=arguments[h+2];r.children=f}return new p(e.type,i,s,u,e._context,r)},p.isValidElement=function(e){var t=!(!e||!e._isReactElement);return t},e.exports=p}).call(t,n(1))},function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),o={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};e.exports=o},function(e,t,n){e.exports=n(146)},function(e,t,n){"use strict";var o=n(33),r=o({bubbled:null,captured:null}),i=o({topBlur:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topReset:null,topScroll:null,topSelectionChange:null,topSubmit:null,topTextInput:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),a={topLevelTypes:i,PropagationPhases:r};e.exports=a},function(e,t,n){(function(t){"use strict";function o(e,n,o){for(var r in n)n.hasOwnProperty(r)&&("production"!==t.env.NODE_ENV?C("function"==typeof n[r],"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",e.displayName||"ReactClass",y[o],r):null)}function r(e,n){var o=T.hasOwnProperty(n)?T[n]:null;P.hasOwnProperty(n)&&("production"!==t.env.NODE_ENV?w(o===D.OVERRIDE_BASE,"ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.",n):w(o===D.OVERRIDE_BASE)),e.hasOwnProperty(n)&&("production"!==t.env.NODE_ENV?w(o===D.DEFINE_MANY||o===D.DEFINE_MANY_MERGED,"ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",n):w(o===D.DEFINE_MANY||o===D.DEFINE_MANY_MERGED))}function i(e,n){if(n){"production"!==t.env.NODE_ENV?w("function"!=typeof n,"ReactClass: You're attempting to use a component class as a mixin. Instead, just use a regular object."):w("function"!=typeof n),"production"!==t.env.NODE_ENV?w(!h.isValidElement(n),"ReactClass: You're attempting to use a component as a mixin. Instead, just use a regular object."):w(!h.isValidElement(n));var o=e.prototype;n.hasOwnProperty(_)&&R.mixins(e,n.mixins);for(var i in n)if(n.hasOwnProperty(i)&&i!==_){var a=n[i];if(r(o,i),R.hasOwnProperty(i))R[i](e,a);else{var l=T.hasOwnProperty(i),u=o.hasOwnProperty(i),p=a&&a.__reactDontBind,d="function"==typeof a,f=d&&!l&&!u&&!p;if(f)o.__reactAutoBindMap||(o.__reactAutoBindMap={}),o.__reactAutoBindMap[i]=a,o[i]=a;else if(u){var g=T[i];"production"!==t.env.NODE_ENV?w(l&&(g===D.DEFINE_MANY_MERGED||g===D.DEFINE_MANY),"ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.",g,i):w(l&&(g===D.DEFINE_MANY_MERGED||g===D.DEFINE_MANY)),g===D.DEFINE_MANY_MERGED?o[i]=s(o[i],a):g===D.DEFINE_MANY&&(o[i]=c(o[i],a))}else o[i]=a,"production"!==t.env.NODE_ENV&&"function"==typeof a&&n.displayName&&(o[i].displayName=n.displayName+"_"+i)}}}}function a(e,n){if(n)for(var o in n){var r=n[o];if(n.hasOwnProperty(o)){var i=o in R;"production"!==t.env.NODE_ENV?w(!i,'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.',o):w(!i);var a=o in e;"production"!==t.env.NODE_ENV?w(!a,"ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",o):w(!a),e[o]=r}}}function l(e,n){"production"!==t.env.NODE_ENV?w(e&&n&&"object"==typeof e&&"object"==typeof n,"mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects."):w(e&&n&&"object"==typeof e&&"object"==typeof n);for(var o in n)n.hasOwnProperty(o)&&("production"!==t.env.NODE_ENV?w(void 0===e[o],"mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.",o):w(void 0===e[o]),e[o]=n[o]);return e}function s(e,t){return function(){var n=e.apply(this,arguments),o=t.apply(this,arguments);if(null==n)return o;if(null==o)return n;var r={};return l(r,n),l(r,o),r}}function c(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function u(e,n){var o=n.bind(e);if("production"!==t.env.NODE_ENV){o.__reactBoundContext=e,o.__reactBoundMethod=n,o.__reactBoundArguments=null;var r=e.constructor.displayName,i=o.bind;o.bind=function(a){for(var l=[],s=1,c=arguments.length;c>s;s++)l.push(arguments[s]);if(a!==e&&null!==a)"production"!==t.env.NODE_ENV?C(!1,"bind(): React component methods may only be bound to the component instance. See %s",r):null;else if(!l.length)return"production"!==t.env.NODE_ENV?C(!1,"bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call. See %s",r):null,o;var u=i.apply(o,arguments);return u.__reactBoundContext=e,u.__reactBoundMethod=n,u.__reactBoundArguments=l,u}}return o}function p(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var n=e.__reactAutoBindMap[t];e[t]=u(e,g.guard(n,e.constructor.displayName+"."+t))}}var d=n(86),f=n(15),h=n(5),g=n(164),b=n(25),m=n(57),v=n(58),y=n(40),x=n(59),E=n(3),w=n(2),N=n(33),k=n(18),C=n(4),_=k({mixins:null}),D=N({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),O=[],T={mixins:D.DEFINE_MANY,statics:D.DEFINE_MANY,propTypes:D.DEFINE_MANY,contextTypes:D.DEFINE_MANY,childContextTypes:D.DEFINE_MANY,getDefaultProps:D.DEFINE_MANY_MERGED,getInitialState:D.DEFINE_MANY_MERGED,getChildContext:D.DEFINE_MANY_MERGED,render:D.DEFINE_ONCE,componentWillMount:D.DEFINE_MANY,componentDidMount:D.DEFINE_MANY,componentWillReceiveProps:D.DEFINE_MANY,shouldComponentUpdate:D.DEFINE_ONCE,componentWillUpdate:D.DEFINE_MANY,componentDidUpdate:D.DEFINE_MANY,componentWillUnmount:D.DEFINE_MANY,updateComponent:D.OVERRIDE_BASE},R={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)i(e,t[n])},childContextTypes:function(e,n){"production"!==t.env.NODE_ENV&&o(e,n,v.childContext),e.childContextTypes=E({},e.childContextTypes,n)},contextTypes:function(e,n){"production"!==t.env.NODE_ENV&&o(e,n,v.context),e.contextTypes=E({},e.contextTypes,n)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=s(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,n){"production"!==t.env.NODE_ENV&&o(e,n,v.prop),e.propTypes=E({},e.propTypes,n)},statics:function(e,t){a(e,t)}},M={enumerable:!1,get:function(){var e=this.displayName||this.name||"Component";return"production"!==t.env.NODE_ENV?C(!1,"%s.type is deprecated. Use %s directly to access the class.",e,e):null,Object.defineProperty(this,"type",{value:this}),this}},P={replaceState:function(e,t){x.enqueueReplaceState(this,e),t&&x.enqueueCallback(this,t)},isMounted:function(){if("production"!==t.env.NODE_ENV){var e=f.current;null!==e&&("production"!==t.env.NODE_ENV?C(e._warnedAboutRefsInRender,"%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.",e.getName()||"A component"):null,e._warnedAboutRefsInRender=!0)}var n=b.get(this);return n&&n!==m.currentlyMountingInstance},setProps:function(e,t){x.enqueueSetProps(this,e),t&&x.enqueueCallback(this,t)},replaceProps:function(e,t){x.enqueueReplaceProps(this,e),t&&x.enqueueCallback(this,t)}},S=function(){};E(S.prototype,d.prototype,P);var I={createClass:function(e){var n=function(e,o){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?C(this instanceof n,"Something is calling a React component directly. Use a factory or JSX instead. See: https://fb.me/react-legacyfactory"):null),this.__reactAutoBindMap&&p(this),this.props=e,this.context=o,this.state=null;var r=this.getInitialState?this.getInitialState():null;"production"!==t.env.NODE_ENV&&"undefined"==typeof r&&this.getInitialState._isMockFunction&&(r=null),"production"!==t.env.NODE_ENV?w("object"==typeof r&&!Array.isArray(r),"%s.getInitialState(): must return an object or null",n.displayName||"ReactCompositeComponent"):w("object"==typeof r&&!Array.isArray(r)),this.state=r};n.prototype=new S,n.prototype.constructor=n,O.forEach(i.bind(null,n)),i(n,e),n.getDefaultProps&&(n.defaultProps=n.getDefaultProps()),"production"!==t.env.NODE_ENV&&(n.getDefaultProps&&(n.getDefaultProps.isReactClassApproved={}),n.prototype.getInitialState&&(n.prototype.getInitialState.isReactClassApproved={})),"production"!==t.env.NODE_ENV?w(n.prototype.render,"createClass(...): Class specification must implement a `render` method."):w(n.prototype.render),"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?C(!n.prototype.componentShouldUpdate,"%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",e.displayName||"A component"):null);for(var o in T)n.prototype[o]||(n.prototype[o]=null);if(n.type=n,"production"!==t.env.NODE_ENV)try{Object.defineProperty(n,"type",M)}catch(r){}return n},injection:{injectMixin:function(e){O.push(e)}}};e.exports=I}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e,t){for(var n=Math.min(e.length,t.length),o=0;n>o;o++)if(e.charAt(o)!==t.charAt(o))return o;return e.length===t.length?-1:n}function r(e){var t=M(e);return t&&K.getID(t)}function i(e){var n=a(e);if(n)if(U.hasOwnProperty(n)){var o=U[n];o!==e&&("production"!==t.env.NODE_ENV?S(!u(o,n),"ReactMount: Two valid but unequal nodes with the same `%s`: %s",V,n):S(!u(o,n)),U[n]=e)}else U[n]=e;return n}function a(e){return e&&e.getAttribute&&e.getAttribute(V)||""}function l(e,t){var n=a(e);n!==t&&delete U[n],e.setAttribute(V,t),U[t]=e}function s(e){return U.hasOwnProperty(e)&&u(U[e],e)||(U[e]=K.findReactNodeByID(e)),U[e]}function c(e){var t=N.get(e)._rootNodeID;return E.isNullComponentID(t)?null:(U.hasOwnProperty(t)&&u(U[t],t)||(U[t]=K.findReactNodeByID(t)),U[t])}function u(e,n){if(e){"production"!==t.env.NODE_ENV?S(a(e)===n,"ReactMount: Unexpected modification of `%s`",V):S(a(e)===n);var o=K.findReactContainerForID(n);if(o&&R(o,e))return!0}return!1}function p(e){delete U[e]}function d(e){var t=U[e];return t&&u(t,e)?void(Y=t):!1}function f(e){Y=null,w.traverseAncestors(e,d);var t=Y;return Y=null,t}function h(e,t,n,o,r){var i=_.mountComponent(e,t,o,T);e._isTopLevel=!0,K._mountImageIntoNode(i,n,r)}function g(e,t,n,o){var r=O.ReactReconcileTransaction.getPooled();r.perform(h,null,e,t,n,r,o),O.ReactReconcileTransaction.release(r)}var b=n(20),m=n(23),v=n(15),y=n(5),x=n(31),E=n(56),w=n(24),N=n(25),k=n(90),C=n(16),_=n(26),D=n(59),O=n(11),T=n(43),R=n(96),M=n(196),P=n(65),S=n(2),I=n(67),A=n(68),j=n(4),L=w.SEPARATOR,V=b.ID_ATTRIBUTE_NAME,U={},F=1,B=9,q={},H={};if("production"!==t.env.NODE_ENV)var z={};var W=[],Y=null,K={_instancesByReactRootID:q,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,n,o,i){return"production"!==t.env.NODE_ENV&&x.checkAndWarnForMutatedProps(n),K.scrollMonitor(o,function(){D.enqueueElementInternal(e,n),i&&D.enqueueCallbackInternal(e,i)}),"production"!==t.env.NODE_ENV&&(z[r(o)]=M(o)),e},_registerComponent:function(e,n){"production"!==t.env.NODE_ENV?S(n&&(n.nodeType===F||n.nodeType===B),"_registerComponent(...): Target container is not a DOM element."):S(n&&(n.nodeType===F||n.nodeType===B)),m.ensureScrollValueMonitoring();var o=K.registerContainer(n);return q[o]=e,o},_renderNewRootComponent:function(e,n,o){"production"!==t.env.NODE_ENV?j(null==v.current,"_renderNewRootComponent(): Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate."):null;var r=P(e,null),i=K._registerComponent(r,n);return O.batchedUpdates(g,r,i,n,o),"production"!==t.env.NODE_ENV&&(z[i]=M(n)),r},render:function(e,n,o){"production"!==t.env.NODE_ENV?S(y.isValidElement(e),"React.render(): Invalid component element.%s","string"==typeof e?" Instead of passing an element string, make sure to instantiate it by passing it to React.createElement.":"function"==typeof e?" Instead of passing a component class, make sure to instantiate it by passing it to React.createElement.":null!=e&&void 0!==e.props?" This may be caused by unintentionally loading two independent copies of React.":""):S(y.isValidElement(e));var i=q[r(n)];if(i){var a=i._currentElement;if(A(a,e))return K._updateRootComponent(i,e,n,o).getPublicInstance();K.unmountComponentAtNode(n)}var l=M(n),s=l&&K.isRenderedByReact(l);if("production"!==t.env.NODE_ENV&&(!s||l.nextSibling))for(var c=l;c;){if(K.isRenderedByReact(c)){"production"!==t.env.NODE_ENV?j(!1,"render(): Target node has markup rendered by React, but there are unrelated nodes as well. This is most commonly caused by white-space inserted around server-rendered markup."):null;break}c=c.nextSibling}var u=s&&!i,p=K._renderNewRootComponent(e,n,u).getPublicInstance();return o&&o.call(p),p},constructAndRenderComponent:function(e,t,n){var o=y.createElement(e,t);return K.render(o,n)},constructAndRenderComponentByID:function(e,n,o){var r=document.getElementById(o);return"production"!==t.env.NODE_ENV?S(r,'Tried to get element with id of "%s" but it is not present on the page.',o):S(r),K.constructAndRenderComponent(e,n,r)},registerContainer:function(e){var t=r(e);return t&&(t=w.getReactRootIDFromNodeID(t)),t||(t=w.createReactRootID()),H[t]=e,t},unmountComponentAtNode:function(e){"production"!==t.env.NODE_ENV?j(null==v.current,"unmountComponentAtNode(): Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate."):null,"production"!==t.env.NODE_ENV?S(e&&(e.nodeType===F||e.nodeType===B),"unmountComponentAtNode(...): Target container is not a DOM element."):S(e&&(e.nodeType===F||e.nodeType===B));var n=r(e),o=q[n];return o?(K.unmountComponentFromNode(o,e),delete q[n],delete H[n],"production"!==t.env.NODE_ENV&&delete z[n],!0):!1},unmountComponentFromNode:function(e,t){for(_.unmountComponent(e),t.nodeType===B&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)},findReactContainerForID:function(e){var n=w.getReactRootIDFromNodeID(e),o=H[n];if("production"!==t.env.NODE_ENV){var r=z[n];if(r&&r.parentNode!==o){"production"!==t.env.NODE_ENV?S(a(r)===n,"ReactMount: Root element ID differed from reactRootID."):S(a(r)===n);var i=o.firstChild;i&&n===a(i)?z[n]=i:"production"!==t.env.NODE_ENV?j(!1,"ReactMount: Root element has been removed from its original container. New container:",r.parentNode):null}}return o},findReactNodeByID:function(e){var t=K.findReactContainerForID(e);return K.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=K.getID(e);return t?t.charAt(0)===L:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(K.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,n){var o=W,r=0,i=f(n)||e;for(o[0]=i.firstChild,o.length=1;r<o.length;){for(var a,l=o[r++];l;){var s=K.getID(l);s?n===s?a=l:w.isAncestorIDOf(s,n)&&(o.length=r=0,o.push(l.firstChild)):o.push(l.firstChild),l=l.nextSibling}if(a)return o.length=0,a}o.length=0,"production"!==t.env.NODE_ENV?S(!1,"findComponentRoot(..., %s): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID `%s`.",n,K.getID(e)):S(!1)},_mountImageIntoNode:function(e,n,r){if("production"!==t.env.NODE_ENV?S(n&&(n.nodeType===F||n.nodeType===B),"mountComponentIntoNode(...): Target container is not valid."):S(n&&(n.nodeType===F||n.nodeType===B)),r){var i=M(n);if(k.canReuseMarkup(e,i))return;var a=i.getAttribute(k.CHECKSUM_ATTR_NAME);i.removeAttribute(k.CHECKSUM_ATTR_NAME);var l=i.outerHTML;i.setAttribute(k.CHECKSUM_ATTR_NAME,a);var s=o(e,l),c=" (client) "+e.substring(s-20,s+20)+"\n (server) "+l.substring(s-20,s+20);"production"!==t.env.NODE_ENV?S(n.nodeType!==B,"You're trying to render a component to the document using server rendering but the checksum was invalid. This usually means you rendered a different component type or props on the client from the one on the server, or your render() methods are impure. React cannot handle this case due to cross-browser quirks by rendering at the document root. You should look for environment dependent code in your components and ensure the props are the same client and server side:\n%s",c):S(n.nodeType!==B),"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?j(!1,"React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:\n%s",c):null)}"production"!==t.env.NODE_ENV?S(n.nodeType!==B,"You're trying to render a component to the document but you didn't use server rendering. We can't do this without using server rendering due to cross-browser quirks. See React.renderToString() for server rendering."):S(n.nodeType!==B),I(n,e)},getReactRootID:r,getID:i,setID:l,getNode:s,getNodeFromInstance:c,purgeID:p};C.measureMethods(K,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),e.exports=K}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(){"production"!==t.env.NODE_ENV?m(O.ReactReconcileTransaction&&w,"ReactUpdates: must inject a reconcile transaction class and batching strategy"):m(O.ReactReconcileTransaction&&w)}function r(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=u.getPooled(),this.reconcileTransaction=O.ReactReconcileTransaction.getPooled()}function i(e,t,n,r,i){o(),w.batchedUpdates(e,t,n,r,i)}function a(e,t){return e._mountOrder-t._mountOrder}function l(e){var n=e.dirtyComponentsLength;"production"!==t.env.NODE_ENV?m(n===y.length,"Expected flush transaction's stored dirty-components length (%s) to match dirty-components array length (%s).",n,y.length):m(n===y.length),y.sort(a);for(var o=0;n>o;o++){var r=y[o],i=r._pendingCallbacks;if(r._pendingCallbacks=null,h.performUpdateIfNecessary(r,e.reconcileTransaction),i)for(var l=0;l<i.length;l++)e.callbackQueue.enqueue(i[l],r.getPublicInstance())}}function s(e){return o(),"production"!==t.env.NODE_ENV?v(null==d.current,"enqueueUpdate(): Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate."):null,w.isBatchingUpdates?void y.push(e):void w.batchedUpdates(s,e)}function c(e,n){"production"!==t.env.NODE_ENV?m(w.isBatchingUpdates,"ReactUpdates.asap: Can't enqueue an asap callback in a context whereupdates are not being batched."):m(w.isBatchingUpdates),x.enqueue(e,n),E=!0}var u=n(48),p=n(13),d=n(15),f=n(16),h=n(26),g=n(42),b=n(3),m=n(2),v=n(4),y=[],x=u.getPooled(),E=!1,w=null,N={initialize:function(){this.dirtyComponentsLength=y.length},close:function(){this.dirtyComponentsLength!==y.length?(y.splice(0,this.dirtyComponentsLength),_()):y.length=0}},k={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},C=[N,k];b(r.prototype,g.Mixin,{getTransactionWrappers:function(){return C},destructor:function(){this.dirtyComponentsLength=null,u.release(this.callbackQueue),this.callbackQueue=null,O.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return g.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),p.addPoolingTo(r);var _=function(){for(;y.length||E;){if(y.length){var e=r.getPooled();e.perform(l,null,e),r.release(e)}if(E){E=!1;var t=x;x=u.getPooled(),t.notifyAll(),u.release(t)}}};_=f.measure("ReactUpdates","flushBatchedUpdates",_);var D={injectReconcileTransaction:function(e){"production"!==t.env.NODE_ENV?m(e,"ReactUpdates: must provide a reconcile transaction class"):m(e),O.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){"production"!==t.env.NODE_ENV?m(e,"ReactUpdates: must provide a batching strategy"):m(e),"production"!==t.env.NODE_ENV?m("function"==typeof e.batchedUpdates,"ReactUpdates: must provide a batchedUpdates() function"):m("function"==typeof e.batchedUpdates),"production"!==t.env.NODE_ENV?m("boolean"==typeof e.isBatchingUpdates,"ReactUpdates: must provide an isBatchingUpdates boolean attribute"):m("boolean"==typeof e.isBatchingUpdates),w=e}},O={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:s,flushBatchedUpdates:_,injection:D,asap:c};e.exports=O}).call(t,n(1))},function(e,t,n){"use strict";var o=n(3),r=n(7).PropTypes,i=n(19),a=o({},r,{falsy:function(e,t,n){return e[t]?new Error("<"+n+'> should not have a "'+t+'" prop'):void 0},route:r.instanceOf(i),router:r.func});e.exports=a},function(e,t,n){(function(t){"use strict";var o=n(2),r=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},i=function(e,t){var n=this;if(n.instancePool.length){var o=n.instancePool.pop();return n.call(o,e,t),o}return new n(e,t)},a=function(e,t,n){var o=this;if(o.instancePool.length){var r=o.instancePool.pop();return o.call(r,e,t,n),r}return new o(e,t,n)},l=function(e,t,n,o,r){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,o,r),a}return new i(e,t,n,o,r)},s=function(e){var n=this;"production"!==t.env.NODE_ENV?o(e instanceof n,"Trying to release an instance into a pool of a different type."):o(e instanceof n),e.destructor&&e.destructor(),n.instancePool.length<n.poolSize&&n.instancePool.push(e)},c=10,u=r,p=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||u,n.poolSize||(n.poolSize=c),n.release=s,n},d={addPoolingTo:p,oneArgumentPooler:r,twoArgumentPooler:i,threeArgumentPooler:a,fiveArgumentPooler:l};e.exports=d}).call(t,n(1))},function(e,t,n){"use strict";var o=n(97),r={getDOMNode:function(){return o(this)}};e.exports=r},function(e,t){"use strict";var n={current:null};e.exports=n},function(e,t,n){(function(t){"use strict";function n(e,t,n){return n}var o={enableMeasure:!1,storedMeasure:n,measureMethods:function(e,n,r){if("production"!==t.env.NODE_ENV)for(var i in r)r.hasOwnProperty(i)&&(e[i]=o.measure(n,r[i],e[i]))},measure:function(e,n,r){if("production"!==t.env.NODE_ENV){var i=null,a=function(){return o.enableMeasure?(i||(i=o.storedMeasure(e,n,r)),i.apply(this,arguments)):r.apply(this,arguments)};return a.displayName=e+"_"+n,a}return r},injection:{injectMeasure:function(e){o.storedMeasure=e}}};e.exports=o}).call(t,n(1))},function(e,t){function n(e){return function(){return e}}function o(){}o.thatReturns=n,o.thatReturnsFalse=n(!1),o.thatReturnsTrue=n(!0),o.thatReturnsNull=n(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},e.exports=o},function(e,t){var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};e.exports=n},function(e,t,n){"use strict";var o,r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=n(3),l=n(2),s=n(4),c=n(45),u=function(){function e(t,n,o,i,a,l,s,u){r(this,e),this.name=t,this.path=n,this.paramNames=c.extractParamNames(this.path),this.ignoreScrollBehavior=!!o,this.isDefault=!!i,this.isNotFound=!!a,this.onEnter=l,this.onLeave=s,this.handler=u}return i(e,[{key:"appendChild",value:function(t){l(t instanceof e,"route.appendChild must use a valid Route"),this.childRoutes||(this.childRoutes=[]),this.childRoutes.push(t)}},{key:"toString",value:function(){var e="<Route";return this.name&&(e+=' name="'+this.name+'"'),e+=' path="'+this.path+'">'}}],[{key:"createRoute",value:function(t,n){t=t||{},"string"==typeof t&&(t={path:t});var r=o;r?s(null==t.parentRoute||t.parentRoute===r,"You should not use parentRoute with createRoute inside another route's child callback; it is ignored"):r=t.parentRoute;var i=t.name,a=t.path||i;!a||t.isDefault||t.isNotFound?a=r?r.path:"/":c.isAbsolute(a)?r&&l(a===r.path||0===r.paramNames.length,'You cannot nest path "%s" inside "%s"; the parent requires URL parameters',a,r.path):a=r?c.join(r.path,a):"/"+a,t.isNotFound&&!/\*$/.test(a)&&(a+="*");var u=new e(i,a,t.ignoreScrollBehavior,t.isDefault,t.isNotFound,t.onEnter,t.onLeave,t.handler);if(r&&(u.isDefault?(l(null==r.defaultRoute,"%s may not have more than one default route",r),r.defaultRoute=u):u.isNotFound&&(l(null==r.notFoundRoute,"%s may not have more than one not found route",r),r.notFoundRoute=u),r.appendChild(u)),"function"==typeof n){var p=o;o=u,n.call(u,u),o=p}return u}},{key:"createDefaultRoute",value:function(t){return e.createRoute(a({},t,{isDefault:!0}))}},{key:"createNotFoundRoute",value:function(t){return e.createRoute(a({},t,{isNotFound:!0}))}},{key:"createRedirect",value:function(t){return e.createRoute(a({},t,{path:t.path||t.from||"*",onEnter:function(e,n,o){e.redirect(t.to,t.params||n,t.query||o)}}))}}]),e}();e.exports=u},function(e,t,n){(function(t){"use strict";function o(e,t){return(e&t)===t}var r=n(2),i={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var n=e.Properties||{},a=e.DOMAttributeNames||{},s=e.DOMPropertyNames||{},c=e.DOMMutationMethods||{};e.isCustomAttribute&&l._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var u in n){"production"!==t.env.NODE_ENV?r(!l.isStandardName.hasOwnProperty(u),"injectDOMPropertyConfig(...): You're trying to inject DOM property '%s' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.",u):r(!l.isStandardName.hasOwnProperty(u)),l.isStandardName[u]=!0;var p=u.toLowerCase();if(l.getPossibleStandardName[p]=u,a.hasOwnProperty(u)){var d=a[u];l.getPossibleStandardName[d]=u,l.getAttributeName[u]=d}else l.getAttributeName[u]=p;l.getPropertyName[u]=s.hasOwnProperty(u)?s[u]:u,c.hasOwnProperty(u)?l.getMutationMethod[u]=c[u]:l.getMutationMethod[u]=null; var f=n[u];l.mustUseAttribute[u]=o(f,i.MUST_USE_ATTRIBUTE),l.mustUseProperty[u]=o(f,i.MUST_USE_PROPERTY),l.hasSideEffects[u]=o(f,i.HAS_SIDE_EFFECTS),l.hasBooleanValue[u]=o(f,i.HAS_BOOLEAN_VALUE),l.hasNumericValue[u]=o(f,i.HAS_NUMERIC_VALUE),l.hasPositiveNumericValue[u]=o(f,i.HAS_POSITIVE_NUMERIC_VALUE),l.hasOverloadedBooleanValue[u]=o(f,i.HAS_OVERLOADED_BOOLEAN_VALUE),"production"!==t.env.NODE_ENV?r(!l.mustUseAttribute[u]||!l.mustUseProperty[u],"DOMProperty: Cannot require using both attribute and property: %s",u):r(!l.mustUseAttribute[u]||!l.mustUseProperty[u]),"production"!==t.env.NODE_ENV?r(l.mustUseProperty[u]||!l.hasSideEffects[u],"DOMProperty: Properties that have side effects must use property: %s",u):r(l.mustUseProperty[u]||!l.hasSideEffects[u]),"production"!==t.env.NODE_ENV?r(!!l.hasBooleanValue[u]+!!l.hasNumericValue[u]+!!l.hasOverloadedBooleanValue[u]<=1,"DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s",u):r(!!l.hasBooleanValue[u]+!!l.hasNumericValue[u]+!!l.hasOverloadedBooleanValue[u]<=1)}}},a={},l={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasNumericValue:{},hasPositiveNumericValue:{},hasOverloadedBooleanValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<l._isCustomAttributeFunctions.length;t++){var n=l._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,o=a[e];return o||(a[e]=o={}),t in o||(n=document.createElement(e),o[t]=n[t]),o[t]},injection:i};e.exports=l}).call(t,n(1))},function(e,t,n){"use strict";function o(e,t,n){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var o=this.constructor.Interface;for(var r in o)if(o.hasOwnProperty(r)){var i=o[r];i?this[r]=i(n):this[r]=n[r]}var l=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;l?this.isDefaultPrevented=a.thatReturnsTrue:this.isDefaultPrevented=a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse}var r=n(13),i=n(3),a=n(17),l=n(64),s={type:null,target:l,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};i(o.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=a.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=a.thatReturnsTrue},persist:function(){this.isPersistent=a.thatReturnsTrue},isPersistent:a.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),o.Interface=s,o.augmentClass=function(e,t){var n=this,o=Object.create(n.prototype);i(o,e.prototype),e.prototype=o,e.prototype.constructor=e,e.Interface=i({},n.Interface,t),e.augmentClass=n.augmentClass,r.addPoolingTo(e,r.threeArgumentPooler)},r.addPoolingTo(o,r.threeArgumentPooler),e.exports=o},function(e,t,n){"use strict";var o=n(2),r=n(6).canUseDOM,i={length:1,back:function(){o(r,"Cannot use History.back without a DOM"),i.length-=1,window.history.back()}};e.exports=i},function(e,t,n){"use strict";function o(e){return Object.prototype.hasOwnProperty.call(e,g)||(e[g]=f++,p[e[g]]={}),p[e[g]]}var r=n(8),i=n(29),a=n(85),l=n(165),s=n(95),c=n(3),u=n(66),p={},d=!1,f=0,h={topBlur:"blur",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topScroll:"scroll",topSelectionChange:"selectionchange",topTextInput:"textInput",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topWheel:"wheel"},g="_reactListenersID"+String(Math.random()).slice(2),b=c({},l,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(b.handleTopLevel),b.ReactEventListener=e}},setEnabled:function(e){b.ReactEventListener&&b.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!b.ReactEventListener||!b.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,i=o(n),l=a.registrationNameDependencies[e],s=r.topLevelTypes,c=0,p=l.length;p>c;c++){var d=l[c];i.hasOwnProperty(d)&&i[d]||(d===s.topWheel?u("wheel")?b.ReactEventListener.trapBubbledEvent(s.topWheel,"wheel",n):u("mousewheel")?b.ReactEventListener.trapBubbledEvent(s.topWheel,"mousewheel",n):b.ReactEventListener.trapBubbledEvent(s.topWheel,"DOMMouseScroll",n):d===s.topScroll?u("scroll",!0)?b.ReactEventListener.trapCapturedEvent(s.topScroll,"scroll",n):b.ReactEventListener.trapBubbledEvent(s.topScroll,"scroll",b.ReactEventListener.WINDOW_HANDLE):d===s.topFocus||d===s.topBlur?(u("focus",!0)?(b.ReactEventListener.trapCapturedEvent(s.topFocus,"focus",n),b.ReactEventListener.trapCapturedEvent(s.topBlur,"blur",n)):u("focusin")&&(b.ReactEventListener.trapBubbledEvent(s.topFocus,"focusin",n),b.ReactEventListener.trapBubbledEvent(s.topBlur,"focusout",n)),i[s.topBlur]=!0,i[s.topFocus]=!0):h.hasOwnProperty(d)&&b.ReactEventListener.trapBubbledEvent(d,h[d],n),i[d]=!0)}},trapBubbledEvent:function(e,t,n){return b.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return b.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!d){var e=s.refreshScrollValues;b.ReactEventListener.monitorScrollValue(e),d=!0}},eventNameDispatchConfigs:i.eventNameDispatchConfigs,registrationNameModules:i.registrationNameModules,putListener:i.putListener,getListener:i.getListener,deleteListener:i.deleteListener,deleteAllListeners:i.deleteAllListeners});e.exports=b},function(e,t,n){(function(t){"use strict";function o(e){return f+e.toString(36)}function r(e,t){return e.charAt(t)===f||t===e.length}function i(e){return""===e||e.charAt(0)===f&&e.charAt(e.length-1)!==f}function a(e,t){return 0===t.indexOf(e)&&r(t,e.length)}function l(e){return e?e.substr(0,e.lastIndexOf(f)):""}function s(e,n){if("production"!==t.env.NODE_ENV?d(i(e)&&i(n),"getNextDescendantID(%s, %s): Received an invalid React DOM ID.",e,n):d(i(e)&&i(n)),"production"!==t.env.NODE_ENV?d(a(e,n),"getNextDescendantID(...): React has made an invalid assumption about the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.",e,n):d(a(e,n)),e===n)return e;var o,l=e.length+h;for(o=l;o<n.length&&!r(n,o);o++);return n.substr(0,o)}function c(e,n){var o=Math.min(e.length,n.length);if(0===o)return"";for(var a=0,l=0;o>=l;l++)if(r(e,l)&&r(n,l))a=l;else if(e.charAt(l)!==n.charAt(l))break;var s=e.substr(0,a);return"production"!==t.env.NODE_ENV?d(i(s),"getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s",e,n,s):d(i(s)),s}function u(e,n,o,r,i,c){e=e||"",n=n||"","production"!==t.env.NODE_ENV?d(e!==n,"traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.",e):d(e!==n);var u=a(n,e);"production"!==t.env.NODE_ENV?d(u||a(e,n),"traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do not have a parent path.",e,n):d(u||a(e,n));for(var p=0,f=u?l:s,h=e;;h=f(h,n)){var b;if(i&&h===e||c&&h===n||(b=o(h,u,r)),b===!1||h===n)break;"production"!==t.env.NODE_ENV?d(p++<g,"traverseParentPath(%s, %s, ...): Detected an infinite loop while traversing the React DOM ID tree. This may be due to malformed IDs: %s",e,n):d(p++<g)}}var p=n(94),d=n(2),f=".",h=f.length,g=100,b={createReactRootID:function(){return o(p.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===f&&e.length>1){var t=e.indexOf(f,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,o,r){var i=c(e,t);i!==e&&u(e,i,n,o,!1,!0),i!==t&&u(i,t,n,r,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(u("",e,t,n,!0,!1),u(e,"",t,n,!1,!0))},traverseAncestors:function(e,t,n){u("",e,t,n,!0,!1)},_getFirstCommonAncestorID:c,_getNextDescendantID:s,isAncestorIDOf:a,SEPARATOR:f};e.exports=b}).call(t,n(1))},function(e,t){"use strict";var n={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};e.exports=n},function(e,t,n){(function(t){"use strict";function o(){r.attachRefs(this,this._currentElement)}var r=n(171),i=n(31),a={mountComponent:function(e,n,r,a){var l=e.mountComponent(n,r,a);return"production"!==t.env.NODE_ENV&&i.checkAndWarnForMutatedProps(e._currentElement),r.getReactMountReady().enqueue(o,e),l},unmountComponent:function(e){r.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,n,a,l){var s=e._currentElement;if(n!==s||null==n._owner){"production"!==t.env.NODE_ENV&&i.checkAndWarnForMutatedProps(n);var c=r.shouldUpdateRefs(s,n);c&&r.detachRefs(e,s),e.receiveComponent(n,a,l),c&&a.getReactMountReady().enqueue(o,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}};e.exports=a}).call(t,n(1))},function(e,t){"use strict";var n={PUSH:"push",REPLACE:"replace",POP:"pop"};e.exports=n},function(e,t,n){(function(t){"use strict";function o(e,t){return null==t||r.hasBooleanValue[e]&&!t||r.hasNumericValue[e]&&isNaN(t)||r.hasPositiveNumericValue[e]&&1>t||r.hasOverloadedBooleanValue[e]&&t===!1}var r=n(20),i=n(206),a=n(4);if("production"!==t.env.NODE_ENV)var l={children:!0,dangerouslySetInnerHTML:!0,key:!0,ref:!0},s={},c=function(e){if(!(l.hasOwnProperty(e)&&l[e]||s.hasOwnProperty(e)&&s[e])){s[e]=!0;var n=e.toLowerCase(),o=r.isCustomAttribute(n)?n:r.getPossibleStandardName.hasOwnProperty(n)?r.getPossibleStandardName[n]:null;"production"!==t.env.NODE_ENV?a(null==o,"Unknown DOM property %s. Did you mean %s?",e,o):null}};var u={createMarkupForID:function(e){return r.ID_ATTRIBUTE_NAME+"="+i(e)},createMarkupForProperty:function(e,n){if(r.isStandardName.hasOwnProperty(e)&&r.isStandardName[e]){if(o(e,n))return"";var a=r.getAttributeName[e];return r.hasBooleanValue[e]||r.hasOverloadedBooleanValue[e]&&n===!0?a:a+"="+i(n)}return r.isCustomAttribute(e)?null==n?"":e+"="+i(n):("production"!==t.env.NODE_ENV&&c(e),null)},setValueForProperty:function(e,n,i){if(r.isStandardName.hasOwnProperty(n)&&r.isStandardName[n]){var a=r.getMutationMethod[n];if(a)a(e,i);else if(o(n,i))this.deleteValueForProperty(e,n);else if(r.mustUseAttribute[n])e.setAttribute(r.getAttributeName[n],""+i);else{var l=r.getPropertyName[n];r.hasSideEffects[n]&&""+e[l]==""+i||(e[l]=i)}}else r.isCustomAttribute(n)?null==i?e.removeAttribute(n):e.setAttribute(n,""+i):"production"!==t.env.NODE_ENV&&c(n)},deleteValueForProperty:function(e,n){if(r.isStandardName.hasOwnProperty(n)&&r.isStandardName[n]){var o=r.getMutationMethod[n];if(o)o(e,void 0);else if(r.mustUseAttribute[n])e.removeAttribute(r.getAttributeName[n]);else{var i=r.getPropertyName[n],a=r.getDefaultValueForProperty(e.nodeName,i);r.hasSideEffects[n]&&""+e[i]===a||(e[i]=a)}}else r.isCustomAttribute(n)?e.removeAttribute(n):"production"!==t.env.NODE_ENV&&c(n)}};e.exports=u}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(){var e=d&&d.traverseTwoPhase&&d.traverseEnterLeave;"production"!==t.env.NODE_ENV?s(e,"InstanceHandle not injected before use!"):s(e)}var r=n(85),i=n(49),a=n(60),l=n(61),s=n(2),c={},u=null,p=function(e){if(e){var t=i.executeDispatch,n=r.getPluginModuleForEvent(e);n&&n.executeDispatch&&(t=n.executeDispatch),i.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},d=null,f={injection:{injectMount:i.injection.injectMount,injectInstanceHandle:function(e){d=e,"production"!==t.env.NODE_ENV&&o()},getInstanceHandle:function(){return"production"!==t.env.NODE_ENV&&o(),d},injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},eventNameDispatchConfigs:r.eventNameDispatchConfigs,registrationNameModules:r.registrationNameModules,putListener:function(e,n,o){"production"!==t.env.NODE_ENV?s(!o||"function"==typeof o,"Expected %s listener to be a function, instead got type %s",n,typeof o):s(!o||"function"==typeof o);var r=c[n]||(c[n]={});r[e]=o},getListener:function(e,t){var n=c[t];return n&&n[e]},deleteListener:function(e,t){var n=c[t];n&&delete n[e]},deleteAllListeners:function(e){for(var t in c)delete c[t][e]},extractEvents:function(e,t,n,o){for(var i,l=r.plugins,s=0,c=l.length;c>s;s++){var u=l[s];if(u){var p=u.extractEvents(e,t,n,o);p&&(i=a(i,p))}}return i},enqueueEvents:function(e){e&&(u=a(u,e))},processEventQueue:function(){var e=u;u=null,l(e,p),"production"!==t.env.NODE_ENV?s(!u,"processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented."):s(!u)},__purge:function(){c={}},__getListenerBank:function(){return c}};e.exports=f}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e,t,n){var o=t.dispatchConfig.phasedRegistrationNames[n];return b(e,o)}function r(e,n,r){if("production"!==t.env.NODE_ENV&&!e)throw new Error("Dispatching id must not be null");var i=n?g.bubbled:g.captured,a=o(e,r,i);a&&(r._dispatchListeners=f(r._dispatchListeners,a),r._dispatchIDs=f(r._dispatchIDs,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&d.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,r,e)}function a(e,t,n){if(n&&n.dispatchConfig.registrationName){var o=n.dispatchConfig.registrationName,r=b(e,o);r&&(n._dispatchListeners=f(n._dispatchListeners,r),n._dispatchIDs=f(n._dispatchIDs,e))}}function l(e){e&&e.dispatchConfig.registrationName&&a(e.dispatchMarker,null,e)}function s(e){h(e,i)}function c(e,t,n,o){d.injection.getInstanceHandle().traverseEnterLeave(n,o,a,e,t)}function u(e){h(e,l)}var p=n(8),d=n(29),f=n(60),h=n(61),g=p.PropagationPhases,b=d.getListener,m={accumulateTwoPhaseDispatches:s,accumulateDirectDispatches:u,accumulateEnterLeaveDispatches:c};e.exports=m}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(){if(y.current){var e=y.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function r(e){var t=e&&e.getPublicInstance();if(!t)return void 0;var n=t.constructor;return n?n.displayName||n.name||void 0:void 0}function i(){var e=y.current;return e&&r(e)||void 0}function a(e,t){e._store.validated||null!=e.key||(e._store.validated=!0,s('Each child in an array or iterator should have a unique "key" prop.',e,t))}function l(e,t,n){_.test(e)&&s("Child objects should have non-numeric keys so ordering is preserved.",t,n)}function s(e,n,o){var a=i(),l="string"==typeof o?o:o.displayName||o.name,s=a||l,c=k[e]||(k[e]={});if(!c.hasOwnProperty(s)){c[s]=!0;var u=a?" Check the render method of "+a+".":l?" Check the React.render call using <"+l+">.":"",p="";if(n&&n._owner&&n._owner!==y.current){var d=r(n._owner);p=" It was passed a child from "+d+"."}"production"!==t.env.NODE_ENV?N(!1,e+"%s%s See https://fb.me/react-warning-keys for more information.",u,p):null}}function c(e,t){if(Array.isArray(e))for(var n=0;n<e.length;n++){var o=e[n];g.isValidElement(o)&&a(o,t)}else if(g.isValidElement(e))e._store.validated=!0;else if(e){var r=E(e);if(r){if(r!==e.entries)for(var i,s=r.call(e);!(i=s.next()).done;)g.isValidElement(i.value)&&a(i.value,t)}else if("object"==typeof e){var c=b.extractIfFragment(e);for(var u in c)c.hasOwnProperty(u)&&l(u,c[u],t)}}}function u(e,n,r,i){for(var a in n)if(n.hasOwnProperty(a)){var l;try{"production"!==t.env.NODE_ENV?w("function"==typeof n[a],"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",e||"React class",v[i],a):w("function"==typeof n[a]),l=n[a](r,a,e,i)}catch(s){l=s}if(l instanceof Error&&!(l.message in C)){C[l.message]=!0;var c=o(this);"production"!==t.env.NODE_ENV?N(!1,"Failed propType: %s%s",l.message,c):null}}}function p(e,n){var o=n.type,r="string"==typeof o?o:o.displayName,i=n._owner?n._owner.getPublicInstance().constructor.displayName:null,a=e+"|"+r+"|"+i;if(!D.hasOwnProperty(a)){D[a]=!0;var l="";r&&(l=" <"+r+" />");var s="";i&&(s=" The element was created by "+i+"."),"production"!==t.env.NODE_ENV?N(!1,"Don't set .props.%s of the React component%s. Instead, specify the correct value when initially creating the element or use React.cloneElement to make a new element with updated props.%s",e,l,s):null}}function d(e,t){return e!==e?t!==t:0===e&&0===t?1/e===1/t:e===t}function f(e){if(e._store){var t=e._store.originalProps,n=e.props;for(var o in n)n.hasOwnProperty(o)&&(t.hasOwnProperty(o)&&d(t[o],n[o])||(p(o,e),t[o]=n[o]))}}function h(e){if(null!=e.type){var n=x.getComponentClassForElement(e),o=n.displayName||n.name;n.propTypes&&u(o,n.propTypes,e.props,m.prop),"function"==typeof n.getDefaultProps&&("production"!==t.env.NODE_ENV?N(n.getDefaultProps.isReactClassApproved,"getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."):null)}}var g=n(5),b=n(38),m=n(58),v=n(40),y=n(15),x=n(39),E=n(100),w=n(2),N=n(4),k={},C={},_=/^\d+$/,D={},O={checkAndWarnForMutatedProps:f,createElement:function(e,n,o){"production"!==t.env.NODE_ENV?N(null!=e,"React.createElement: type should not be null or undefined. It should be a string (for DOM elements) or a ReactClass (for composite components)."):null;var r=g.createElement.apply(this,arguments);if(null==r)return r;for(var i=2;i<arguments.length;i++)c(arguments[i],e);return h(r),r},createFactory:function(e){var n=O.createElement.bind(null,e);if(n.type=e,"production"!==t.env.NODE_ENV)try{Object.defineProperty(n,"type",{enumerable:!1,get:function(){return"production"!==t.env.NODE_ENV?N(!1,"Factory.type is deprecated. Access the class directly before passing it to createFactory."):null,Object.defineProperty(this,"type",{value:e}),e}})}catch(o){}return n},cloneElement:function(e,t,n){for(var o=g.cloneElement.apply(this,arguments),r=2;r<arguments.length;r++)c(arguments[r],o.type);return h(o),o}};e.exports=O}).call(t,n(1))},function(e,t,n){"use strict";function o(e,t,n){r.call(this,e,t,n)}var r=n(21),i=n(64),a={view:function(e){if(e.view)return e.view;var t=i(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};r.augmentClass(o,a),e.exports=o},function(e,t,n){(function(t){"use strict";var o=n(2),r=function(e){var n,r={};"production"!==t.env.NODE_ENV?o(e instanceof Object&&!Array.isArray(e),"keyMirror(...): Argument must be an object."):o(e instanceof Object&&!Array.isArray(e));for(n in e)e.hasOwnProperty(n)&&(r[n]=n);return r};e.exports=r}).call(t,n(1))},function(e,t,n){try{(function(){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={state:{documents:{},content:{}},StoreDocuments:function(e){this.state.documents=e,this.onChange()},StoreContent:function(e){this.state.content=e,this.onChangeContent()},getDocuments:function(){var e=this.state.documents,t=[];for(var n in e)0!=e[n].ponderation&&t.push(e[n]);return t},getContent:function(){return this.state.content},onChangeContent:function(){},onChange:function(){}};t["default"]=n,e.exports=t["default"]}).call(this)}finally{}},function(e,t,n){"use strict";var o=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},r=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),i=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},a=n(7),l=n(2),s=n(12),c=n(36),u=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return i(t,e),r(t,[{key:"render",value:function(){l(!1,"%s elements are for router configuration only and should not be rendered",this.constructor.name)}}]),t}(a.Component);u.propTypes={name:s.string,path:s.string,handler:s.func,ignoreScrollBehavior:s.bool},u.defaultProps={handler:c},e.exports=u},function(e,t,n){"use strict";var o=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},r=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),i=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},a=n(7),l=n(123),s=n(3),c=n(12),u="__routeHandler__",p=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return i(t,e),r(t,[{key:"getChildContext",value:function(){return{routeDepth:this.context.routeDepth+1}}},{key:"componentDidMount",value:function(){this._updateRouteComponent(this.refs[u])}},{key:"componentDidUpdate",value:function(){this._updateRouteComponent(this.refs[u])}},{key:"componentWillUnmount",value:function(){this._updateRouteComponent(null)}},{key:"_updateRouteComponent",value:function(e){this.context.router.setRouteComponentAtDepth(this.getRouteDepth(),e)}},{key:"getRouteDepth",value:function(){return this.context.routeDepth}},{key:"createChildRouteHandler",value:function(e){var t=this.context.router.getRouteAtDepth(this.getRouteDepth());if(null==t)return null;var n=s({},e||this.props,{ref:u,params:this.context.router.getCurrentParams(),query:this.context.router.getCurrentQuery()});return a.createElement(t.handler,n)}},{key:"render",value:function(){var e=this.createChildRouteHandler();return e?a.createElement(l,null,e):a.createElement("script",null)}}]),t}(a.Component);p.contextTypes={routeDepth:c.number.isRequired,router:c.router.isRequired},p.childContextTypes={routeDepth:c.number.isRequired},e.exports=p},function(e,t,n){"use strict";var o=n(98),r={componentDidMount:function(){this.props.autoFocus&&o(this.getDOMNode())}};e.exports=r},function(e,t,n){(function(t){"use strict";var o=n(5),r=n(4);if("production"!==t.env.NODE_ENV){var i="_reactFragment",a="_reactDidWarn",l=!1;try{var s=function(){return 1};Object.defineProperty({},i,{enumerable:!1,value:!0}),Object.defineProperty({},"key",{enumerable:!0,get:s}),l=!0}catch(c){}var u=function(e,n){Object.defineProperty(e,n,{enumerable:!0,get:function(){return"production"!==t.env.NODE_ENV?r(this[a],"A ReactFragment is an opaque type. Accessing any of its properties is deprecated. Pass it to one of the React.Children helpers."):null,this[a]=!0,this[i][n]},set:function(e){"production"!==t.env.NODE_ENV?r(this[a],"A ReactFragment is an immutable opaque type. Mutating its properties is deprecated."):null,this[a]=!0,this[i][n]=e}})},p={},d=function(e){var t="";for(var n in e)t+=n+":"+typeof e[n]+",";var o=!!p[t];return p[t]=!0,o}}var f={create:function(e){if("production"!==t.env.NODE_ENV){if("object"!=typeof e||!e||Array.isArray(e))return"production"!==t.env.NODE_ENV?r(!1,"React.addons.createFragment only accepts a single object.",e):null,e;if(o.isValidElement(e))return"production"!==t.env.NODE_ENV?r(!1,"React.addons.createFragment does not accept a ReactElement without a wrapper object."):null,e;if(l){var n={};Object.defineProperty(n,i,{enumerable:!1,value:e}),Object.defineProperty(n,a,{writable:!0,enumerable:!1,value:!1});for(var s in e)u(n,s);return Object.preventExtensions(n),n}}return e},extract:function(e){return"production"!==t.env.NODE_ENV&&l?e[i]?e[i]:("production"!==t.env.NODE_ENV?r(d(e),"Any use of a keyed object should be wrapped in React.addons.createFragment(object) before being passed as a child."):null,e):e},extractIfFragment:function(e){if("production"!==t.env.NODE_ENV&&l){if(e[i])return e[i];for(var n in e)if(e.hasOwnProperty(n)&&o.isValidElement(e[n]))return f.extract(e)}return e}};e.exports=f}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e){if("function"==typeof e.type)return e.type;var t=e.type,n=p[t];return null==n&&(p[t]=n=c(t)),n}function r(e){return"production"!==t.env.NODE_ENV?s(u,"There is no registered component for the tag %s",e.type):s(u),new u(e.type,e.props)}function i(e){return new d(e)}function a(e){return e instanceof d}var l=n(3),s=n(2),c=null,u=null,p={},d=null,f={injectGenericComponentClass:function(e){u=e},injectTextComponentClass:function(e){d=e},injectComponentClasses:function(e){l(p,e)},injectAutoWrapper:function(e){c=e}},h={getComponentClassForElement:o,createInternalComponent:r,createInstanceForText:i,isTextComponent:a,injection:f};e.exports=h}).call(t,n(1))},function(e,t,n){(function(t){"use strict";var n={};"production"!==t.env.NODE_ENV&&(n={prop:"prop",context:"context",childContext:"child context"}),e.exports=n}).call(t,n(1))},function(e,t,n){"use strict";function o(e,t,n){r.call(this,e,t,n)}var r=n(32),i=n(95),a=n(63),l={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+i.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+i.currentScrollTop}};r.augmentClass(o,l),e.exports=o},function(e,t,n){(function(t){"use strict";var o=n(2),r={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,n,r,i,a,l,s,c){"production"!==t.env.NODE_ENV?o(!this.isInTransaction(),"Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction."):o(!this.isInTransaction());var u,p;try{this._isInTransaction=!0,u=!0,this.initializeAll(0),p=e.call(n,r,i,a,l,s,c),u=!1}finally{try{if(u)try{this.closeAll(0)}catch(d){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return p},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var o=t[n];try{this.wrapperInitData[n]=i.OBSERVED_ERROR,this.wrapperInitData[n]=o.initialize?o.initialize.call(this):null}finally{if(this.wrapperInitData[n]===i.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(r){}}}},closeAll:function(e){"production"!==t.env.NODE_ENV?o(this.isInTransaction(),"Transaction.closeAll(): Cannot close transaction when none are open."):o(this.isInTransaction());for(var n=this.transactionWrappers,r=e;r<n.length;r++){var a,l=n[r],s=this.wrapperInitData[r];try{a=!0,s!==i.OBSERVED_ERROR&&l.close&&l.close.call(this,s),a=!1}finally{if(a)try{this.closeAll(r+1)}catch(c){}}}this.wrapperInitData.length=0}},i={Mixin:r,OBSERVED_ERROR:{}};e.exports=i}).call(t,n(1))},function(e,t,n){(function(t){"use strict";var n={};"production"!==t.env.NODE_ENV&&Object.freeze(n),e.exports=n}).call(t,n(1))},function(e,t){"use strict";function n(e){return r[e]}function o(e){return(""+e).replace(i,n)}var r={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},i=/[&><"']/g;e.exports=o},function(e,t,n){"use strict";function o(e){if(!(e in p)){var t=[],n=e.replace(l,function(e,n){return n?(t.push(n),"([^/?#]+)"):"*"===e?(t.push("splat"),"(.*?)"):"\\"+e});p[e]={matcher:new RegExp("^"+n+"$","i"),paramNames:t}}return p[e]}var r=n(2),i=n(130),a=n(131),l=/:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g,s=/:([a-zA-Z_$][a-zA-Z0-9_$?]*[?]?)|[*]/g,c=/\/\/\?|\/\?\/|\/\?/g,u=/\?(.*)$/,p={},d={isAbsolute:function(e){return"/"===e.charAt(0)},join:function(e,t){return e.replace(/\/*$/,"/")+t},extractParamNames:function(e){return o(e).paramNames},extractParams:function(e,t){var n=o(e),r=n.matcher,i=n.paramNames,a=t.match(r);if(!a)return null;var l={};return i.forEach(function(e,t){l[e]=a[t+1]}),l},injectParams:function(e,t){t=t||{};var n=0;return e.replace(s,function(o,i){if(i=i||"splat","?"===i.slice(-1)){if(i=i.slice(0,-1),null==t[i])return""}else r(null!=t[i],'Missing "%s" parameter for path "%s"',i,e);var a;return"splat"===i&&Array.isArray(t[i])?(a=t[i][n++],r(null!=a,'Missing splat # %s for path "%s"',n,e)):a=t[i],a}).replace(c,"/")},extractQuery:function(e){var t=e.match(u);return t&&a.parse(t[1])},withoutQuery:function(e){return e.replace(u,"")},withQuery:function(e,t){var n=d.extractQuery(e);n&&(t=t?i(n,t):n);var o=a.stringify(t,{arrayFormat:"brackets"});return o?d.withoutQuery(e)+"?"+o:d.withoutQuery(e)}};e.exports=d},function(e,t,n){"use strict";t.DefaultRoute=n(74),t.Link=n(124),t.NotFoundRoute=n(75),t.Redirect=n(76),t.Route=n(35),t.ActiveHandler=n(36),t.RouteHandler=t.ActiveHandler,t.HashLocation=n(79),t.HistoryLocation=n(47),t.RefreshLocation=n(80),t.StaticLocation=n(81),t.TestLocation=n(127),t.ImitateBrowserBehavior=n(73),t.ScrollToTopBehavior=n(122),t.History=n(22),t.Navigation=n(118),t.State=n(120),t.createRoute=n(19).createRoute,t.createDefaultRoute=n(19).createDefaultRoute,t.createNotFoundRoute=n(19).createNotFoundRoute,t.createRedirect=n(19).createRedirect,t.createRoutesFromReactChildren=n(78),t.create=n(77),t.run=n(128)},function(e,t,n){"use strict";function o(e){var t={path:c.getCurrentPath(),type:e};l.forEach(function(e){e.call(c,t)})}function r(e){void 0!==e.state&&o(i.POP)}var i=n(27),a=n(22),l=[],s=!1,c={addChangeListener:function(e){l.push(e),s||(window.addEventListener?window.addEventListener("popstate",r,!1):window.attachEvent("onpopstate",r),s=!0)},removeChangeListener:function(e){l=l.filter(function(t){return t!==e}),0===l.length&&(window.addEventListener?window.removeEventListener("popstate",r,!1):window.removeEvent("onpopstate",r),s=!1)},push:function(e){window.history.pushState({path:e},"",e),a.length+=1,o(i.PUSH)},replace:function(e){window.history.replaceState({path:e},"",e),o(i.REPLACE)},pop:a.back,getCurrentPath:function(){return decodeURI(window.location.pathname+window.location.search)},toString:function(){return"<HistoryLocation>"}};e.exports=c},function(e,t,n){(function(t){"use strict";function o(){this._callbacks=null,this._contexts=null}var r=n(13),i=n(3),a=n(2);i(o.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,n=this._contexts;if(e){"production"!==t.env.NODE_ENV?a(e.length===n.length,"Mismatched list of contexts in callback queue"):a(e.length===n.length),this._callbacks=null,this._contexts=null;for(var o=0,r=e.length;r>o;o++)e[o].call(n[o]);e.length=0,n.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),r.addPoolingTo(o),e.exports=o}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e){return e===m.topMouseUp||e===m.topTouchEnd||e===m.topTouchCancel}function r(e){return e===m.topMouseMove||e===m.topTouchMove}function i(e){return e===m.topMouseDown||e===m.topTouchStart}function a(e,n){var o=e._dispatchListeners,r=e._dispatchIDs;if("production"!==t.env.NODE_ENV&&f(e),Array.isArray(o))for(var i=0;i<o.length&&!e.isPropagationStopped();i++)n(e,o[i],r[i]);else o&&n(e,o,r); }function l(e,t,n){e.currentTarget=b.Mount.getNode(n);var o=t(e,n);return e.currentTarget=null,o}function s(e,t){a(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function c(e){var n=e._dispatchListeners,o=e._dispatchIDs;if("production"!==t.env.NODE_ENV&&f(e),Array.isArray(n)){for(var r=0;r<n.length&&!e.isPropagationStopped();r++)if(n[r](e,o[r]))return o[r]}else if(n&&n(e,o))return o;return null}function u(e){var t=c(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function p(e){"production"!==t.env.NODE_ENV&&f(e);var n=e._dispatchListeners,o=e._dispatchIDs;"production"!==t.env.NODE_ENV?g(!Array.isArray(n),"executeDirectDispatch(...): Invalid `event`."):g(!Array.isArray(n));var r=n?n(e,o):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function d(e){return!!e._dispatchListeners}var f,h=n(8),g=n(2),b={Mount:null,injectMount:function(e){b.Mount=e,"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?g(e&&e.getNode,"EventPluginUtils.injection.injectMount(...): Injected Mount module is missing getNode."):g(e&&e.getNode))}},m=h.topLevelTypes;"production"!==t.env.NODE_ENV&&(f=function(e){var n=e._dispatchListeners,o=e._dispatchIDs,r=Array.isArray(n),i=Array.isArray(o),a=i?o.length:o?1:0,l=r?n.length:n?1:0;"production"!==t.env.NODE_ENV?g(i===r&&a===l,"EventPluginUtils: Invalid `event`."):g(i===r&&a===l)});var v={isEndish:o,isMoveish:r,isStartish:i,executeDirectDispatch:p,executeDispatch:l,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:u,hasDispatches:d,injection:b,useTouchEvents:!1};e.exports=v}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e){"production"!==t.env.NODE_ENV?c(null==e.props.checkedLink||null==e.props.valueLink,"Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don't want to use valueLink and vice versa."):c(null==e.props.checkedLink||null==e.props.valueLink)}function r(e){o(e),"production"!==t.env.NODE_ENV?c(null==e.props.value&&null==e.props.onChange,"Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don't want to use valueLink."):c(null==e.props.value&&null==e.props.onChange)}function i(e){o(e),"production"!==t.env.NODE_ENV?c(null==e.props.checked&&null==e.props.onChange,"Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don't want to use checkedLink"):c(null==e.props.checked&&null==e.props.onChange)}function a(e){this.props.valueLink.requestChange(e.target.value)}function l(e){this.props.checkedLink.requestChange(e.target.checked)}var s=n(92),c=n(2),u={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},p={Mixin:{propTypes:{value:function(e,t,n){return!e[t]||u[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,n){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:s.func}},getValue:function(e){return e.props.valueLink?(r(e),e.props.valueLink.value):e.props.value},getChecked:function(e){return e.props.checkedLink?(i(e),e.props.checkedLink.value):e.props.checked},getOnChange:function(e){return e.props.valueLink?(r(e),a):e.props.checkedLink?(i(e),l):e.props.onChange}};e.exports=p}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e){e.remove()}var r=n(23),i=n(60),a=n(61),l=n(2),s={trapBubbledEvent:function(e,n){"production"!==t.env.NODE_ENV?l(this.isMounted(),"Must be mounted to trap events"):l(this.isMounted());var o=this.getDOMNode();"production"!==t.env.NODE_ENV?l(o,"LocalEventTrapMixin.trapBubbledEvent(...): Requires node to be rendered."):l(o);var a=r.trapBubbledEvent(e,n,o);this._localEventListeners=i(this._localEventListeners,a)},componentWillUnmount:function(){this._localEventListeners&&a(this._localEventListeners,o)}};e.exports=s}).call(t,n(1))},function(e,t,n){"use strict";var o=n(87),r=n(10),i={processChildrenUpdates:o.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:o.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){r.purgeID(e)}};e.exports=i},function(e,t,n){(function(t){"use strict";var o=n(2),r=!1,i={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){"production"!==t.env.NODE_ENV?o(!r,"ReactCompositeComponent: injectEnvironment() can only be called once."):o(!r),i.unmountIDFromEnvironment=e.unmountIDFromEnvironment,i.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,i.processChildrenUpdates=e.processChildrenUpdates,r=!0}}};e.exports=i}).call(t,n(1))},function(e,t,n){(function(t){"use strict";var o=n(3),r=n(43),i=n(4),a=!1,l={current:r,withContext:function(e,n){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?i(a,"withContext is deprecated and will be removed in a future version. Use a wrapper component with getChildContext instead."):null,a=!0);var r,s=l.current;l.current=o({},s,e);try{r=n()}finally{l.current=s}return r}};e.exports=l}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e){e&&(null!=e.dangerouslySetInnerHTML&&("production"!==t.env.NODE_ENV?m(null==e.children,"Can only set one of `children` or `props.dangerouslySetInnerHTML`."):m(null==e.children),"production"!==t.env.NODE_ENV?m("object"==typeof e.dangerouslySetInnerHTML&&"__html"in e.dangerouslySetInnerHTML,"`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information."):m("object"==typeof e.dangerouslySetInnerHTML&&"__html"in e.dangerouslySetInnerHTML)),"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?x(null==e.innerHTML,"Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."):null,"production"!==t.env.NODE_ENV?x(!e.contentEditable||null==e.children,"A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."):null),"production"!==t.env.NODE_ENV?m(null==e.style||"object"==typeof e.style,"The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."):m(null==e.style||"object"==typeof e.style))}function r(e,n,o,r){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?x("onScroll"!==n||v("scroll",!0),"This browser doesn't support the `onScroll` event"):null);var i=d.findReactContainerForID(e);if(i){var a=i.nodeType===_?i.ownerDocument:i;w(n,a)}r.getPutListenerQueue().enqueuePutListener(e,n,o)}function i(e){M.call(R,e)||("production"!==t.env.NODE_ENV?m(T.test(e),"Invalid tag: %s",e):m(T.test(e)),R[e]=!0)}function a(e){i(e),this._tag=e,this._renderedChildren=null,this._previousStyleCopy=null,this._rootNodeID=null}var l=n(84),s=n(20),c=n(28),u=n(23),p=n(52),d=n(10),f=n(168),h=n(16),g=n(3),b=n(44),m=n(2),v=n(66),y=n(18),x=n(4),E=u.deleteListener,w=u.listenTo,N=u.registrationNameModules,k={string:!0,number:!0},C=y({style:null}),_=1,D=null,O={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},T=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,R={},M={}.hasOwnProperty;a.displayName="ReactDOMComponent",a.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,t,n){this._rootNodeID=e,o(this._currentElement.props);var r=O[this._tag]?"":"</"+this._tag+">";return this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t,n)+r},_createOpenTagMarkupAndPutListeners:function(e){var t=this._currentElement.props,n="<"+this._tag;for(var o in t)if(t.hasOwnProperty(o)){var i=t[o];if(null!=i)if(N.hasOwnProperty(o))r(this._rootNodeID,o,i,e);else{o===C&&(i&&(i=this._previousStyleCopy=g({},t.style)),i=l.createMarkupForStyles(i));var a=c.createMarkupForProperty(o,i);a&&(n+=" "+a)}}if(e.renderToStaticMarkup)return n+">";var s=c.createMarkupForID(this._rootNodeID);return n+" "+s+">"},_createContentMarkup:function(e,t){var n="";("listing"===this._tag||"pre"===this._tag||"textarea"===this._tag)&&(n="\n");var o=this._currentElement.props,r=o.dangerouslySetInnerHTML;if(null!=r){if(null!=r.__html)return n+r.__html}else{var i=k[typeof o.children]?o.children:null,a=null!=i?null:o.children;if(null!=i)return n+b(i);if(null!=a){var l=this.mountChildren(a,e,t);return n+l.join("")}}return n},receiveComponent:function(e,t,n){var o=this._currentElement;this._currentElement=e,this.updateComponent(t,o,e,n)},updateComponent:function(e,t,n,r){o(this._currentElement.props),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e,r)},_updateDOMProperties:function(e,t){var n,o,i,a=this._currentElement.props;for(n in e)if(!a.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===C){var l=this._previousStyleCopy;for(o in l)l.hasOwnProperty(o)&&(i=i||{},i[o]="");this._previousStyleCopy=null}else N.hasOwnProperty(n)?E(this._rootNodeID,n):(s.isStandardName[n]||s.isCustomAttribute(n))&&D.deletePropertyByID(this._rootNodeID,n);for(n in a){var c=a[n],u=n===C?this._previousStyleCopy:e[n];if(a.hasOwnProperty(n)&&c!==u)if(n===C)if(c?c=this._previousStyleCopy=g({},c):this._previousStyleCopy=null,u){for(o in u)!u.hasOwnProperty(o)||c&&c.hasOwnProperty(o)||(i=i||{},i[o]="");for(o in c)c.hasOwnProperty(o)&&u[o]!==c[o]&&(i=i||{},i[o]=c[o])}else i=c;else N.hasOwnProperty(n)?r(this._rootNodeID,n,c,t):(s.isStandardName[n]||s.isCustomAttribute(n))&&D.updatePropertyByID(this._rootNodeID,n,c)}i&&D.updateStylesByID(this._rootNodeID,i)},_updateDOMChildren:function(e,t,n){var o=this._currentElement.props,r=k[typeof e.children]?e.children:null,i=k[typeof o.children]?o.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,l=o.dangerouslySetInnerHTML&&o.dangerouslySetInnerHTML.__html,s=null!=r?null:e.children,c=null!=i?null:o.children,u=null!=r||null!=a,p=null!=i||null!=l;null!=s&&null==c?this.updateChildren(null,t,n):u&&!p&&this.updateTextContent(""),null!=i?r!==i&&this.updateTextContent(""+i):null!=l?a!==l&&D.updateInnerHTMLByID(this._rootNodeID,l):null!=c&&this.updateChildren(c,t,n)},unmountComponent:function(){this.unmountChildren(),u.deleteAllListeners(this._rootNodeID),p.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null}},h.measureMethods(a,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),g(a.prototype,a.Mixin,f.Mixin),a.injection={injectIDOperations:function(e){a.BackendIDOperations=D=e}},e.exports=a}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e){u[e]=!0}function r(e){delete u[e]}function i(e){return!!u[e]}var a,l=n(5),s=n(25),c=n(2),u={},p={injectEmptyComponent:function(e){a=l.createFactory(e)}},d=function(){};d.prototype.componentDidMount=function(){var e=s.get(this);e&&o(e._rootNodeID)},d.prototype.componentWillUnmount=function(){var e=s.get(this);e&&r(e._rootNodeID)},d.prototype.render=function(){return"production"!==t.env.NODE_ENV?c(a,"Trying to return null from a render, but no null placeholder component was injected."):c(a),a()};var f=l.createElement(d),h={emptyElement:f,injection:p,isNullComponentID:i};e.exports=h}).call(t,n(1))},function(e,t){"use strict";var n={currentlyMountingInstance:null,currentlyUnmountingInstance:null};e.exports=n},function(e,t,n){"use strict";var o=n(33),r=o({prop:null,context:null,childContext:null});e.exports=r},function(e,t,n){(function(t){"use strict";function o(e){e!==i.currentlyMountingInstance&&c.enqueueUpdate(e)}function r(e,n){"production"!==t.env.NODE_ENV?p(null==a.current,"%s(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.",n):p(null==a.current);var o=s.get(e);return o?o===i.currentlyUnmountingInstance?null:o:("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?d(!n,"%s(...): Can only update a mounted or mounting component. This usually means you called %s() on an unmounted component. This is a no-op.",n,n):null),null)}var i=n(57),a=n(15),l=n(5),s=n(25),c=n(11),u=n(3),p=n(2),d=n(4),f={enqueueCallback:function(e,n){"production"!==t.env.NODE_ENV?p("function"==typeof n,"enqueueCallback(...): You called `setProps`, `replaceProps`, `setState`, `replaceState`, or `forceUpdate` with a callback that isn't callable."):p("function"==typeof n);var a=r(e);return a&&a!==i.currentlyMountingInstance?(a._pendingCallbacks?a._pendingCallbacks.push(n):a._pendingCallbacks=[n],void o(a)):null},enqueueCallbackInternal:function(e,n){"production"!==t.env.NODE_ENV?p("function"==typeof n,"enqueueCallback(...): You called `setProps`, `replaceProps`, `setState`, `replaceState`, or `forceUpdate` with a callback that isn't callable."):p("function"==typeof n),e._pendingCallbacks?e._pendingCallbacks.push(n):e._pendingCallbacks=[n],o(e)},enqueueForceUpdate:function(e){var t=r(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,o(t))},enqueueReplaceState:function(e,t){var n=r(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,o(n))},enqueueSetState:function(e,t){var n=r(e,"setState");if(n){var i=n._pendingStateQueue||(n._pendingStateQueue=[]);i.push(t),o(n)}},enqueueSetProps:function(e,n){var i=r(e,"setProps");if(i){"production"!==t.env.NODE_ENV?p(i._isTopLevel,"setProps(...): You called `setProps` on a component with a parent. This is an anti-pattern since props will get reactively updated when rendered. Instead, change the owner's `render` method to pass the correct value as props to the component where it is created."):p(i._isTopLevel);var a=i._pendingElement||i._currentElement,s=u({},a.props,n);i._pendingElement=l.cloneAndReplaceProps(a,s),o(i)}},enqueueReplaceProps:function(e,n){var i=r(e,"replaceProps");if(i){"production"!==t.env.NODE_ENV?p(i._isTopLevel,"replaceProps(...): You called `replaceProps` on a component with a parent. This is an anti-pattern since props will get reactively updated when rendered. Instead, change the owner's `render` method to pass the correct value as props to the component where it is created."):p(i._isTopLevel);var a=i._pendingElement||i._currentElement;i._pendingElement=l.cloneAndReplaceProps(a,n),o(i)}},enqueueElementInternal:function(e,t){e._pendingElement=t,o(e)}};e.exports=f}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e,n){if("production"!==t.env.NODE_ENV?r(null!=n,"accumulateInto(...): Accumulated items must not be null or undefined."):r(null!=n),null==e)return n;var o=Array.isArray(e),i=Array.isArray(n);return o&&i?(e.push.apply(e,n),e):o?(e.push(n),e):i?[e].concat(n):[e,n]}var r=n(2);e.exports=o}).call(t,n(1))},function(e,t){"use strict";var n=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};e.exports=n},function(e,t){"use strict";function n(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}e.exports=n},function(e,t){"use strict";function n(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var o=r[e];return o?!!n[o]:!1}function o(e){return n}var r={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};e.exports=o},function(e,t){"use strict";function n(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}e.exports=n},function(e,t,n){(function(t){"use strict";function o(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function r(e,n){var r;if((null===e||e===!1)&&(e=a.emptyElement),"object"==typeof e){var i=e;"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?u(i&&("function"==typeof i.type||"string"==typeof i.type),"Only functions or strings can be mounted as React components."):null),r=n===i.type&&"string"==typeof i.type?l.createInternalComponent(i):o(i.type)?new i.type(i):new p}else"string"==typeof e||"number"==typeof e?r=l.createInstanceForText(e):"production"!==t.env.NODE_ENV?c(!1,"Encountered invalid React node of type %s",typeof e):c(!1);return"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?u("function"==typeof r.construct&&"function"==typeof r.mountComponent&&"function"==typeof r.receiveComponent&&"function"==typeof r.unmountComponent,"Only React Components can be mounted."):null),r.construct(e),r._mountIndex=0,r._mountImage=null,"production"!==t.env.NODE_ENV&&(r._isOwnerNecessary=!1,r._warnedAboutRefsInRender=!1),"production"!==t.env.NODE_ENV&&Object.preventExtensions&&Object.preventExtensions(r),r}var i=n(149),a=n(56),l=n(39),s=n(3),c=n(2),u=n(4),p=function(){};s(p.prototype,i.Mixin,{_instantiateReactComponent:r}),e.exports=r}).call(t,n(1))},function(e,t,n){"use strict";/** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function o(e,t){if(!i.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,o=n in document;if(!o){var a=document.createElement("div");a.setAttribute(n,"return;"),o="function"==typeof a[n]}return!o&&r&&"wheel"===e&&(o=document.implementation.hasFeature("Events.wheel","3.0")),o}var r,i=n(6);i.canUseDOM&&(r=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),e.exports=o},function(e,t,n){"use strict";var o=n(6),r=/^[ \r\n\t\f]/,i=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,a=function(e,t){e.innerHTML=t};if("undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(a=function(e,t){MSApp.execUnsafeLocalFunction(function(){e.innerHTML=t})}),o.canUseDOM){var l=document.createElement("div");l.innerHTML=" ",""===l.innerHTML&&(a=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),r.test(t)||"<"===t[0]&&i.test(t)){e.innerHTML="\ufeff"+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}e.exports=a},function(e,t,n){(function(t){"use strict";function o(e,n){if(null!=e&&null!=n){var o=typeof e,i=typeof n;if("string"===o||"number"===o)return"string"===i||"number"===i;if("object"===i&&e.type===n.type&&e.key===n.key){var a=e._owner===n._owner,l=null,s=null,c=null;return"production"!==t.env.NODE_ENV&&(a||(null!=e._owner&&null!=e._owner.getPublicInstance()&&null!=e._owner.getPublicInstance().constructor&&(l=e._owner.getPublicInstance().constructor.displayName),null!=n._owner&&null!=n._owner.getPublicInstance()&&null!=n._owner.getPublicInstance().constructor&&(s=n._owner.getPublicInstance().constructor.displayName),null!=n.type&&null!=n.type.displayName&&(c=n.type.displayName),null!=n.type&&"string"==typeof n.type&&(c=n.type),("string"!=typeof n.type||"input"===n.type||"textarea"===n.type)&&(null!=e._owner&&e._owner._isOwnerNecessary===!1||null!=n._owner&&n._owner._isOwnerNecessary===!1)&&(null!=e._owner&&(e._owner._isOwnerNecessary=!0),null!=n._owner&&(n._owner._isOwnerNecessary=!0),"production"!==t.env.NODE_ENV?r(!1,"<%s /> is being rendered by both %s and %s using the same key (%s) in the same place. Currently, this means that they don't preserve state. This behavior should be very rare so we're considering deprecating it. Please contact the React team and explain your use case so that we can take that into consideration.",c||"Unknown Component",l||"[Unknown]",s||"[Unknown]",e.key):null))),a}}return!1}var r=n(4);e.exports=o}).call(t,n(1))},function(e,t,n){e.exports=n.p+"f4769f9bdb7466be65088239c12046d1.eot"},function(e,t,n){try{(function(){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(34),i=o(r),a=n(108),l=o(a),s={fetchDocuments:function(e){l["default"].ajax({url:"/request/?req="+e,dataType:"json",type:"GET",success:function(e){i["default"].StoreDocuments(e)}.bind(this),error:function(e,t,n){console.error("/request/",t,n.toString())}.bind(this)})},fetchContent:function(e){l["default"].ajax({url:"/documents/"+e,dataType:"text",type:"GET",success:function(e){i["default"].StoreContent(e)}.bind(this),error:function(e,t,n){console.error("/documents/",t,n.toString())}.bind(this)})}};t["default"]=s,e.exports=t["default"]}).call(this)}finally{}},function(e,t){"use strict";function n(){}e.exports=n},function(e,t){"use strict";function n(e,t,n){this.to=e,this.params=t,this.query=n}e.exports=n},function(e,t,n){"use strict";var o=n(27),r={updateScrollPosition:function(e,t){switch(t){case o.PUSH:case o.REPLACE:window.scrollTo(0,0);break;case o.POP:e?window.scrollTo(e.x,e.y):window.scrollTo(0,0)}}};e.exports=r},function(e,t,n){"use strict";var o=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},r=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},i=n(12),a=n(36),l=n(35),s=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return r(t,e),t}(l);s.propTypes={name:i.string,path:i.falsy,children:i.falsy,handler:i.func.isRequired},s.defaultProps={handler:a},e.exports=s},function(e,t,n){"use strict";var o=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},r=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},i=n(12),a=n(36),l=n(35),s=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return r(t,e),t}(l);s.propTypes={name:i.string,path:i.falsy,children:i.falsy,handler:i.func.isRequired},s.defaultProps={handler:a},e.exports=s},function(e,t,n){"use strict";var o=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},r=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},i=n(12),a=n(35),l=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return r(t,e),t}(a);l.propTypes={path:i.string,from:i.string,to:i.string,handler:i.falsy},l.defaultProps={},e.exports=l},function(e,t,n){(function(t){"use strict";function o(e,t){for(var n in t)if(t.hasOwnProperty(n)&&e[n]!==t[n])return!1;return!0}function r(e,t,n,r,i,a){return e.some(function(e){if(e!==t)return!1;for(var l,s=t.paramNames,c=0,u=s.length;u>c;++c)if(l=s[c],r[l]!==n[l])return!1;return o(i,a)&&o(a,i)})}function i(e,t){for(var n,o=0,r=e.length;r>o;++o)n=e[o],n.name&&(d(null==t[n.name],'You may not have more than one route named "%s"',n.name),t[n.name]=n),n.childRoutes&&i(n.childRoutes,t)}function a(e,t){return e.some(function(e){return e.name===t})}function l(e,t){for(var n in t)if(String(e[n])!==String(t[n]))return!1;return!0}function s(e,t){for(var n in t)if(String(e[n])!==String(t[n]))return!1;return!0}function c(e){e=e||{},w(e)&&(e={routes:e});var n=[],o=e.location||P,c=e.scrollBehavior||S,g={},I={},A=null,j=null;"string"==typeof o&&(o=new y(o)),o instanceof y?p(!f||"test"===t.env.NODE_ENV,"You should not use a static location in a DOM environment because the router will not be kept in sync with the current URL"):d(f||o.needsDOM===!1,"You cannot use %s without a DOM",o),o!==m||R()||(o=v);var L=u.createClass({displayName:"Router",statics:{isRunning:!1,cancelPendingTransition:function(){A&&(A.cancel(),A=null)},clearAllRoutes:function(){L.cancelPendingTransition(),L.namedRoutes={},L.routes=[]},addRoutes:function(e){w(e)&&(e=E(e)),i(e,L.namedRoutes),L.routes.push.apply(L.routes,e)},replaceRoutes:function(e){L.clearAllRoutes(),L.addRoutes(e),L.refresh()},match:function(e){return O.findMatch(L.routes,e)},makePath:function(e,t,n){var o;if(M.isAbsolute(e))o=e;else{var r=e instanceof T?e:L.namedRoutes[e];d(r instanceof T,'Cannot find a route named "%s"',e),o=r.path}return M.withQuery(M.injectParams(o,t),n)},makeHref:function(e,t,n){var r=L.makePath(e,t,n);return o===b?"#"+r:r},transitionTo:function(e,t,n){var r=L.makePath(e,t,n);A?o.replace(r):o.push(r)},replaceWith:function(e,t,n){o.replace(L.makePath(e,t,n))},goBack:function(){return _.length>1||o===v?(o.pop(),!0):(p(!1,"goBack() was ignored because there is no router history"),!1)},handleAbort:e.onAbort||function(e){if(o instanceof y)throw new Error("Unhandled aborted transition! Reason: "+e);e instanceof D||(e instanceof C?o.replace(L.makePath(e.to,e.params,e.query)):o.pop())},handleError:e.onError||function(e){throw e},handleLocationChange:function(e){L.dispatch(e.path,e.type)},dispatch:function(e,t){L.cancelPendingTransition();var o=g.path,i=null==t;if(o!==e||i){o&&t===h.PUSH&&L.recordScrollPosition(o);var a=L.match(e);p(null!=a,'No route matches path "%s". Make sure you have <Route path="%s"> somewhere in your routes',e,e),null==a&&(a={});var l,s,c=g.routes||[],u=g.params||{},d=g.query||{},f=a.routes||[],b=a.params||{},m=a.query||{};c.length?(l=c.filter(function(e){return!r(f,e,u,b,d,m)}),s=f.filter(function(e){return!r(c,e,u,b,d,m)})):(l=[],s=f);var v=new N(e,L.replaceWith.bind(L,e));A=v;var y=n.slice(c.length-l.length);N.from(v,l,y,function(n){return n||v.abortReason?j.call(L,n,v):void N.to(v,s,b,m,function(n){j.call(L,n,v,{path:e,action:t,pathname:a.pathname,routes:f,params:b,query:m})})})}},run:function(e){d(!L.isRunning,"Router is already running"),j=function(t,n,o){t&&L.handleError(t),A===n&&(A=null,n.abortReason?L.handleAbort(n.abortReason):e.call(L,L,I=o))},o instanceof y||(o.addChangeListener&&o.addChangeListener(L.handleLocationChange),L.isRunning=!0),L.refresh()},refresh:function(){L.dispatch(o.getCurrentPath(),null)},stop:function(){L.cancelPendingTransition(),o.removeChangeListener&&o.removeChangeListener(L.handleLocationChange),L.isRunning=!1},getLocation:function(){return o},getScrollBehavior:function(){return c},getRouteAtDepth:function(e){var t=g.routes;return t&&t[e]},setRouteComponentAtDepth:function(e,t){n[e]=t},getCurrentPath:function(){return g.path},getCurrentPathname:function(){return g.pathname},getCurrentParams:function(){return g.params},getCurrentQuery:function(){return g.query},getCurrentRoutes:function(){return g.routes},isActive:function(e,t,n){return M.isAbsolute(e)?e===g.path:a(g.routes,e)&&l(g.params,t)&&(null==n||s(g.query,n))}},mixins:[x],propTypes:{children:k.falsy},childContextTypes:{routeDepth:k.number.isRequired,router:k.router.isRequired},getChildContext:function(){return{routeDepth:1,router:L}},getInitialState:function(){return g=I},componentWillReceiveProps:function(){this.setState(g=I)},componentWillUnmount:function(){L.stop()},render:function(){var e=L.getRouteAtDepth(0);return e?u.createElement(e.handler,this.props):null}});return L.clearAllRoutes(),e.routes&&L.addRoutes(e.routes),L}var u=n(7),p=n(4),d=n(2),f=n(6).canUseDOM,h=n(27),g=n(73),b=n(79),m=n(47),v=n(80),y=n(81),x=n(119),E=n(78),w=n(126),N=n(121),k=n(12),C=n(72),_=n(22),D=n(71),O=n(117),T=n(19),R=n(129),M=n(45),P=f?b:"/",S=f?g:null;e.exports=c}).call(t,n(1))},function(e,t,n){"use strict";function o(e,t,n){e=e||"UnknownComponent";for(var o in t)if(t.hasOwnProperty(o)){var r=t[o](n,o,e);r instanceof Error&&c(!1,r.message)}}function r(e){var t=s({},e),n=t.handler;return n&&(t.onEnter=n.willTransitionTo,t.onLeave=n.willTransitionFrom),t}function i(e){if(l.isValidElement(e)){var t=e.type,n=s({},t.defaultProps,e.props);return t.propTypes&&o(t.displayName,t.propTypes,n),t===u?f.createDefaultRoute(r(n)):t===p?f.createNotFoundRoute(r(n)):t===d?f.createRedirect(r(n)):f.createRoute(r(n),function(){n.children&&a(n.children)})}}function a(e){var t=[];return l.Children.forEach(e,function(e){(e=i(e))&&t.push(e)}),t}var l=n(7),s=n(3),c=n(4),u=n(74),p=n(75),d=n(76),f=n(19);e.exports=a},function(e,t,n){"use strict";function o(e){e===l.PUSH&&(s.length+=1);var t={path:p.getCurrentPath(),type:e};c.forEach(function(e){e.call(p,t)})}function r(){var e=p.getCurrentPath();return"/"===e.charAt(0)?!0:(p.replace("/"+e),!1)}function i(){if(r()){var e=a;a=null,o(e||l.POP)}}var a,l=n(27),s=n(22),c=[],u=!1,p={addChangeListener:function(e){c.push(e),r(),u||(window.addEventListener?window.addEventListener("hashchange",i,!1):window.attachEvent("onhashchange",i),u=!0)},removeChangeListener:function(e){c=c.filter(function(t){return t!==e}),0===c.length&&(window.removeEventListener?window.removeEventListener("hashchange",i,!1):window.removeEvent("onhashchange",i),u=!1)},push:function(e){a=l.PUSH,window.location.hash=e},replace:function(e){a=l.REPLACE,window.location.replace(window.location.pathname+window.location.search+"#"+e)},pop:function(){a=l.POP,s.back()},getCurrentPath:function(){return decodeURI(window.location.href.split("#")[1]||"")},toString:function(){return"<HashLocation>"}};e.exports=p},function(e,t,n){"use strict";var o=n(47),r=n(22),i={push:function(e){window.location=e},replace:function(e){window.location.replace(e)},pop:r.back,getCurrentPath:o.getCurrentPath,toString:function(){return"<RefreshLocation>"}};e.exports=i},function(e,t,n){"use strict";function o(){a(!1,"You cannot modify a static location")}var r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=n(2),l=function(){function e(t){r(this,e),this.path=t}return i(e,[{key:"getCurrentPath",value:function(){return this.path}},{key:"toString",value:function(){return'<StaticLocation path="'+this.path+'">'}}]),e}();l.prototype.push=o,l.prototype.replace=o,l.prototype.pop=o,e.exports=l},function(e,t){t.arrayToObject=function(e){for(var t={},n=0,o=e.length;o>n;++n)"undefined"!=typeof e[n]&&(t[n]=e[n]);return t},t.merge=function(e,n){if(!n)return e;if("object"!=typeof n)return Array.isArray(e)?e.push(n):e[n]=!0,e;if("object"!=typeof e)return e=[e].concat(n);Array.isArray(e)&&!Array.isArray(n)&&(e=t.arrayToObject(e));for(var o=Object.keys(n),r=0,i=o.length;i>r;++r){var a=o[r],l=n[a];e[a]?e[a]=t.merge(e[a],l):e[a]=l}return e},t.decode=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},t.compact=function(e,n){if("object"!=typeof e||null===e)return e;n=n||[];var o=n.indexOf(e);if(-1!==o)return n[o];if(n.push(e),Array.isArray(e)){for(var r=[],i=0,a=e.length;a>i;++i)"undefined"!=typeof e[i]&&r.push(e[i]);return r}var l=Object.keys(e);for(i=0,a=l.length;a>i;++i){var s=l[i];e[s]=t.compact(e[s],n)}return e},t.isRegExp=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},t.isBuffer=function(e){return null===e||"undefined"==typeof e?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}},function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var o={boxFlex:!0,boxFlexGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0},r=["Webkit","ms","Moz","O"];Object.keys(o).forEach(function(e){r.forEach(function(t){o[n(t,e)]=o[e]})});var i={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0}},a={isUnitlessNumber:o,shorthandPropertyExpansions:i};e.exports=a},function(e,t,n){(function(t){"use strict";var o=n(83),r=n(6),i=n(188),a=n(192),l=n(199),s=n(202),c=n(4),u=s(function(e){return l(e)}),p="cssFloat";if(r.canUseDOM&&void 0===document.documentElement.style.cssFloat&&(p="styleFloat"),"production"!==t.env.NODE_ENV)var d=/^(?:webkit|moz|o)[A-Z]/,f=/;\s*$/,h={},g={},b=function(e){h.hasOwnProperty(e)&&h[e]||(h[e]=!0,"production"!==t.env.NODE_ENV?c(!1,"Unsupported style property %s. Did you mean %s?",e,i(e)):null)},m=function(e){h.hasOwnProperty(e)&&h[e]||(h[e]=!0,"production"!==t.env.NODE_ENV?c(!1,"Unsupported vendor-prefixed style property %s. Did you mean %s?",e,e.charAt(0).toUpperCase()+e.slice(1)):null)},v=function(e,n){g.hasOwnProperty(n)&&g[n]||(g[n]=!0,"production"!==t.env.NODE_ENV?c(!1,'Style property values shouldn\'t contain a semicolon. Try "%s: %s" instead.',e,n.replace(f,"")):null)},y=function(e,t){e.indexOf("-")>-1?b(e):d.test(e)?m(e):f.test(t)&&v(e,t)};var x={createMarkupForStyles:function(e){var n="";for(var o in e)if(e.hasOwnProperty(o)){var r=e[o];"production"!==t.env.NODE_ENV&&y(o,r),null!=r&&(n+=u(o)+":",n+=a(o,r)+";")}return n||null},setValueForStyles:function(e,n){var r=e.style;for(var i in n)if(n.hasOwnProperty(i)){"production"!==t.env.NODE_ENV&&y(i,n[i]);var l=a(i,n[i]);if("float"===i&&(i=p),l)r[i]=l;else{var s=o.shorthandPropertyExpansions[i];if(s)for(var c in s)r[c]="";else r[i]=""}}}};e.exports=x}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(){if(l)for(var e in s){var n=s[e],o=l.indexOf(e);if("production"!==t.env.NODE_ENV?a(o>-1,"EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.",e):a(o>-1),!c.plugins[o]){"production"!==t.env.NODE_ENV?a(n.extractEvents,"EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.",e):a(n.extractEvents),c.plugins[o]=n;var i=n.eventTypes;for(var u in i)"production"!==t.env.NODE_ENV?a(r(i[u],n,u),"EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.",u,e):a(r(i[u],n,u))}}}function r(e,n,o){"production"!==t.env.NODE_ENV?a(!c.eventNameDispatchConfigs.hasOwnProperty(o),"EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.",o):a(!c.eventNameDispatchConfigs.hasOwnProperty(o)),c.eventNameDispatchConfigs[o]=e;var r=e.phasedRegistrationNames;if(r){for(var l in r)if(r.hasOwnProperty(l)){var s=r[l];i(s,n,o)}return!0}return e.registrationName?(i(e.registrationName,n,o),!0):!1}function i(e,n,o){"production"!==t.env.NODE_ENV?a(!c.registrationNameModules[e],"EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.",e):a(!c.registrationNameModules[e]),c.registrationNameModules[e]=n,c.registrationNameDependencies[e]=n.eventTypes[o].dependencies}var a=n(2),l=null,s={},c={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){"production"!==t.env.NODE_ENV?a(!l,"EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React."):a(!l),l=Array.prototype.slice.call(e),o()},injectEventPluginsByName:function(e){var n=!1;for(var r in e)if(e.hasOwnProperty(r)){var i=e[r];s.hasOwnProperty(r)&&s[r]===i||("production"!==t.env.NODE_ENV?a(!s[r],"EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.",r):a(!s[r]),s[r]=i,n=!0)}n&&o()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return c.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var o=c.registrationNameModules[t.phasedRegistrationNames[n]];if(o)return o}return null},_resetEventPlugins:function(){l=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];c.plugins.length=0;var t=c.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var o=c.registrationNameModules;for(var r in o)o.hasOwnProperty(r)&&delete o[r]}};e.exports=c}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e,t){this.props=e,this.context=t}var r=n(59),i=n(2),a=n(4);if(o.prototype.setState=function(e,n){"production"!==t.env.NODE_ENV?i("object"==typeof e||"function"==typeof e||null==e,"setState(...): takes an object of state variables to update or a function which returns an object of state variables."):i("object"==typeof e||"function"==typeof e||null==e),"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?a(null!=e,"setState(...): You passed an undefined or null state object; instead, use forceUpdate()."):null),r.enqueueSetState(this,e),n&&r.enqueueCallback(this,n)},o.prototype.forceUpdate=function(e){r.enqueueForceUpdate(this),e&&r.enqueueCallback(this,e)},"production"!==t.env.NODE_ENV){var l={getDOMNode:["getDOMNode","Use React.findDOMNode(component) instead."],isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceProps:["replaceProps","Instead, call React.render again at the top level."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."],setProps:["setProps","Instead, call React.render again at the top level."]},s=function(e,n){try{Object.defineProperty(o.prototype,e,{get:function(){return void("production"!==t.env.NODE_ENV?a(!1,"%s(...) is deprecated in plain JavaScript React classes. %s",n[0],n[1]):null)}})}catch(r){}};for(var c in l)l.hasOwnProperty(c)&&s(c,l[c])}e.exports=o}).call(t,n(1))},function(e,t,n){(function(t){"use strict";var o=n(84),r=n(138),i=n(28),a=n(10),l=n(16),s=n(2),c=n(67),u={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},p={updatePropertyByID:function(e,n,o){var r=a.getNode(e);"production"!==t.env.NODE_ENV?s(!u.hasOwnProperty(n),"updatePropertyByID(...): %s",u[n]):s(!u.hasOwnProperty(n)),null!=o?i.setValueForProperty(r,n,o):i.deleteValueForProperty(r,n)},deletePropertyByID:function(e,n,o){var r=a.getNode(e);"production"!==t.env.NODE_ENV?s(!u.hasOwnProperty(n),"updatePropertyByID(...): %s",u[n]):s(!u.hasOwnProperty(n)),i.deleteValueForProperty(r,n,o)},updateStylesByID:function(e,t){var n=a.getNode(e);o.setValueForStyles(n,t)},updateInnerHTMLByID:function(e,t){var n=a.getNode(e);c(n,t)},updateTextContentByID:function(e,t){var n=a.getNode(e);r.updateTextContent(n,t)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=a.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=a.getNode(e[n].parentID);r.processUpdates(e,t)}};l.measureMethods(p,"ReactDOMIDOperations",{updatePropertyByID:"updatePropertyByID",deletePropertyByID:"deletePropertyByID",updateStylesByID:"updateStylesByID",updateInnerHTMLByID:"updateInnerHTMLByID",updateTextContentByID:"updateTextContentByID",dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),e.exports=p}).call(t,n(1))},function(e,t,n){"use strict";var o=n(28),r=n(52),i=n(55),a=n(3),l=n(44),s=function(e){};a(s.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,t,n){this._rootNodeID=e;var r=l(this._stringText);return t.renderToStaticMarkup?r:"<span "+o.createMarkupForID(e)+">"+r+"</span>"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;n!==this._stringText&&(this._stringText=n,i.BackendIDOperations.updateTextContentByID(this._rootNodeID,n))}},unmountComponent:function(){r.unmountIDFromEnvironment(this._rootNodeID)}}),e.exports=s},function(e,t,n){"use strict";function o(e){return i(document.documentElement,e)}var r=n(158),i=n(96),a=n(98),l=n(99),s={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=l();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=l(),n=e.focusedElem,r=e.selectionRange;t!==n&&o(n)&&(s.hasSelectionCapabilities(n)&&s.setSelection(n,r),a(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&"INPUT"===e.nodeName){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=r.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,o=t.end;if("undefined"==typeof o&&(o=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(o,e.value.length);else if(document.selection&&"INPUT"===e.nodeName){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",o-n),i.select()}else r.setOffsets(e,t)}};e.exports=s},function(e,t,n){"use strict";var o=n(186),r={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=o(e);return e.replace(">"," "+r.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var n=t.getAttribute(r.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var i=o(e);return i===n}};e.exports=r},function(e,t,n){"use strict";var o=n(33),r=o({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});e.exports=r},function(e,t,n){"use strict";function o(e){function t(t,n,o,r,i){if(r=r||E,null==n[o]){var a=y[i];return t?new Error("Required "+a+" `"+o+"` was not specified in "+("`"+r+"`.")):null}return e(n,o,r,i)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function r(e){function t(t,n,o,r){var i=t[n],a=g(i);if(a!==e){var l=y[r],s=b(i);return new Error("Invalid "+l+" `"+n+"` of type `"+s+"` "+("supplied to `"+o+"`, expected `"+e+"`."))}return null}return o(t)}function i(){return o(x.thatReturns(null))}function a(e){function t(t,n,o,r){var i=t[n];if(!Array.isArray(i)){var a=y[r],l=g(i);return new Error("Invalid "+a+" `"+n+"` of type "+("`"+l+"` supplied to `"+o+"`, expected an array."))}for(var s=0;s<i.length;s++){var c=e(i,s,o,r);if(c instanceof Error)return c}return null}return o(t)}function l(){function e(e,t,n,o){if(!m.isValidElement(e[t])){var r=y[o];return new Error("Invalid "+r+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactElement."))}return null}return o(e)}function s(e){function t(t,n,o,r){if(!(t[n]instanceof e)){var i=y[r],a=e.name||E;return new Error("Invalid "+i+" `"+n+"` supplied to "+("`"+o+"`, expected instance of `"+a+"`."))}return null}return o(t)}function c(e){function t(t,n,o,r){for(var i=t[n],a=0;a<e.length;a++)if(i===e[a])return null;var l=y[r],s=JSON.stringify(e);return new Error("Invalid "+l+" `"+n+"` of value `"+i+"` "+("supplied to `"+o+"`, expected one of "+s+"."))}return o(t)}function u(e){function t(t,n,o,r){var i=t[n],a=g(i);if("object"!==a){var l=y[r];return new Error("Invalid "+l+" `"+n+"` of type "+("`"+a+"` supplied to `"+o+"`, expected an object."))}for(var s in i)if(i.hasOwnProperty(s)){var c=e(i,s,o,r);if(c instanceof Error)return c}return null}return o(t)}function p(e){function t(t,n,o,r){for(var i=0;i<e.length;i++){var a=e[i];if(null==a(t,n,o,r))return null}var l=y[r];return new Error("Invalid "+l+" `"+n+"` supplied to "+("`"+o+"`."))}return o(t)}function d(){function e(e,t,n,o){if(!h(e[t])){var r=y[o];return new Error("Invalid "+r+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return o(e)}function f(e){function t(t,n,o,r){var i=t[n],a=g(i);if("object"!==a){var l=y[r];return new Error("Invalid "+l+" `"+n+"` of type `"+a+"` "+("supplied to `"+o+"`, expected `object`."))}for(var s in e){var c=e[s];if(c){var u=c(i,s,o,r);if(u)return u}}return null}return o(t)}function h(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(h);if(null===e||m.isValidElement(e))return!0;e=v.extractIfFragment(e);for(var t in e)if(!h(e[t]))return!1;return!0;default:return!1}}function g(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function b(e){var t=g(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}var m=n(5),v=n(38),y=n(40),x=n(17),E="<<anonymous>>",w=l(),N=d(),k={array:r("array"),bool:r("boolean"),func:r("function"),number:r("number"),object:r("object"),string:r("string"),any:i(),arrayOf:a,element:w,instanceOf:s,node:N,objectOf:u,oneOf:c,oneOfType:p,shape:f};e.exports=k},function(e,t,n){"use strict";function o(){this.listenersToPut=[]}var r=n(13),i=n(23),a=n(3);a(o.prototype,{enqueuePutListener:function(e,t,n){this.listenersToPut.push({rootNodeID:e,propKey:t,propValue:n})},putListeners:function(){for(var e=0;e<this.listenersToPut.length;e++){var t=this.listenersToPut[e];i.putListener(t.rootNodeID,t.propKey,t.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),r.addPoolingTo(o),e.exports=o},function(e,t){"use strict";var n={injectCreateReactRootIndex:function(e){o.createReactRootIndex=e}},o={createReactRootIndex:null,injection:n};e.exports=o},function(e,t){"use strict";var n={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){n.currentScrollLeft=e.x,n.currentScrollTop=e.y}};e.exports=n},function(e,t,n){function o(e,t){return e&&t?e===t?!0:r(e)?!1:r(t)?o(e,t.parentNode):e.contains?e.contains(t):e.compareDocumentPosition?!!(16&e.compareDocumentPosition(t)):!1:!1}var r=n(200);e.exports=o},function(e,t,n){(function(t){"use strict";function o(e){if("production"!==t.env.NODE_ENV){var n=r.current;null!==n&&("production"!==t.env.NODE_ENV?c(n._warnedAboutRefsInRender,"%s is accessing getDOMNode or findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.",n.getName()||"A component"):null,n._warnedAboutRefsInRender=!0)}return null==e?null:s(e)?e:i.has(e)?a.getNodeFromInstance(e):("production"!==t.env.NODE_ENV?l(null==e.render||"function"!=typeof e.render,"Component (with keys: %s) contains `render` method but is not mounted in the DOM",Object.keys(e)):l(null==e.render||"function"!=typeof e.render),void("production"!==t.env.NODE_ENV?l(!1,"Element appears to be neither ReactComponent nor DOMNode (keys: %s)",Object.keys(e)):l(!1)))}var r=n(15),i=n(25),a=n(10),l=n(2),s=n(103),c=n(4);e.exports=o}).call(t,n(1))},function(e,t){"use strict";function n(e){try{e.focus()}catch(t){}}e.exports=n},function(e,t){function n(){try{return document.activeElement||document.body}catch(e){return document.body}}e.exports=n},function(e,t){"use strict";function n(e){var t=e&&(o&&e[o]||e[r]);return"function"==typeof t?t:void 0}var o="function"==typeof Symbol&&Symbol.iterator,r="@@iterator";e.exports=n},function(e,t,n){(function(t){function o(e){return"production"!==t.env.NODE_ENV?i(!!a,"Markup wrapping node not initialized"):i(!!a),d.hasOwnProperty(e)||(e="*"),l.hasOwnProperty(e)||("*"===e?a.innerHTML="<link />":a.innerHTML="<"+e+"></"+e+">",l[e]=!a.firstChild),l[e]?d[e]:null}var r=n(6),i=n(2),a=r.canUseDOM?document.createElement("div"):null,l={circle:!0,clipPath:!0,defs:!0,ellipse:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},s=[1,'<select multiple="true">',"</select>"],c=[1,"<table>","</table>"],u=[3,"<table><tbody><tr>","</tr></tbody></table>"],p=[1,"<svg>","</svg>"],d={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:s,option:s,caption:c,colgroup:c,tbody:c,tfoot:c,thead:c,td:u,th:u,circle:p,clipPath:p,defs:p,ellipse:p,g:p,line:p,linearGradient:p,path:p,polygon:p,polyline:p,radialGradient:p,rect:p,stop:p,text:p};e.exports=o}).call(t,n(1))},function(e,t,n){"use strict";function o(){return!i&&r.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var r=n(6),i=null;e.exports=o},function(e,t){function n(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}e.exports=n},function(e,t){"use strict";function n(e){return e&&("INPUT"===e.nodeName&&o[e.type]||"TEXTAREA"===e.nodeName)}var o={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};e.exports=n},function(e,t,n){ (function(t){"use strict";function o(e){return m[e]}function r(e,t){return e&&null!=e.key?a(e.key):t.toString(36)}function i(e){return(""+e).replace(v,o)}function a(e){return"$"+i(e)}function l(e,n,o,i,s){var p=typeof e;if(("undefined"===p||"boolean"===p)&&(e=null),null===e||"string"===p||"number"===p||c.isValidElement(e))return i(s,e,""===n?g+r(e,0):n,o),1;var m,v,x,E=0;if(Array.isArray(e))for(var w=0;w<e.length;w++)m=e[w],v=(""!==n?n+b:g)+r(m,w),x=o+E,E+=l(m,v,x,i,s);else{var N=d(e);if(N){var k,C=N.call(e);if(N!==e.entries)for(var _=0;!(k=C.next()).done;)m=k.value,v=(""!==n?n+b:g)+r(m,_++),x=o+E,E+=l(m,v,x,i,s);else for("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?h(y,"Using Maps as children is not yet fully supported. It is an experimental feature that might be removed. Convert it to a sequence / iterable of keyed ReactElements instead."):null,y=!0);!(k=C.next()).done;){var D=k.value;D&&(m=D[1],v=(""!==n?n+b:g)+a(D[0])+b+r(m,0),x=o+E,E+=l(m,v,x,i,s))}}else if("object"===p){"production"!==t.env.NODE_ENV?f(1!==e.nodeType,"traverseAllChildren(...): Encountered an invalid child; DOM elements are not valid children of React components."):f(1!==e.nodeType);var O=u.extract(e);for(var T in O)O.hasOwnProperty(T)&&(m=O[T],v=(""!==n?n+b:g)+a(T)+b+r(m,0),x=o+E,E+=l(m,v,x,i,s))}}return E}function s(e,t,n){return null==e?0:l(e,"",0,t,n)}var c=n(5),u=n(38),p=n(24),d=n(100),f=n(2),h=n(4),g=p.SEPARATOR,b=":",m={"=":"=0",".":"=1",":":"=2"},v=/[=.:]/g,y=!1;e.exports=s}).call(t,n(1))},function(e,t,n){t=e.exports=n(107)(),t.push([e.id,'/*! normalize.css v3.0.2 | MIT License | git.io/normalize */html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background-color:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{box-sizing:content-box;height:0}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace;font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-appearance:textfield;box-sizing:content-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-collapse:collapse;border-spacing:0}td,th{padding:0}/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */@media print{*,:after,:before{background:transparent!important;color:#000!important;box-shadow:none!important;text-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="#"]:after,a[href^="javascript:"]:after{content:""}blockquote,pre{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}img{max-width:100%!important}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}select{background:#fff!important}.navbar{display:none}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #ddd!important}}@font-face{font-family:Glyphicons Halflings;src:url('+n(69)+");src:url("+n(69)+"?#iefix) format('embedded-opentype'),url("+n(213)+") format('woff2'),url("+n(212)+") format('woff'),url("+n(214)+") format('truetype'),url("+n(215)+'#glyphicons_halflingsregular) format(\'svg\')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:Glyphicons Halflings;font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"*"}.glyphicon-plus:before{content:"+"}.glyphicon-eur:before,.glyphicon-euro:before{content:"\\20AC"}.glyphicon-minus:before{content:"\\2212"}.glyphicon-cloud:before{content:"\\2601"}.glyphicon-envelope:before{content:"\\2709"}.glyphicon-pencil:before{content:"\\270F"}.glyphicon-glass:before{content:"\\E001"}.glyphicon-music:before{content:"\\E002"}.glyphicon-search:before{content:"\\E003"}.glyphicon-heart:before{content:"\\E005"}.glyphicon-star:before{content:"\\E006"}.glyphicon-star-empty:before{content:"\\E007"}.glyphicon-user:before{content:"\\E008"}.glyphicon-film:before{content:"\\E009"}.glyphicon-th-large:before{content:"\\E010"}.glyphicon-th:before{content:"\\E011"}.glyphicon-th-list:before{content:"\\E012"}.glyphicon-ok:before{content:"\\E013"}.glyphicon-remove:before{content:"\\E014"}.glyphicon-zoom-in:before{content:"\\E015"}.glyphicon-zoom-out:before{content:"\\E016"}.glyphicon-off:before{content:"\\E017"}.glyphicon-signal:before{content:"\\E018"}.glyphicon-cog:before{content:"\\E019"}.glyphicon-trash:before{content:"\\E020"}.glyphicon-home:before{content:"\\E021"}.glyphicon-file:before{content:"\\E022"}.glyphicon-time:before{content:"\\E023"}.glyphicon-road:before{content:"\\E024"}.glyphicon-download-alt:before{content:"\\E025"}.glyphicon-download:before{content:"\\E026"}.glyphicon-upload:before{content:"\\E027"}.glyphicon-inbox:before{content:"\\E028"}.glyphicon-play-circle:before{content:"\\E029"}.glyphicon-repeat:before{content:"\\E030"}.glyphicon-refresh:before{content:"\\E031"}.glyphicon-list-alt:before{content:"\\E032"}.glyphicon-lock:before{content:"\\E033"}.glyphicon-flag:before{content:"\\E034"}.glyphicon-headphones:before{content:"\\E035"}.glyphicon-volume-off:before{content:"\\E036"}.glyphicon-volume-down:before{content:"\\E037"}.glyphicon-volume-up:before{content:"\\E038"}.glyphicon-qrcode:before{content:"\\E039"}.glyphicon-barcode:before{content:"\\E040"}.glyphicon-tag:before{content:"\\E041"}.glyphicon-tags:before{content:"\\E042"}.glyphicon-book:before{content:"\\E043"}.glyphicon-bookmark:before{content:"\\E044"}.glyphicon-print:before{content:"\\E045"}.glyphicon-camera:before{content:"\\E046"}.glyphicon-font:before{content:"\\E047"}.glyphicon-bold:before{content:"\\E048"}.glyphicon-italic:before{content:"\\E049"}.glyphicon-text-height:before{content:"\\E050"}.glyphicon-text-width:before{content:"\\E051"}.glyphicon-align-left:before{content:"\\E052"}.glyphicon-align-center:before{content:"\\E053"}.glyphicon-align-right:before{content:"\\E054"}.glyphicon-align-justify:before{content:"\\E055"}.glyphicon-list:before{content:"\\E056"}.glyphicon-indent-left:before{content:"\\E057"}.glyphicon-indent-right:before{content:"\\E058"}.glyphicon-facetime-video:before{content:"\\E059"}.glyphicon-picture:before{content:"\\E060"}.glyphicon-map-marker:before{content:"\\E062"}.glyphicon-adjust:before{content:"\\E063"}.glyphicon-tint:before{content:"\\E064"}.glyphicon-edit:before{content:"\\E065"}.glyphicon-share:before{content:"\\E066"}.glyphicon-check:before{content:"\\E067"}.glyphicon-move:before{content:"\\E068"}.glyphicon-step-backward:before{content:"\\E069"}.glyphicon-fast-backward:before{content:"\\E070"}.glyphicon-backward:before{content:"\\E071"}.glyphicon-play:before{content:"\\E072"}.glyphicon-pause:before{content:"\\E073"}.glyphicon-stop:before{content:"\\E074"}.glyphicon-forward:before{content:"\\E075"}.glyphicon-fast-forward:before{content:"\\E076"}.glyphicon-step-forward:before{content:"\\E077"}.glyphicon-eject:before{content:"\\E078"}.glyphicon-chevron-left:before{content:"\\E079"}.glyphicon-chevron-right:before{content:"\\E080"}.glyphicon-plus-sign:before{content:"\\E081"}.glyphicon-minus-sign:before{content:"\\E082"}.glyphicon-remove-sign:before{content:"\\E083"}.glyphicon-ok-sign:before{content:"\\E084"}.glyphicon-question-sign:before{content:"\\E085"}.glyphicon-info-sign:before{content:"\\E086"}.glyphicon-screenshot:before{content:"\\E087"}.glyphicon-remove-circle:before{content:"\\E088"}.glyphicon-ok-circle:before{content:"\\E089"}.glyphicon-ban-circle:before{content:"\\E090"}.glyphicon-arrow-left:before{content:"\\E091"}.glyphicon-arrow-right:before{content:"\\E092"}.glyphicon-arrow-up:before{content:"\\E093"}.glyphicon-arrow-down:before{content:"\\E094"}.glyphicon-share-alt:before{content:"\\E095"}.glyphicon-resize-full:before{content:"\\E096"}.glyphicon-resize-small:before{content:"\\E097"}.glyphicon-exclamation-sign:before{content:"\\E101"}.glyphicon-gift:before{content:"\\E102"}.glyphicon-leaf:before{content:"\\E103"}.glyphicon-fire:before{content:"\\E104"}.glyphicon-eye-open:before{content:"\\E105"}.glyphicon-eye-close:before{content:"\\E106"}.glyphicon-warning-sign:before{content:"\\E107"}.glyphicon-plane:before{content:"\\E108"}.glyphicon-calendar:before{content:"\\E109"}.glyphicon-random:before{content:"\\E110"}.glyphicon-comment:before{content:"\\E111"}.glyphicon-magnet:before{content:"\\E112"}.glyphicon-chevron-up:before{content:"\\E113"}.glyphicon-chevron-down:before{content:"\\E114"}.glyphicon-retweet:before{content:"\\E115"}.glyphicon-shopping-cart:before{content:"\\E116"}.glyphicon-folder-close:before{content:"\\E117"}.glyphicon-folder-open:before{content:"\\E118"}.glyphicon-resize-vertical:before{content:"\\E119"}.glyphicon-resize-horizontal:before{content:"\\E120"}.glyphicon-hdd:before{content:"\\E121"}.glyphicon-bullhorn:before{content:"\\E122"}.glyphicon-bell:before{content:"\\E123"}.glyphicon-certificate:before{content:"\\E124"}.glyphicon-thumbs-up:before{content:"\\E125"}.glyphicon-thumbs-down:before{content:"\\E126"}.glyphicon-hand-right:before{content:"\\E127"}.glyphicon-hand-left:before{content:"\\E128"}.glyphicon-hand-up:before{content:"\\E129"}.glyphicon-hand-down:before{content:"\\E130"}.glyphicon-circle-arrow-right:before{content:"\\E131"}.glyphicon-circle-arrow-left:before{content:"\\E132"}.glyphicon-circle-arrow-up:before{content:"\\E133"}.glyphicon-circle-arrow-down:before{content:"\\E134"}.glyphicon-globe:before{content:"\\E135"}.glyphicon-wrench:before{content:"\\E136"}.glyphicon-tasks:before{content:"\\E137"}.glyphicon-filter:before{content:"\\E138"}.glyphicon-briefcase:before{content:"\\E139"}.glyphicon-fullscreen:before{content:"\\E140"}.glyphicon-dashboard:before{content:"\\E141"}.glyphicon-paperclip:before{content:"\\E142"}.glyphicon-heart-empty:before{content:"\\E143"}.glyphicon-link:before{content:"\\E144"}.glyphicon-phone:before{content:"\\E145"}.glyphicon-pushpin:before{content:"\\E146"}.glyphicon-usd:before{content:"\\E148"}.glyphicon-gbp:before{content:"\\E149"}.glyphicon-sort:before{content:"\\E150"}.glyphicon-sort-by-alphabet:before{content:"\\E151"}.glyphicon-sort-by-alphabet-alt:before{content:"\\E152"}.glyphicon-sort-by-order:before{content:"\\E153"}.glyphicon-sort-by-order-alt:before{content:"\\E154"}.glyphicon-sort-by-attributes:before{content:"\\E155"}.glyphicon-sort-by-attributes-alt:before{content:"\\E156"}.glyphicon-unchecked:before{content:"\\E157"}.glyphicon-expand:before{content:"\\E158"}.glyphicon-collapse-down:before{content:"\\E159"}.glyphicon-collapse-up:before{content:"\\E160"}.glyphicon-log-in:before{content:"\\E161"}.glyphicon-flash:before{content:"\\E162"}.glyphicon-log-out:before{content:"\\E163"}.glyphicon-new-window:before{content:"\\E164"}.glyphicon-record:before{content:"\\E165"}.glyphicon-save:before{content:"\\E166"}.glyphicon-open:before{content:"\\E167"}.glyphicon-saved:before{content:"\\E168"}.glyphicon-import:before{content:"\\E169"}.glyphicon-export:before{content:"\\E170"}.glyphicon-send:before{content:"\\E171"}.glyphicon-floppy-disk:before{content:"\\E172"}.glyphicon-floppy-saved:before{content:"\\E173"}.glyphicon-floppy-remove:before{content:"\\E174"}.glyphicon-floppy-save:before{content:"\\E175"}.glyphicon-floppy-open:before{content:"\\E176"}.glyphicon-credit-card:before{content:"\\E177"}.glyphicon-transfer:before{content:"\\E178"}.glyphicon-cutlery:before{content:"\\E179"}.glyphicon-header:before{content:"\\E180"}.glyphicon-compressed:before{content:"\\E181"}.glyphicon-earphone:before{content:"\\E182"}.glyphicon-phone-alt:before{content:"\\E183"}.glyphicon-tower:before{content:"\\E184"}.glyphicon-stats:before{content:"\\E185"}.glyphicon-sd-video:before{content:"\\E186"}.glyphicon-hd-video:before{content:"\\E187"}.glyphicon-subtitles:before{content:"\\E188"}.glyphicon-sound-stereo:before{content:"\\E189"}.glyphicon-sound-dolby:before{content:"\\E190"}.glyphicon-sound-5-1:before{content:"\\E191"}.glyphicon-sound-6-1:before{content:"\\E192"}.glyphicon-sound-7-1:before{content:"\\E193"}.glyphicon-copyright-mark:before{content:"\\E194"}.glyphicon-registration-mark:before{content:"\\E195"}.glyphicon-cloud-download:before{content:"\\E197"}.glyphicon-cloud-upload:before{content:"\\E198"}.glyphicon-tree-conifer:before{content:"\\E199"}.glyphicon-tree-deciduous:before{content:"\\E200"}.glyphicon-cd:before{content:"\\E201"}.glyphicon-save-file:before{content:"\\E202"}.glyphicon-open-file:before{content:"\\E203"}.glyphicon-level-up:before{content:"\\E204"}.glyphicon-copy:before{content:"\\E205"}.glyphicon-paste:before{content:"\\E206"}.glyphicon-alert:before{content:"\\E209"}.glyphicon-equalizer:before{content:"\\E210"}.glyphicon-king:before{content:"\\E211"}.glyphicon-queen:before{content:"\\E212"}.glyphicon-pawn:before{content:"\\E213"}.glyphicon-bishop:before{content:"\\E214"}.glyphicon-knight:before{content:"\\E215"}.glyphicon-baby-formula:before{content:"\\E216"}.glyphicon-tent:before{content:"\\26FA"}.glyphicon-blackboard:before{content:"\\E218"}.glyphicon-bed:before{content:"\\E219"}.glyphicon-apple:before{content:"\\F8FF"}.glyphicon-erase:before{content:"\\E221"}.glyphicon-hourglass:before{content:"\\231B"}.glyphicon-lamp:before{content:"\\E223"}.glyphicon-duplicate:before{content:"\\E224"}.glyphicon-piggy-bank:before{content:"\\E225"}.glyphicon-scissors:before{content:"\\E226"}.glyphicon-bitcoin:before{content:"\\E227"}.glyphicon-yen:before{content:"\\A5"}.glyphicon-ruble:before{content:"\\20BD"}.glyphicon-scale:before{content:"\\E230"}.glyphicon-ice-lolly:before{content:"\\E231"}.glyphicon-ice-lolly-tasted:before{content:"\\E232"}.glyphicon-education:before{content:"\\E233"}.glyphicon-option-horizontal:before{content:"\\E234"}.glyphicon-option-vertical:before{content:"\\E235"}.glyphicon-menu-hamburger:before{content:"\\E236"}.glyphicon-modal-window:before{content:"\\E237"}.glyphicon-oil:before{content:"\\E238"}.glyphicon-grain:before{content:"\\E239"}.glyphicon-sunglasses:before{content:"\\E240"}.glyphicon-text-size:before{content:"\\E241"}.glyphicon-text-color:before{content:"\\E242"}.glyphicon-text-background:before{content:"\\E243"}.glyphicon-object-align-top:before{content:"\\E244"}.glyphicon-object-align-bottom:before{content:"\\E245"}.glyphicon-object-align-horizontal:before{content:"\\E246"}.glyphicon-object-align-left:before{content:"\\E247"}.glyphicon-object-align-vertical:before{content:"\\E248"}.glyphicon-object-align-right:before{content:"\\E249"}.glyphicon-triangle-right:before{content:"\\E250"}.glyphicon-triangle-left:before{content:"\\E251"}.glyphicon-triangle-bottom:before{content:"\\E252"}.glyphicon-triangle-top:before{content:"\\E253"}.glyphicon-console:before{content:"\\E254"}.glyphicon-superscript:before{content:"\\E255"}.glyphicon-subscript:before{content:"\\E256"}.glyphicon-menu-left:before{content:"\\E257"}.glyphicon-menu-right:before{content:"\\E258"}.glyphicon-menu-down:before{content:"\\E259"}.glyphicon-menu-up:before{content:"\\E260"}*,:after,:before{box-sizing:border-box}html{font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}button,input,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#337ab7;text-decoration:none}a:focus,a:hover{color:#23527c;text-decoration:underline}a:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.carousel-inner>.item>a>img,.carousel-inner>.item>img,.img-responsive,.thumbnail a>img,.thumbnail>img{display:block;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out;display:inline-block;max-width:100%;height:auto}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-weight:400;line-height:1;color:#777}.h1,.h2,.h3,h1,h2,h3{margin-top:20px;margin-bottom:10px}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small{font-size:65%}.h4,.h5,.h6,h4,h5,h6{margin-top:10px;margin-bottom:10px}.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-size:75%}.h1,h1{font-size:36px}.h2,h2{font-size:30px}.h3,h3{font-size:24px}.h4,h4{font-size:18px}.h5,h5{font-size:14px}.h6,h6{font-size:9pt}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:1pc;font-weight:300;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}.small,small{font-size:85%}.mark,mark{background-color:#fcf8e3;padding:.2em}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-nowrap{white-space:nowrap}.text-lowercase{text-transform:lowercase}.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-muted{color:#777}.text-primary{color:#337ab7}a.text-primary:hover{color:#286090}.text-success{color:#3c763d}a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#337ab7}a.bg-primary:hover{background-color:#286090}.bg-success{background-color:#dff0d8}a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ol,ul{margin-top:0;margin-bottom:10px}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}.list-inline,.list-unstyled{padding-left:0;list-style:none}.list-inline{margin-left:-5px}.list-inline>li{display:inline-block;padding-left:5px;padding-right:5px}dl{margin-top:0;margin-bottom:20px}dd,dt{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:768px){.dl-horizontal dt{float:left;width:10pc;clear:left;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[data-original-title],abbr[title]{cursor:help;border-bottom:1px dotted #777}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}blockquote ol:last-child,blockquote p:last-child,blockquote ul:last-child{margin-bottom:0}blockquote .small,blockquote footer,blockquote small{display:block;font-size:80%;line-height:1.42857143;color:#777}blockquote .small:before,blockquote footer:before,blockquote small:before{content:\'\\2014 \\A0\'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0;text-align:right}.blockquote-reverse .small:before,.blockquote-reverse footer:before,.blockquote-reverse small:before,blockquote.pull-right .small:before,blockquote.pull-right footer:before,blockquote.pull-right small:before{content:\'\'}.blockquote-reverse .small:after,.blockquote-reverse footer:after,.blockquote-reverse small:after,blockquote.pull-right .small:after,blockquote.pull-right footer:after,blockquote.pull-right small:after{content:\'\\A0 \\2014\'}address{margin-bottom:20px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,Courier New,monospace}code{color:#c7254e;background-color:#f9f2f4;border-radius:4px}code,kbd{padding:2px 4px;font-size:90%}kbd{color:#fff;background-color:#333;border-radius:3px;box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;font-weight:700;box-shadow:none}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}.row{margin-left:-15px;margin-right:-15px}.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12,.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12{position:relative;min-height:1px;padding-left:15px;padding-right:15px}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:auto}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:auto}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:auto}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:auto}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:auto}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:auto}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:auto}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:auto}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{background-color:transparent}caption{padding-top:8px;padding-bottom:8px;color:#777}caption,th{text-align:left}.table{width:100%;max-width:100%;margin-bottom:20px}.table>tbody>tr>td,.table>tbody>tr>th,.table>tfoot>tr>td,.table>tfoot>tr>th,.table>thead>tr>td,.table>thead>tr>th{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>td,.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>td,.table>thead:first-child>tr:first-child>th{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>tbody>tr>td,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>td,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>thead>tr>th{padding:5px}.table-bordered,.table-bordered>tbody>tr>td,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>td,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border:1px solid #ddd}.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border-bottom-width:2px}.table-striped>tbody>tr:nth-of-type(odd){background-color:#f9f9f9}.table-hover>tbody>tr:hover{background-color:#f5f5f5}table col[class*=col-]{position:static;float:none;display:table-column}table td[class*=col-],table th[class*=col-]{position:static;float:none;display:table-cell}.table>tbody>tr.active>td,.table>tbody>tr.active>th,.table>tbody>tr>td.active,.table>tbody>tr>th.active,.table>tfoot>tr.active>td,.table>tfoot>tr.active>th,.table>tfoot>tr>td.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>thead>tr.active>th,.table>thead>tr>td.active,.table>thead>tr>th.active{background-color:#f5f5f5}.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr.active:hover>th,.table-hover>tbody>tr:hover>.active,.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover{background-color:#e8e8e8}.table>tbody>tr.success>td,.table>tbody>tr.success>th,.table>tbody>tr>td.success,.table>tbody>tr>th.success,.table>tfoot>tr.success>td,.table>tfoot>tr.success>th,.table>tfoot>tr>td.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>thead>tr.success>th,.table>thead>tr>td.success,.table>thead>tr>th.success{background-color:#dff0d8}.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr.success:hover>th,.table-hover>tbody>tr:hover>.success,.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover{background-color:#d0e9c6}.table>tbody>tr.info>td,.table>tbody>tr.info>th,.table>tbody>tr>td.info,.table>tbody>tr>th.info,.table>tfoot>tr.info>td,.table>tfoot>tr.info>th,.table>tfoot>tr>td.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>thead>tr.info>th,.table>thead>tr>td.info,.table>thead>tr>th.info{background-color:#d9edf7}.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr.info:hover>th,.table-hover>tbody>tr:hover>.info,.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover{background-color:#c4e3f3}.table>tbody>tr.warning>td,.table>tbody>tr.warning>th,.table>tbody>tr>td.warning,.table>tbody>tr>th.warning,.table>tfoot>tr.warning>td,.table>tfoot>tr.warning>th,.table>tfoot>tr>td.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>thead>tr.warning>th,.table>thead>tr>td.warning,.table>thead>tr>th.warning{background-color:#fcf8e3}.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr.warning:hover>th,.table-hover>tbody>tr:hover>.warning,.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover{background-color:#faf2cc}.table>tbody>tr.danger>td,.table>tbody>tr.danger>th,.table>tbody>tr>td.danger,.table>tbody>tr>th.danger,.table>tfoot>tr.danger>td,.table>tfoot>tr.danger>th,.table>tfoot>tr>td.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>thead>tr.danger>th,.table>thead>tr>td.danger,.table>thead>tr>th.danger{background-color:#f2dede}.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr.danger:hover>th,.table-hover>tbody>tr:hover>.danger,.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover{background-color:#ebcccc}.table-responsive{overflow-x:auto;min-height:.01%}@media screen and (max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-y:hidden;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>td,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>thead>tr>th{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}}fieldset{margin:0;min-width:0}fieldset,legend{padding:0;border:0}legend{display:block;width:100%;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type=search]{box-sizing:border-box}input[type=checkbox],input[type=radio]{margin:4px 0 0;margin-top:1px\\9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=checkbox]:focus,input[type=file]:focus,input[type=radio]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{padding-top:7px}.form-control,output{display:block;font-size:14px;line-height:1.42857143;color:#555}.form-control{width:100%;height:34px;padding:6px 9pt;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#999;opacity:1}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee;opacity:1}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}@media screen and (-webkit-min-device-pixel-ratio:0){input[type=date],input[type=datetime-local],input[type=month],input[type=time]{line-height:34px}.input-group-sm input[type=date],.input-group-sm input[type=datetime-local],.input-group-sm input[type=month],.input-group-sm input[type=time],input[type=date].input-sm,input[type=datetime-local].input-sm,input[type=month].input-sm,input[type=time].input-sm{line-height:30px}.input-group-lg input[type=date],.input-group-lg input[type=datetime-local],.input-group-lg input[type=month],.input-group-lg input[type=time],input[type=date].input-lg,input[type=datetime-local].input-lg,input[type=month].input-lg,input[type=time].input-lg{line-height:46px}}.form-group{margin-bottom:15px}.checkbox,.radio{position:relative;display:block;margin-top:10px;margin-bottom:10px}.checkbox label,.radio label{min-height:20px;padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox],.radio input[type=radio],.radio-inline input[type=radio]{position:absolute;margin-left:-20px;margin-top:4px\\9}.checkbox+.checkbox,.radio+.radio{margin-top:-5px}.checkbox-inline,.radio-inline{display:inline-block;padding-left:20px;margin-bottom:0;vertical-align:middle;font-weight:400;cursor:pointer}.checkbox-inline+.checkbox-inline,.radio-inline+.radio-inline{margin-top:0;margin-left:10px}.checkbox-inline.disabled,.checkbox.disabled label,.radio-inline.disabled,.radio.disabled label,fieldset[disabled] .checkbox label,fieldset[disabled] .checkbox-inline,fieldset[disabled] .radio label,fieldset[disabled] .radio-inline,fieldset[disabled] input[type=checkbox],fieldset[disabled] input[type=radio],input[type=checkbox].disabled,input[type=checkbox][disabled],input[type=radio].disabled,input[type=radio][disabled]{cursor:not-allowed}.form-control-static{padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-control-static.input-sm{padding-left:0;padding-right:0}.input-sm{height:30px;padding:5px 10px;font-size:9pt;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}select[multiple].input-sm,textarea.input-sm{height:auto}.form-group-sm .form-control{height:30px;padding:5px 10px;font-size:9pt;line-height:1.5;border-radius:3px}select.form-group-sm .form-control{height:30px;line-height:30px}select[multiple].form-group-sm .form-control,textarea.form-group-sm .form-control{height:auto}.form-group-sm .form-control-static{height:30px;padding:5px 10px;font-size:9pt;line-height:1.5}.input-lg{height:46px;padding:10px 1pc;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-lg{height:46px;line-height:46px}select[multiple].input-lg,textarea.input-lg{height:auto}.form-group-lg .form-control{height:46px;padding:10px 1pc;font-size:18px;line-height:1.3333333;border-radius:6px}select.form-group-lg .form-control{height:46px;line-height:46px}select[multiple].form-group-lg .form-control,textarea.form-group-lg .form-control{height:auto}.form-group-lg .form-control-static{height:46px;padding:10px 1pc;font-size:18px;line-height:1.3333333}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:0;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center;pointer-events:none}.input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .checkbox,.has-success .checkbox-inline,.has-success .control-label,.has-success .help-block,.has-success .radio,.has-success .radio-inline,.has-success.checkbox label,.has-success.checkbox-inline label,.has-success.radio label,.has-success.radio-inline label{color:#3c763d}.has-success .form-control{border-color:#3c763d;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;border-color:#3c763d;background-color:#dff0d8}.has-success .form-control-feedback{color:#3c763d}.has-warning .checkbox,.has-warning .checkbox-inline,.has-warning .control-label,.has-warning .help-block,.has-warning .radio,.has-warning .radio-inline,.has-warning.checkbox label,.has-warning.checkbox-inline label,.has-warning.radio label,.has-warning.radio-inline label{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;border-color:#8a6d3b;background-color:#fcf8e3}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .checkbox,.has-error .checkbox-inline,.has-error .control-label,.has-error .help-block,.has-error .radio,.has-error .radio-inline,.has-error.checkbox label,.has-error.checkbox-inline label,.has-error.radio label,.has-error.radio-inline label{color:#a94442}.has-error .form-control{border-color:#a94442;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;border-color:#a94442;background-color:#f2dede}.has-error .form-control-feedback{color:#a94442}.has-feedback label~.form-control-feedback{top:25px}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-static{display:inline-block}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .form-control,.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .checkbox,.form-inline .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .checkbox label,.form-inline .radio label{padding-left:0}.form-inline .checkbox input[type=checkbox],.form-inline .radio input[type=radio]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .checkbox,.form-horizontal .checkbox-inline,.form-horizontal .radio,.form-horizontal .radio-inline{margin-top:0;margin-bottom:0;padding-top:7px}.form-horizontal .checkbox,.form-horizontal .radio{min-height:27px}.form-horizontal .form-group{margin-left:-15px;margin-right:-15px}@media (min-width:768px){.form-horizontal .control-label{text-align:right;margin-bottom:0;padding-top:7px}}.form-horizontal .has-feedback .form-control-feedback{right:15px}@media (min-width:768px){.form-horizontal .form-group-lg .control-label{padding-top:14.333333px}}@media (min-width:768px){.form-horizontal .form-group-sm .control-label{padding-top:6px}}.btn{display:inline-block;margin-bottom:0;font-weight:400;text-align:center;vertical-align:middle;touch-action:manipulation;cursor:pointer;background-image:none;border:1px solid transparent;white-space:nowrap;padding:6px 9pt;font-size:14px;line-height:1.42857143;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.btn.active.focus,.btn.active:focus,.btn.focus,.btn:active.focus,.btn:active:focus,.btn:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.focus,.btn:focus,.btn:hover{color:#333;text-decoration:none}.btn.active,.btn:active{outline:0;background-image:none;box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;pointer-events:none;opacity:.65;filter:alpha(opacity=65);box-shadow:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default.active,.btn-default.focus,.btn-default:active,.btn-default:focus,.btn-default:hover,.open>.dropdown-toggle.btn-default{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default.active,.btn-default:active,.open>.dropdown-toggle.btn-default{background-image:none}.btn-default.disabled,.btn-default.disabled.active,.btn-default.disabled.focus,.btn-default.disabled:active,.btn-default.disabled:focus,.btn-default.disabled:hover,.btn-default[disabled],.btn-default[disabled].active,.btn-default[disabled].focus,.btn-default[disabled]:active,.btn-default[disabled]:focus,.btn-default[disabled]:hover,fieldset[disabled] .btn-default,fieldset[disabled] .btn-default.active,fieldset[disabled] .btn-default.focus,fieldset[disabled] .btn-default:active,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:hover{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#337ab7;border-color:#2e6da4}.btn-primary.active,.btn-primary.focus,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.open>.dropdown-toggle.btn-primary{color:#fff;background-color:#286090;border-color:#204d74}.btn-primary.active,.btn-primary:active,.open>.dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled,.btn-primary.disabled.active,.btn-primary.disabled.focus,.btn-primary.disabled:active,.btn-primary.disabled:focus,.btn-primary.disabled:hover,.btn-primary[disabled],.btn-primary[disabled].active,.btn-primary[disabled].focus,.btn-primary[disabled]:active,.btn-primary[disabled]:focus,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary,fieldset[disabled] .btn-primary.active,fieldset[disabled] .btn-primary.focus,fieldset[disabled] .btn-primary:active,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:hover{background-color:#337ab7;border-color:#2e6da4}.btn-primary .badge{color:#337ab7;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success.active,.btn-success.focus,.btn-success:active,.btn-success:focus,.btn-success:hover,.open>.dropdown-toggle.btn-success{color:#fff;background-color:#449d44;border-color:#398439}.btn-success.active,.btn-success:active,.open>.dropdown-toggle.btn-success{background-image:none}.btn-success.disabled,.btn-success.disabled.active,.btn-success.disabled.focus,.btn-success.disabled:active,.btn-success.disabled:focus,.btn-success.disabled:hover,.btn-success[disabled],.btn-success[disabled].active,.btn-success[disabled].focus,.btn-success[disabled]:active,.btn-success[disabled]:focus,.btn-success[disabled]:hover,fieldset[disabled] .btn-success,fieldset[disabled] .btn-success.active,fieldset[disabled] .btn-success.focus,fieldset[disabled] .btn-success:active,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:hover{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info.active,.btn-info.focus,.btn-info:active,.btn-info:focus,.btn-info:hover,.open>.dropdown-toggle.btn-info{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info.active,.btn-info:active,.open>.dropdown-toggle.btn-info{background-image:none}.btn-info.disabled,.btn-info.disabled.active,.btn-info.disabled.focus,.btn-info.disabled:active,.btn-info.disabled:focus,.btn-info.disabled:hover,.btn-info[disabled],.btn-info[disabled].active,.btn-info[disabled].focus,.btn-info[disabled]:active,.btn-info[disabled]:focus,.btn-info[disabled]:hover,fieldset[disabled] .btn-info,fieldset[disabled] .btn-info.active,fieldset[disabled] .btn-info.focus,fieldset[disabled] .btn-info:active,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:hover{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning.active,.btn-warning.focus,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.open>.dropdown-toggle.btn-warning{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning.active,.btn-warning:active,.open>.dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled,.btn-warning.disabled.active,.btn-warning.disabled.focus,.btn-warning.disabled:active,.btn-warning.disabled:focus,.btn-warning.disabled:hover,.btn-warning[disabled],.btn-warning[disabled].active,.btn-warning[disabled].focus,.btn-warning[disabled]:active,.btn-warning[disabled]:focus,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning,fieldset[disabled] .btn-warning.active,fieldset[disabled] .btn-warning.focus,fieldset[disabled] .btn-warning:active,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:hover{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger.active,.btn-danger.focus,.btn-danger:active,.btn-danger:focus,.btn-danger:hover,.open>.dropdown-toggle.btn-danger{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger.active,.btn-danger:active,.open>.dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled,.btn-danger.disabled.active,.btn-danger.disabled.focus,.btn-danger.disabled:active,.btn-danger.disabled:focus,.btn-danger.disabled:hover,.btn-danger[disabled],.btn-danger[disabled].active,.btn-danger[disabled].focus,.btn-danger[disabled]:active,.btn-danger[disabled]:focus,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger,fieldset[disabled] .btn-danger.active,fieldset[disabled] .btn-danger.focus,fieldset[disabled] .btn-danger:active,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:hover{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{color:#337ab7;font-weight:400;border-radius:0}.btn-link,.btn-link.active,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;box-shadow:none}.btn-link,.btn-link:active,.btn-link:focus,.btn-link:hover{border-color:transparent}.btn-link:focus,.btn-link:hover{color:#23527c;text-decoration:underline;background-color:transparent}.btn-link[disabled]:focus,.btn-link[disabled]:hover,fieldset[disabled] .btn-link:focus,fieldset[disabled] .btn-link:hover{color:#777;text-decoration:none}.btn-group-lg>.btn,.btn-lg{padding:10px 1pc;font-size:18px;line-height:1.3333333;border-radius:6px}.btn-group-sm>.btn,.btn-sm{padding:5px 10px;font-size:9pt;line-height:1.5;border-radius:3px}.btn-group-xs>.btn,.btn-xs{padding:1px 5px;font-size:9pt;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none;visibility:hidden}.collapse.in{display:block;visibility:visible}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition-property:height,visibility;transition-property:height,visibility;-webkit-transition-duration:.35s;transition-duration:.35s;-webkit-transition-timing-function:ease;transition-timing-function:ease}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown,.dropup{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:10pc;padding:5px 0;margin:2px 0 0;list-style:none;font-size:14px;text-align:left;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;box-shadow:0 6px 9pt rgba(0,0,0,.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:focus,.dropdown-menu>li>a:hover{text-decoration:none;color:#262626;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:focus,.dropdown-menu>.active>a:hover{color:#fff;text-decoration:none;outline:0;background-color:#337ab7}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{color:#777}.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{text-decoration:none;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);cursor:not-allowed}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{left:auto;right:0}.dropdown-menu-left{left:0;right:auto}.dropdown-header{display:block;padding:3px 20px;font-size:9pt;line-height:1.42857143;color:#777;white-space:nowrap}.dropdown-backdrop{position:fixed;left:0;right:0;bottom:0;top:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:2px}@media (min-width:768px){.navbar-right .dropdown-menu{left:auto;right:0}.navbar-right .dropdown-menu-left{left:0;right:auto}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;float:left}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group-vertical>.btn:hover,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus,.btn-group>.btn:hover{z-index:2}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-top-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-top-right-radius:0}.btn-group>.btn-group:last-child:not(:first-child)>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-left:8px;padding-right:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-left:9pt;padding-right:9pt}.btn-group.open .dropdown-toggle{box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-bottom-left-radius:4px;border-top-right-radius:0;border-top-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{float:none;display:table-cell;width:1%}.btn-group-justified>.btn-group .btn{width:100%}.btn-group-justified>.btn-group .dropdown-menu{left:auto}[data-toggle=buttons]>.btn input[type=checkbox],[data-toggle=buttons]>.btn input[type=radio],[data-toggle=buttons]>.btn-group>.btn input[type=checkbox],[data-toggle=buttons]>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-left:0;padding-right:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 1pc;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:46px;line-height:46px}select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn,textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:9pt;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn,textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn{height:auto}.input-group .form-control,.input-group-addon,.input-group-btn{display:table-cell}.input-group .form-control:not(:first-child):not(:last-child),.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 9pt;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:9pt;border-radius:3px}.input-group-addon.input-lg{padding:10px 1pc;font-size:18px;border-radius:6px}.input-group-addon input[type=checkbox],.input-group-addon input[type=radio]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn-group:not(:last-child)>.btn,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-top-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:first-child>.btn-group:not(:first-child)>.btn,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle{border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{font-size:0;white-space:nowrap}.input-group-btn,.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:active,.input-group-btn>.btn:focus,.input-group-btn>.btn:hover{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{margin-left:-1px}.nav{margin-bottom:0;padding-left:0;list-style:none}.nav>li,.nav>li>a{position:relative;display:block}.nav>li>a{padding:10px 15px}.nav>li>a:focus,.nav>li>a:hover{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#777}.nav>li.disabled>a:focus,.nav>li.disabled>a:hover{color:#777;text-decoration:none;background-color:transparent;cursor:not-allowed}.nav .open>a,.nav .open>a:focus,.nav .open>a:hover{background-color:#eee;border-color:#337ab7}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:focus,.nav-tabs>li.active>a:hover{color:#555;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent;cursor:default}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{text-align:center;margin-bottom:5px}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:focus,.nav-pills>li.active>a:hover{color:#fff;background-color:#337ab7}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{text-align:center;margin-bottom:5px}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none;visibility:hidden}.tab-content>.active{display:block;visibility:visible}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}@media (min-width:768px){.navbar{border-radius:4px}}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{overflow-x:visible;padding-right:15px;padding-left:15px;border-top:1px solid transparent;box-shadow:inset 0 1px 0 hsla(0,0%,100%,.1);-webkit-overflow-scrolling:touch}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;box-shadow:none}.navbar-collapse.collapse{display:block!important;visibility:visible!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse{padding-left:0;padding-right:0}}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:340px}@media (max-device-width:480px) and (orientation:landscape){.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:200px}}.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-bottom,.navbar-fixed-top{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.navbar-fixed-bottom,.navbar-fixed-top{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;padding:15px;font-size:18px;line-height:20px;height:50px}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-brand>img{display:block}@media (min-width:768px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;margin-right:15px;padding:9px 10px;margin-top:8px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;box-shadow:none}.navbar-nav .open .dropdown-menu .dropdown-header,.navbar-nav .open .dropdown-menu>li>a{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:focus,.navbar-nav .open .dropdown-menu>li>a:hover{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}.navbar-form{margin:8px -15px;padding:10px 15px;border-top:1px solid transparent;border-bottom:1px solid transparent;box-shadow:inset 0 1px 0 hsla(0,0%,100%,.1),0 1px 0 hsla(0,0%,100%,.1)}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .form-control-static{display:inline-block}.navbar-form .input-group{display:inline-table;vertical-align:middle}.navbar-form .input-group .form-control,.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn{width:auto}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .checkbox,.navbar-form .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.navbar-form .checkbox label,.navbar-form .radio label{padding-left:0}.navbar-form .checkbox input[type=checkbox],.navbar-form .radio input[type=radio]{position:relative;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}.navbar-form .form-group:last-child{margin-bottom:0}}@media (min-width:768px){.navbar-form{width:auto;border:0;margin-left:0;margin-right:0;padding-top:0;padding-bottom:0;box-shadow:none}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{margin-bottom:0;border-top-right-radius:4px;border-top-left-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.navbar-text{float:left;margin-left:15px;margin-right:15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important;margin-right:-15px}.navbar-right~.navbar-right{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:focus,.navbar-default .navbar-brand:hover{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-nav>li>a,.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a:focus,.navbar-default .navbar-nav>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:focus,.navbar-default .navbar-nav>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:focus,.navbar-default .navbar-nav>.disabled>a:hover{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:focus,.navbar-default .navbar-toggle:hover{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:focus,.navbar-default .navbar-nav>.open>a:hover{background-color:#e7e7e7;color:#555}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-default .btn-link{color:#777}.navbar-default .btn-link:focus,.navbar-default .btn-link:hover{color:#333}.navbar-default .btn-link[disabled]:focus,.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:focus,fieldset[disabled] .navbar-default .btn-link:hover{color:#ccc}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#9d9d9d}.navbar-inverse .navbar-brand:focus,.navbar-inverse .navbar-brand:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>li>a,.navbar-inverse .navbar-text{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a:focus,.navbar-inverse .navbar-nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:focus,.navbar-inverse .navbar-nav>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:focus,.navbar-inverse .navbar-nav>.disabled>a:hover{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:focus,.navbar-inverse .navbar-toggle:hover{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:focus,.navbar-inverse .navbar-nav>.open>a:hover{background-color:#080808;color:#fff}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#9d9d9d}.navbar-inverse .navbar-link:hover{color:#fff}.navbar-inverse .btn-link{color:#9d9d9d}.navbar-inverse .btn-link:focus,.navbar-inverse .btn-link:hover{color:#fff}.navbar-inverse .btn-link[disabled]:focus,.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:focus,fieldset[disabled] .navbar-inverse .btn-link:hover{color:#444}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{content:"/\\A0";padding:0 5px;color:#ccc}.breadcrumb>.active{color:#777}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 9pt;line-height:1.42857143;text-decoration:none;color:#337ab7;background-color:#fff;border:1px solid #ddd;margin-left:-1px}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-bottom-right-radius:4px;border-top-right-radius:4px}.pagination>li>a:focus,.pagination>li>a:hover,.pagination>li>span:focus,.pagination>li>span:hover{color:#23527c;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>a:focus,.pagination>.active>a:hover,.pagination>.active>span,.pagination>.active>span:focus,.pagination>.active>span:hover{z-index:2;color:#fff;background-color:#337ab7;border-color:#337ab7;cursor:default}.pagination>.disabled>a,.pagination>.disabled>a:focus,.pagination>.disabled>a:hover,.pagination>.disabled>span,.pagination>.disabled>span:focus,.pagination>.disabled>span:hover{color:#777;background-color:#fff;border-color:#ddd;cursor:not-allowed}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 1pc;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-bottom-right-radius:6px;border-top-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:9pt}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-bottom-right-radius:3px;border-top-right-radius:3px}.pager{padding-left:0;margin:20px 0;list-style:none;text-align:center}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:focus,.pager li>a:hover{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:focus,.pager .disabled>a:hover,.pager .disabled>span{color:#777;background-color:#fff;cursor:not-allowed}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}a.label:focus,a.label:hover{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#777}.label-default[href]:focus,.label-default[href]:hover{background-color:#5e5e5e}.label-primary{background-color:#337ab7}.label-primary[href]:focus,.label-primary[href]:hover{background-color:#286090}.label-success{background-color:#5cb85c}.label-success[href]:focus,.label-success[href]:hover{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:focus,.label-info[href]:hover{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:focus,.label-warning[href]:hover{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:focus,.label-danger[href]:hover{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:9pt;font-weight:700;color:#fff;line-height:1;vertical-align:baseline;white-space:nowrap;text-align:center;background-color:#777;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-xs .badge{top:0;padding:1px 5px}a.badge:focus,a.badge:hover{color:#fff;text-decoration:none;cursor:pointer}.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#337ab7;background-color:#fff}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding:30px 15px;margin-bottom:30px;background-color:#eee}.jumbotron,.jumbotron .h1,.jumbotron h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.jumbotron>hr{border-top-color:#d5d5d5}.container .jumbotron,.container-fluid .jumbotron{border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding:3pc 0}.container .jumbotron,.container-fluid .jumbotron{padding-left:60px;padding-right:60px}.jumbotron .h1,.jumbotron h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:border .2s ease-in-out;transition:border .2s ease-in-out}.thumbnail a>img,.thumbnail>img{margin-left:auto;margin-right:auto}a.thumbnail.active,a.thumbnail:focus,a.thumbnail:hover{border-color:#337ab7}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable,.alert-dismissible{padding-right:35px}.alert-dismissable .close,.alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{background-color:#dff0d8;border-color:#d6e9c6;color:#3c763d}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{background-color:#d9edf7;border-color:#bce8f1;color:#31708f}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{background-color:#fcf8e3;border-color:#faebcc;color:#8a6d3b}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{background-color:#f2dede;border-color:#ebccd1;color:#a94442}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{0%{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{0%{background-position:40px 0}to{background-position:0 0}}.progress{overflow:hidden;height:20px;margin-bottom:20px;background-color:#f5f5f5;border-radius:4px;box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:9pt;line-height:20px;color:#fff;text-align:center;background-color:#337ab7;box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-bar-striped,.progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 25%,transparent 50%,hsla(0,0%,100%,.15) 50%,hsla(0,0%,100%,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 25%,transparent 50%,hsla(0,0%,100%,.15) 50%,hsla(0,0%,100%,.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress-bar.active,.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 25%,transparent 50%,hsla(0,0%,100%,.15) 50%,hsla(0,0%,100%,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 25%,transparent 50%,hsla(0,0%,100%,.15) 50%,hsla(0,0%,100%,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 25%,transparent 50%,hsla(0,0%,100%,.15) 50%,hsla(0,0%,100%,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 25%,transparent 50%,hsla(0,0%,100%,.15) 50%,hsla(0,0%,100%,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 25%,transparent 50%,hsla(0,0%,100%,.15) 50%,hsla(0,0%,100%,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 25%,transparent 50%,hsla(0,0%,100%,.15) 50%,hsla(0,0%,100%,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 25%,transparent 50%,hsla(0,0%,100%,.15) 50%,hsla(0,0%,100%,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 25%,transparent 50%,hsla(0,0%,100%,.15) 50%,hsla(0,0%,100%,.15) 75%,transparent 75%,transparent)}.media{margin-top:15px}.media:first-child{margin-top:0}.media,.media-body{zoom:1;overflow:hidden}.media-body{width:625pc}.media-object{display:block}.media-right,.media>.pull-right{padding-left:10px}.media-left,.media>.pull-left{padding-right:10px}.media-body,.media-left,.media-right{display:table-cell;vertical-align:top}.media-middle{vertical-align:middle}.media-bottom{vertical-align:bottom}.media-heading{margin-top:0;margin-bottom:5px}.media-list{padding-left:0;list-style:none}.list-group{margin-bottom:20px;padding-left:0}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}a.list-group-item{color:#555}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item:focus,a.list-group-item:hover{text-decoration:none;color:#555;background-color:#f5f5f5}.list-group-item.disabled,.list-group-item.disabled:focus,.list-group-item.disabled:hover{background-color:#eee;color:#777;cursor:not-allowed}.list-group-item.disabled .list-group-item-heading,.list-group-item.disabled:focus .list-group-item-heading,.list-group-item.disabled:hover .list-group-item-heading{color:inherit}.list-group-item.disabled .list-group-item-text,.list-group-item.disabled:focus .list-group-item-text,.list-group-item.disabled:hover .list-group-item-text{color:#777}.list-group-item.active,.list-group-item.active:focus,.list-group-item.active:hover{z-index:2;color:#fff;background-color:#337ab7;border-color:#337ab7}.list-group-item.active .list-group-item-heading,.list-group-item.active .list-group-item-heading>.small,.list-group-item.active .list-group-item-heading>small,.list-group-item.active:focus .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading>.small,.list-group-item.active:focus .list-group-item-heading>small,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading>.small,.list-group-item.active:hover .list-group-item-heading>small{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:focus .list-group-item-text,.list-group-item.active:hover .list-group-item-text{color:#c7ddef}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:focus,a.list-group-item-success:hover{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:focus,a.list-group-item-success.active:hover{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:focus,a.list-group-item-info:hover{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:focus,a.list-group-item-info.active:hover{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:focus,a.list-group-item-warning:hover{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:focus,a.list-group-item-warning.active:hover{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:focus,a.list-group-item-danger:hover{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:focus,a.list-group-item-danger.active:hover{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-right-radius:3px;border-top-left-radius:3px}.panel-heading>.dropdown .dropdown-toggle,.panel-title{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:1pc}.panel-title>.small,.panel-title>.small>a,.panel-title>a,.panel-title>small,.panel-title>small>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group,.panel>.panel-collapse>.list-group{margin-bottom:0}.panel>.list-group .list-group-item,.panel>.panel-collapse>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child,.panel>.panel-collapse>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-right-radius:3px;border-top-left-radius:3px}.panel>.list-group:last-child .list-group-item:last-child,.panel>.panel-collapse>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.list-group+.panel-footer,.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.panel>.panel-collapse>.table,.panel>.table,.panel>.table-responsive>.table{margin-bottom:0}.panel>.panel-collapse>.table caption,.panel>.table caption,.panel>.table-responsive>.table caption{padding-left:15px;padding-right:15px}.panel>.table-responsive:first-child>.table:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child,.panel>.table:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child,.panel>.table:first-child>thead:first-child>tr:first-child{border-top-right-radius:3px;border-top-left-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table-responsive:last-child>.table:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child,.panel>.table:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive,.panel>.table+.panel-body,.panel>.table-responsive+.panel-body{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child td,.panel>.table>tbody:first-child>tr:first-child th{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th{border-bottom:0}.panel>.table-responsive{border:0;margin-bottom:0}.panel-group{margin-bottom:20px}.panel-group .panel{margin-bottom:0;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse>.list-group,.panel-group .panel-heading+.panel-collapse>.panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ddd}.panel-default>.panel-heading .badge{color:#f5f5f5;background-color:#333}.panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#337ab7}.panel-primary>.panel-heading{color:#fff;background-color:#337ab7;border-color:#337ab7}.panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#337ab7}.panel-primary>.panel-heading .badge{color:#337ab7;background-color:#fff}.panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#337ab7}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;left:0;bottom:0;height:100%;width:100%;border:0}.embed-responsive.embed-responsive-16by9{padding-bottom:56.25%}.embed-responsive.embed-responsive-4by3{padding-bottom:75%}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:focus,.close:hover{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.modal,.modal-open{overflow:hidden}.modal{display:none;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transform:translate(0, -25%);-ms-transform:translate(0, -25%);transform:translate(0, -25%);-webkit-transition:-webkit-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate(0, 0);-ms-transform:translate(0, 0);transform:translate(0, 0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;box-shadow:0 3px 9px rgba(0,0,0,.5);background-clip:padding-box;outline:0}.modal-backdrop{position:absolute;top:0;right:0;left:0;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5;min-height:16.42857143px}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1070;display:block;visibility:visible;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:9pt;font-weight:400;line-height:1.4;opacity:0;filter:alpha(opacity=0)}.tooltip.in{opacity:.9;filter:alpha(opacity=90)}.tooltip.top{margin-top:-3px;padding:5px 0}.tooltip.right{margin-left:3px;padding:0 5px}.tooltip.bottom{margin-top:3px;padding:5px 0}.tooltip.left{margin-left:-3px;padding:0 5px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{right:5px}.tooltip.top-left .tooltip-arrow,.tooltip.top-right .tooltip-arrow{bottom:0;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{left:5px}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;right:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;left:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;font-weight:400;line-height:1.42857143;text-align:left;background-color:#fff;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;box-shadow:0 5px 10px rgba(0,0,0,.2);white-space:normal}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{margin:0;padding:8px 14px;font-size:14px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{border-width:10px;content:""}.popover.top>.arrow{left:50%;margin-left:-11px;border-bottom-width:0;border-top-color:#999;border-top-color:rgba(0,0,0,.25);bottom:-11px}.popover.top>.arrow:after{content:" ";bottom:1px;margin-left:-10px;border-bottom-width:0;border-top-color:#fff}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-left-width:0;border-right-color:#999;border-right-color:rgba(0,0,0,.25)}.popover.right>.arrow:after{content:" ";left:1px;bottom:-10px;border-left-width:0;border-right-color:#fff}.popover.bottom>.arrow{left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25);top:-11px}.popover.bottom>.arrow:after{content:" ";top:1px;margin-left:-10px;border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{content:" ";right:1px;border-right-width:0;border-left-color:#fff;bottom:-10px}.carousel,.carousel-inner{position:relative}.carousel-inner{overflow:hidden;width:100%}.carousel-inner>.item{display:none;position:relative;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>a>img,.carousel-inner>.item>img{line-height:1}@media (-webkit-transform-3d),all and (transform-3d){.carousel-inner>.item{-webkit-transition:-webkit-transform .6s ease-in-out;transition:transform .6s ease-in-out;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000;perspective:1000}.carousel-inner>.item.active.right,.carousel-inner>.item.next{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0);left:0}.carousel-inner>.item.active.left,.carousel-inner>.item.prev{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0);left:0}.carousel-inner>.item.active,.carousel-inner>.item.next.left,.carousel-inner>.item.prev.right{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);left:0}}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;left:0;bottom:0;width:15%;opacity:.5;filter:alpha(opacity=50);font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\'#80000000\',endColorstr=\'#00000000\',GradientType=1)}.carousel-control.right{left:auto;right:0;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\'#00000000\',endColorstr=\'#80000000\',GradientType=1)}.carousel-control:focus,.carousel-control:hover{outline:0;color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{position:absolute;top:50%;z-index:5;display:inline-block}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{left:50%;margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{right:50%;margin-right:-10px}.carousel-control .icon-next,.carousel-control .icon-prev{width:20px;height:20px;margin-top:-10px;line-height:1;font-family:serif}.carousel-control .icon-prev:before{content:\'\\2039\'}.carousel-control .icon-next:before{content:\'\\203A\'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;margin-left:-30%;padding-left:0;list-style:none;text-align:center}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;border:1px solid #fff;border-radius:10px;cursor:pointer;background-color:#000\\9;background-color:transparent}.carousel-indicators .active{margin:0;width:9pt;height:9pt;background-color:#fff}.carousel-caption{position:absolute;left:15%;right:15%;bottom:20px;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{width:30px;height:30px;margin-top:-15px;font-size:30px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{margin-left:-15px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{margin-right:-15px}.carousel-caption{left:20%;right:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.btn-group-vertical>.btn-group:after,.btn-group-vertical>.btn-group:before,.btn-toolbar:after,.btn-toolbar:before,.clearfix:after,.clearfix:before,.container-fluid:after,.container-fluid:before,.container:after,.container:before,.dl-horizontal dd:after,.dl-horizontal dd:before,.form-horizontal .form-group:after,.form-horizontal .form-group:before,.modal-footer:after,.modal-footer:before,.nav:after,.nav:before,.navbar-collapse:after,.navbar-collapse:before,.navbar-header:after,.navbar-header:before,.navbar:after,.navbar:before,.pager:after,.pager:before,.panel-body:after,.panel-body:before,.row:after,.row:before{content:" ";display:table}.btn-group-vertical>.btn-group:after,.btn-toolbar:after,.clearfix:after,.container-fluid:after,.container:after,.dl-horizontal dd:after,.form-horizontal .form-group:after,.modal-footer:after,.nav:after,.navbar-collapse:after,.navbar-header:after,.navbar:after,.pager:after,.panel-body:after,.row:after{clear:both}.center-block{display:block;margin-left:auto;margin-right:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-lg,.visible-lg-block,.visible-lg-inline,.visible-lg-inline-block,.visible-md,.visible-md-block,.visible-md-inline,.visible-md-inline-block,.visible-sm,.visible-sm-block,.visible-sm-inline,.visible-sm-inline-block,.visible-xs,.visible-xs-block,.visible-xs-inline,.visible-xs-inline-block{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table}tr.visible-xs{display:table-row!important}td.visible-xs,th.visible-xs{display:table-cell!important}}@media (max-width:767px){.visible-xs-block{display:block!important}}@media (max-width:767px){.visible-xs-inline{display:inline!important}}@media (max-width:767px){.visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table}tr.visible-sm{display:table-row!important}td.visible-sm,th.visible-sm{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-block{display:block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline{display:inline!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table}tr.visible-md{display:table-row!important}td.visible-md,th.visible-md{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-block{display:block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline{display:inline!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table}tr.visible-lg{display:table-row!important}td.visible-lg,th.visible-lg{display:table-cell!important}}@media (min-width:1200px){.visible-lg-block{display:block!important}}@media (min-width:1200px){.visible-lg-inline{display:inline!important}}@media (min-width:1200px){.visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table}tr.visible-print{display:table-row!important}td.visible-print,th.visible-print{display:table-cell!important}}.visible-print-block{display:none!important}@media print{.visible-print-block{display:block!important}}.visible-print-inline{display:none!important}@media print{.visible-print-inline{display:inline!important}}.visible-print-inline-block{display:none!important}@media print{.visible-print-inline-block{display:inline-block!important}}@media print{.hidden-print{display:none!important}}',""]); },function(e,t){e.exports=function(){var e=[];return e.toString=function(){for(var e=[],t=0;t<this.length;t++){var n=this[t];n[2]?e.push("@media "+n[2]+"{"+n[1]+"}"):e.push(n[1])}return e.join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var o={},r=0;r<this.length;r++){var i=this[r][0];"number"==typeof i&&(o[i]=!0)}for(r=0;r<t.length;r++){var a=t[r];"number"==typeof a[0]&&o[a[0]]||(n&&!a[2]?a[2]=n:n&&(a[2]="("+a[2]+") and ("+n+")"),e.push(a))}},e}},function(e,t,n){var o,r;/*!
* jQuery JavaScript Library v2.1.4 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2015-04-28T16:01Z */ !function(t,n){"object"==typeof e&&"object"==typeof e.exports?e.exports=t.document?n(t,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return n(e)}:n(t)}("undefined"!=typeof window?window:this,function(n,i){function a(e){var t="length"in e&&e.length,n=oe.type(e);return"function"===n||oe.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e}function l(e,t,n){if(oe.isFunction(t))return oe.grep(e,function(e,o){return!!t.call(e,o,e)!==n});if(t.nodeType)return oe.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(pe.test(t))return oe.filter(t,e,n);t=oe.filter(t,e)}return oe.grep(e,function(e){return X.call(t,e)>=0!==n})}function s(e,t){for(;(e=e[t])&&1!==e.nodeType;);return e}function c(e){var t=ve[e]={};return oe.each(e.match(me)||[],function(e,n){t[n]=!0}),t}function u(){te.removeEventListener("DOMContentLoaded",u,!1),n.removeEventListener("load",u,!1),oe.ready()}function p(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=oe.expando+p.uid++}function d(e,t,n){var o;if(void 0===n&&1===e.nodeType)if(o="data-"+t.replace(ke,"-$1").toLowerCase(),n=e.getAttribute(o),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:Ne.test(n)?oe.parseJSON(n):n}catch(r){}we.set(e,t,n)}else n=void 0;return n}function f(){return!0}function h(){return!1}function g(){try{return te.activeElement}catch(e){}}function b(e,t){return oe.nodeName(e,"table")&&oe.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function m(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function v(e){var t=Fe.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function y(e,t){for(var n=0,o=e.length;o>n;n++)Ee.set(e[n],"globalEval",!t||Ee.get(t[n],"globalEval"))}function x(e,t){var n,o,r,i,a,l,s,c;if(1===t.nodeType){if(Ee.hasData(e)&&(i=Ee.access(e),a=Ee.set(t,i),c=i.events)){delete a.handle,a.events={};for(r in c)for(n=0,o=c[r].length;o>n;n++)oe.event.add(t,r,c[r][n])}we.hasData(e)&&(l=we.access(e),s=oe.extend({},l),we.set(t,s))}}function E(e,t){var n=e.getElementsByTagName?e.getElementsByTagName(t||"*"):e.querySelectorAll?e.querySelectorAll(t||"*"):[];return void 0===t||t&&oe.nodeName(e,t)?oe.merge([e],n):n}function w(e,t){var n=t.nodeName.toLowerCase();"input"===n&&Oe.test(e.type)?t.checked=e.checked:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}function N(e,t){var o,r=oe(t.createElement(e)).appendTo(t.body),i=n.getDefaultComputedStyle&&(o=n.getDefaultComputedStyle(r[0]))?o.display:oe.css(r[0],"display");return r.detach(),i}function k(e){var t=te,n=ze[e];return n||(n=N(e,t),"none"!==n&&n||(He=(He||oe("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=He[0].contentDocument,t.write(),t.close(),n=N(e,t),He.detach()),ze[e]=n),n}function C(e,t,n){var o,r,i,a,l=e.style;return n=n||Ke(e),n&&(a=n.getPropertyValue(t)||n[t]),n&&(""!==a||oe.contains(e.ownerDocument,e)||(a=oe.style(e,t)),Ye.test(a)&&We.test(t)&&(o=l.width,r=l.minWidth,i=l.maxWidth,l.minWidth=l.maxWidth=l.width=a,a=n.width,l.width=o,l.minWidth=r,l.maxWidth=i)),void 0!==a?a+"":a}function _(e,t){return{get:function(){return e()?void delete this.get:(this.get=t).apply(this,arguments)}}}function D(e,t){if(t in e)return t;for(var n=t[0].toUpperCase()+t.slice(1),o=t,r=Ze.length;r--;)if(t=Ze[r]+n,t in e)return t;return o}function O(e,t,n){var o=Ge.exec(t);return o?Math.max(0,o[1]-(n||0))+(o[2]||"px"):t}function T(e,t,n,o,r){for(var i=n===(o?"border":"content")?4:"width"===t?1:0,a=0;4>i;i+=2)"margin"===n&&(a+=oe.css(e,n+_e[i],!0,r)),o?("content"===n&&(a-=oe.css(e,"padding"+_e[i],!0,r)),"margin"!==n&&(a-=oe.css(e,"border"+_e[i]+"Width",!0,r))):(a+=oe.css(e,"padding"+_e[i],!0,r),"padding"!==n&&(a+=oe.css(e,"border"+_e[i]+"Width",!0,r)));return a}function R(e,t,n){var o=!0,r="width"===t?e.offsetWidth:e.offsetHeight,i=Ke(e),a="border-box"===oe.css(e,"boxSizing",!1,i);if(0>=r||null==r){if(r=C(e,t,i),(0>r||null==r)&&(r=e.style[t]),Ye.test(r))return r;o=a&&(ee.boxSizingReliable()||r===e.style[t]),r=parseFloat(r)||0}return r+T(e,t,n||(a?"border":"content"),o,i)+"px"}function M(e,t){for(var n,o,r,i=[],a=0,l=e.length;l>a;a++)o=e[a],o.style&&(i[a]=Ee.get(o,"olddisplay"),n=o.style.display,t?(i[a]||"none"!==n||(o.style.display=""),""===o.style.display&&De(o)&&(i[a]=Ee.access(o,"olddisplay",k(o.nodeName)))):(r=De(o),"none"===n&&r||Ee.set(o,"olddisplay",r?n:oe.css(o,"display"))));for(a=0;l>a;a++)o=e[a],o.style&&(t&&"none"!==o.style.display&&""!==o.style.display||(o.style.display=t?i[a]||"":"none"));return e}function P(e,t,n,o,r){return new P.prototype.init(e,t,n,o,r)}function S(){return setTimeout(function(){et=void 0}),et=oe.now()}function I(e,t){var n,o=0,r={height:e};for(t=t?1:0;4>o;o+=2-t)n=_e[o],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function A(e,t,n){for(var o,r=(at[t]||[]).concat(at["*"]),i=0,a=r.length;a>i;i++)if(o=r[i].call(n,t,e))return o}function j(e,t,n){var o,r,i,a,l,s,c,u,p=this,d={},f=e.style,h=e.nodeType&&De(e),g=Ee.get(e,"fxshow");n.queue||(l=oe._queueHooks(e,"fx"),null==l.unqueued&&(l.unqueued=0,s=l.empty.fire,l.empty.fire=function(){l.unqueued||s()}),l.unqueued++,p.always(function(){p.always(function(){l.unqueued--,oe.queue(e,"fx").length||l.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[f.overflow,f.overflowX,f.overflowY],c=oe.css(e,"display"),u="none"===c?Ee.get(e,"olddisplay")||k(e.nodeName):c,"inline"===u&&"none"===oe.css(e,"float")&&(f.display="inline-block")),n.overflow&&(f.overflow="hidden",p.always(function(){f.overflow=n.overflow[0],f.overflowX=n.overflow[1],f.overflowY=n.overflow[2]}));for(o in t)if(r=t[o],nt.exec(r)){if(delete t[o],i=i||"toggle"===r,r===(h?"hide":"show")){if("show"!==r||!g||void 0===g[o])continue;h=!0}d[o]=g&&g[o]||oe.style(e,o)}else c=void 0;if(oe.isEmptyObject(d))"inline"===("none"===c?k(e.nodeName):c)&&(f.display=c);else{g?"hidden"in g&&(h=g.hidden):g=Ee.access(e,"fxshow",{}),i&&(g.hidden=!h),h?oe(e).show():p.done(function(){oe(e).hide()}),p.done(function(){var t;Ee.remove(e,"fxshow");for(t in d)oe.style(e,t,d[t])});for(o in d)a=A(h?g[o]:0,o,p),o in g||(g[o]=a.start,h&&(a.end=a.start,a.start="width"===o||"height"===o?1:0))}}function L(e,t){var n,o,r,i,a;for(n in e)if(o=oe.camelCase(n),r=t[o],i=e[n],oe.isArray(i)&&(r=i[1],i=e[n]=i[0]),n!==o&&(e[o]=i,delete e[n]),a=oe.cssHooks[o],a&&"expand"in a){i=a.expand(i),delete e[o];for(n in i)n in e||(e[n]=i[n],t[n]=r)}else t[o]=r}function V(e,t,n){var o,r,i=0,a=it.length,l=oe.Deferred().always(function(){delete s.elem}),s=function(){if(r)return!1;for(var t=et||S(),n=Math.max(0,c.startTime+c.duration-t),o=n/c.duration||0,i=1-o,a=0,s=c.tweens.length;s>a;a++)c.tweens[a].run(i);return l.notifyWith(e,[c,i,n]),1>i&&s?n:(l.resolveWith(e,[c]),!1)},c=l.promise({elem:e,props:oe.extend({},t),opts:oe.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:et||S(),duration:n.duration,tweens:[],createTween:function(t,n){var o=oe.Tween(e,c.opts,t,n,c.opts.specialEasing[t]||c.opts.easing);return c.tweens.push(o),o},stop:function(t){var n=0,o=t?c.tweens.length:0;if(r)return this;for(r=!0;o>n;n++)c.tweens[n].run(1);return t?l.resolveWith(e,[c,t]):l.rejectWith(e,[c,t]),this}}),u=c.props;for(L(u,c.opts.specialEasing);a>i;i++)if(o=it[i].call(c,e,u,c.opts))return o;return oe.map(u,A,c),oe.isFunction(c.opts.start)&&c.opts.start.call(e,c),oe.fx.timer(oe.extend(s,{elem:e,anim:c,queue:c.opts.queue})),c.progress(c.opts.progress).done(c.opts.done,c.opts.complete).fail(c.opts.fail).always(c.opts.always)}function U(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var o,r=0,i=t.toLowerCase().match(me)||[];if(oe.isFunction(n))for(;o=i[r++];)"+"===o[0]?(o=o.slice(1)||"*",(e[o]=e[o]||[]).unshift(n)):(e[o]=e[o]||[]).push(n)}}function F(e,t,n,o){function r(l){var s;return i[l]=!0,oe.each(e[l]||[],function(e,l){var c=l(t,n,o);return"string"!=typeof c||a||i[c]?a?!(s=c):void 0:(t.dataTypes.unshift(c),r(c),!1)}),s}var i={},a=e===Nt;return r(t.dataTypes[0])||!i["*"]&&r("*")}function B(e,t){var n,o,r=oe.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((r[n]?e:o||(o={}))[n]=t[n]);return o&&oe.extend(!0,e,o),e}function q(e,t,n){for(var o,r,i,a,l=e.contents,s=e.dataTypes;"*"===s[0];)s.shift(),void 0===o&&(o=e.mimeType||t.getResponseHeader("Content-Type"));if(o)for(r in l)if(l[r]&&l[r].test(o)){s.unshift(r);break}if(s[0]in n)i=s[0];else{for(r in n){if(!s[0]||e.converters[r+" "+s[0]]){i=r;break}a||(a=r)}i=i||a}return i?(i!==s[0]&&s.unshift(i),n[i]):void 0}function H(e,t,n,o){var r,i,a,l,s,c={},u=e.dataTypes.slice();if(u[1])for(a in e.converters)c[a.toLowerCase()]=e.converters[a];for(i=u.shift();i;)if(e.responseFields[i]&&(n[e.responseFields[i]]=t),!s&&o&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),s=i,i=u.shift())if("*"===i)i=s;else if("*"!==s&&s!==i){if(a=c[s+" "+i]||c["* "+i],!a)for(r in c)if(l=r.split(" "),l[1]===i&&(a=c[s+" "+l[0]]||c["* "+l[0]])){a===!0?a=c[r]:c[r]!==!0&&(i=l[0],u.unshift(l[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+s+" to "+i}}}return{state:"success",data:t}}function z(e,t,n,o){var r;if(oe.isArray(t))oe.each(t,function(t,r){n||Ot.test(e)?o(e,r):z(e+"["+("object"==typeof r?t:"")+"]",r,n,o)});else if(n||"object"!==oe.type(t))o(e,t);else for(r in t)z(e+"["+r+"]",t[r],n,o)}function W(e){return oe.isWindow(e)?e:9===e.nodeType&&e.defaultView}var Y=[],K=Y.slice,$=Y.concat,G=Y.push,X=Y.indexOf,Q={},J=Q.toString,Z=Q.hasOwnProperty,ee={},te=n.document,ne="2.1.4",oe=function(e,t){return new oe.fn.init(e,t)},re=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,ie=/^-ms-/,ae=/-([\da-z])/gi,le=function(e,t){return t.toUpperCase()};oe.fn=oe.prototype={jquery:ne,constructor:oe,selector:"",length:0,toArray:function(){return K.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:K.call(this)},pushStack:function(e){var t=oe.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return oe.each(this,e,t)},map:function(e){return this.pushStack(oe.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(K.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:G,sort:Y.sort,splice:Y.splice},oe.extend=oe.fn.extend=function(){var e,t,n,o,r,i,a=arguments[0]||{},l=1,s=arguments.length,c=!1;for("boolean"==typeof a&&(c=a,a=arguments[l]||{},l++),"object"==typeof a||oe.isFunction(a)||(a={}),l===s&&(a=this,l--);s>l;l++)if(null!=(e=arguments[l]))for(t in e)n=a[t],o=e[t],a!==o&&(c&&o&&(oe.isPlainObject(o)||(r=oe.isArray(o)))?(r?(r=!1,i=n&&oe.isArray(n)?n:[]):i=n&&oe.isPlainObject(n)?n:{},a[t]=oe.extend(c,i,o)):void 0!==o&&(a[t]=o));return a},oe.extend({expando:"jQuery"+(ne+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===oe.type(e)},isArray:Array.isArray,isWindow:function(e){return null!=e&&e===e.window},isNumeric:function(e){return!oe.isArray(e)&&e-parseFloat(e)+1>=0},isPlainObject:function(e){return"object"!==oe.type(e)||e.nodeType||oe.isWindow(e)?!1:e.constructor&&!Z.call(e.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?Q[J.call(e)]||"object":typeof e},globalEval:function(e){var t,n=eval;e=oe.trim(e),e&&(1===e.indexOf("use strict")?(t=te.createElement("script"),t.text=e,te.head.appendChild(t).parentNode.removeChild(t)):n(e))},camelCase:function(e){return e.replace(ie,"ms-").replace(ae,le)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var o,r=0,i=e.length,l=a(e);if(n){if(l)for(;i>r&&(o=t.apply(e[r],n),o!==!1);r++);else for(r in e)if(o=t.apply(e[r],n),o===!1)break}else if(l)for(;i>r&&(o=t.call(e[r],r,e[r]),o!==!1);r++);else for(r in e)if(o=t.call(e[r],r,e[r]),o===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(re,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(a(Object(e))?oe.merge(n,"string"==typeof e?[e]:e):G.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:X.call(t,e,n)},merge:function(e,t){for(var n=+t.length,o=0,r=e.length;n>o;o++)e[r++]=t[o];return e.length=r,e},grep:function(e,t,n){for(var o,r=[],i=0,a=e.length,l=!n;a>i;i++)o=!t(e[i],i),o!==l&&r.push(e[i]);return r},map:function(e,t,n){var o,r=0,i=e.length,l=a(e),s=[];if(l)for(;i>r;r++)o=t(e[r],r,n),null!=o&&s.push(o);else for(r in e)o=t(e[r],r,n),null!=o&&s.push(o);return $.apply([],s)},guid:1,proxy:function(e,t){var n,o,r;return"string"==typeof t&&(n=e[t],t=e,e=n),oe.isFunction(e)?(o=K.call(arguments,2),r=function(){return e.apply(t||this,o.concat(K.call(arguments)))},r.guid=e.guid=e.guid||oe.guid++,r):void 0},now:Date.now,support:ee}),oe.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){Q["[object "+t+"]"]=t.toLowerCase()});var se=/*! * Sizzle CSS Selector Engine v2.2.0-pre * http://sizzlejs.com/ * * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-16 */ function(e){function t(e,t,n,o){var r,i,a,l,s,c,p,f,h,g;if((t?t.ownerDocument||t:F)!==P&&M(t),t=t||P,n=n||[],l=t.nodeType,"string"!=typeof e||!e||1!==l&&9!==l&&11!==l)return n;if(!o&&I){if(11!==l&&(r=ve.exec(e)))if(a=r[1]){if(9===l){if(i=t.getElementById(a),!i||!i.parentNode)return n;if(i.id===a)return n.push(i),n}else if(t.ownerDocument&&(i=t.ownerDocument.getElementById(a))&&V(t,i)&&i.id===a)return n.push(i),n}else{if(r[2])return J.apply(n,t.getElementsByTagName(e)),n;if((a=r[3])&&E.getElementsByClassName)return J.apply(n,t.getElementsByClassName(a)),n}if(E.qsa&&(!A||!A.test(e))){if(f=p=U,h=t,g=1!==l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){for(c=C(e),(p=t.getAttribute("id"))?f=p.replace(xe,"\\$&"):t.setAttribute("id",f),f="[id='"+f+"'] ",s=c.length;s--;)c[s]=f+d(c[s]);h=ye.test(e)&&u(t.parentNode)||t,g=c.join(",")}if(g)try{return J.apply(n,h.querySelectorAll(g)),n}catch(b){}finally{p||t.removeAttribute("id")}}}return D(e.replace(se,"$1"),t,n,o)}function n(){function e(n,o){return t.push(n+" ")>w.cacheLength&&delete e[t.shift()],e[n+" "]=o}var t=[];return e}function o(e){return e[U]=!0,e}function r(e){var t=P.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function i(e,t){for(var n=e.split("|"),o=e.length;o--;)w.attrHandle[n[o]]=t}function a(e,t){var n=t&&e,o=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||K)-(~e.sourceIndex||K);if(o)return o;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function l(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function s(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function c(e){return o(function(t){return t=+t,o(function(n,o){for(var r,i=e([],n.length,t),a=i.length;a--;)n[r=i[a]]&&(n[r]=!(o[r]=n[r]))})})}function u(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function p(){}function d(e){for(var t=0,n=e.length,o="";n>t;t++)o+=e[t].value;return o}function f(e,t,n){var o=t.dir,r=n&&"parentNode"===o,i=q++;return t.first?function(t,n,i){for(;t=t[o];)if(1===t.nodeType||r)return e(t,n,i)}:function(t,n,a){var l,s,c=[B,i];if(a){for(;t=t[o];)if((1===t.nodeType||r)&&e(t,n,a))return!0}else for(;t=t[o];)if(1===t.nodeType||r){if(s=t[U]||(t[U]={}),(l=s[o])&&l[0]===B&&l[1]===i)return c[2]=l[2];if(s[o]=c,c[2]=e(t,n,a))return!0}}}function h(e){return e.length>1?function(t,n,o){for(var r=e.length;r--;)if(!e[r](t,n,o))return!1;return!0}:e[0]}function g(e,n,o){for(var r=0,i=n.length;i>r;r++)t(e,n[r],o);return o}function b(e,t,n,o,r){for(var i,a=[],l=0,s=e.length,c=null!=t;s>l;l++)(i=e[l])&&(!n||n(i,o,r))&&(a.push(i),c&&t.push(l));return a}function m(e,t,n,r,i,a){return r&&!r[U]&&(r=m(r)),i&&!i[U]&&(i=m(i,a)),o(function(o,a,l,s){var c,u,p,d=[],f=[],h=a.length,m=o||g(t||"*",l.nodeType?[l]:l,[]),v=!e||!o&&t?m:b(m,d,e,l,s),y=n?i||(o?e:h||r)?[]:a:v;if(n&&n(v,y,l,s),r)for(c=b(y,f),r(c,[],l,s),u=c.length;u--;)(p=c[u])&&(y[f[u]]=!(v[f[u]]=p));if(o){if(i||e){if(i){for(c=[],u=y.length;u--;)(p=y[u])&&c.push(v[u]=p);i(null,y=[],c,s)}for(u=y.length;u--;)(p=y[u])&&(c=i?ee(o,p):d[u])>-1&&(o[c]=!(a[c]=p))}}else y=b(y===a?y.splice(h,y.length):y),i?i(null,a,y,s):J.apply(a,y)})}function v(e){for(var t,n,o,r=e.length,i=w.relative[e[0].type],a=i||w.relative[" "],l=i?1:0,s=f(function(e){return e===t},a,!0),c=f(function(e){return ee(t,e)>-1},a,!0),u=[function(e,n,o){var r=!i&&(o||n!==O)||((t=n).nodeType?s(e,n,o):c(e,n,o));return t=null,r}];r>l;l++)if(n=w.relative[e[l].type])u=[f(h(u),n)];else{if(n=w.filter[e[l].type].apply(null,e[l].matches),n[U]){for(o=++l;r>o&&!w.relative[e[o].type];o++);return m(l>1&&h(u),l>1&&d(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(se,"$1"),n,o>l&&v(e.slice(l,o)),r>o&&v(e=e.slice(o)),r>o&&d(e))}u.push(n)}return h(u)}function y(e,n){var r=n.length>0,i=e.length>0,a=function(o,a,l,s,c){var u,p,d,f=0,h="0",g=o&&[],m=[],v=O,y=o||i&&w.find.TAG("*",c),x=B+=null==v?1:Math.random()||.1,E=y.length;for(c&&(O=a!==P&&a);h!==E&&null!=(u=y[h]);h++){if(i&&u){for(p=0;d=e[p++];)if(d(u,a,l)){s.push(u);break}c&&(B=x)}r&&((u=!d&&u)&&f--,o&&g.push(u))}if(f+=h,r&&h!==f){for(p=0;d=n[p++];)d(g,m,a,l);if(o){if(f>0)for(;h--;)g[h]||m[h]||(m[h]=X.call(s));m=b(m)}J.apply(s,m),c&&!o&&m.length>0&&f+n.length>1&&t.uniqueSort(s)}return c&&(B=x,O=v),g};return r?o(a):a}var x,E,w,N,k,C,_,D,O,T,R,M,P,S,I,A,j,L,V,U="sizzle"+1*new Date,F=e.document,B=0,q=0,H=n(),z=n(),W=n(),Y=function(e,t){return e===t&&(R=!0),0},K=1<<31,$={}.hasOwnProperty,G=[],X=G.pop,Q=G.push,J=G.push,Z=G.slice,ee=function(e,t){for(var n=0,o=e.length;o>n;n++)if(e[n]===t)return n;return-1},te="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",ne="[\\x20\\t\\r\\n\\f]",oe="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",re=oe.replace("w","w#"),ie="\\["+ne+"*("+oe+")(?:"+ne+"*([*^$|!~]?=)"+ne+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+re+"))|)"+ne+"*\\]",ae=":("+oe+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ie+")*)|.*)\\)|)",le=new RegExp(ne+"+","g"),se=new RegExp("^"+ne+"+|((?:^|[^\\\\])(?:\\\\.)*)"+ne+"+$","g"),ce=new RegExp("^"+ne+"*,"+ne+"*"),ue=new RegExp("^"+ne+"*([>+~]|"+ne+")"+ne+"*"),pe=new RegExp("="+ne+"*([^\\]'\"]*?)"+ne+"*\\]","g"),de=new RegExp(ae),fe=new RegExp("^"+re+"$"),he={ID:new RegExp("^#("+oe+")"),CLASS:new RegExp("^\\.("+oe+")"),TAG:new RegExp("^("+oe.replace("w","w*")+")"),ATTR:new RegExp("^"+ie),PSEUDO:new RegExp("^"+ae),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ne+"*(even|odd|(([+-]|)(\\d*)n|)"+ne+"*(?:([+-]|)"+ne+"*(\\d+)|))"+ne+"*\\)|)","i"),bool:new RegExp("^(?:"+te+")$","i"),needsContext:new RegExp("^"+ne+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ne+"*((?:-\\d)?\\d*)"+ne+"*\\)|)(?=[^-]|$)","i")},ge=/^(?:input|select|textarea|button)$/i,be=/^h\d$/i,me=/^[^{]+\{\s*\[native \w/,ve=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ye=/[+~]/,xe=/'|\\/g,Ee=new RegExp("\\\\([\\da-f]{1,6}"+ne+"?|("+ne+")|.)","ig"),we=function(e,t,n){var o="0x"+t-65536;return o!==o||n?t:0>o?String.fromCharCode(o+65536):String.fromCharCode(o>>10|55296,1023&o|56320)},Ne=function(){M()};try{J.apply(G=Z.call(F.childNodes),F.childNodes),G[F.childNodes.length].nodeType}catch(ke){J={apply:G.length?function(e,t){Q.apply(e,Z.call(t))}:function(e,t){for(var n=e.length,o=0;e[n++]=t[o++];);e.length=n-1}}}E=t.support={},k=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},M=t.setDocument=function(e){var t,n,o=e?e.ownerDocument||e:F;return o!==P&&9===o.nodeType&&o.documentElement?(P=o,S=o.documentElement,n=o.defaultView,n&&n!==n.top&&(n.addEventListener?n.addEventListener("unload",Ne,!1):n.attachEvent&&n.attachEvent("onunload",Ne)),I=!k(o),E.attributes=r(function(e){return e.className="i",!e.getAttribute("className")}),E.getElementsByTagName=r(function(e){return e.appendChild(o.createComment("")),!e.getElementsByTagName("*").length}),E.getElementsByClassName=me.test(o.getElementsByClassName),E.getById=r(function(e){return S.appendChild(e).id=U,!o.getElementsByName||!o.getElementsByName(U).length}),E.getById?(w.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&I){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},w.filter.ID=function(e){var t=e.replace(Ee,we);return function(e){return e.getAttribute("id")===t}}):(delete w.find.ID,w.filter.ID=function(e){var t=e.replace(Ee,we);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}}),w.find.TAG=E.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):E.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,o=[],r=0,i=t.getElementsByTagName(e);if("*"===e){for(;n=i[r++];)1===n.nodeType&&o.push(n);return o}return i},w.find.CLASS=E.getElementsByClassName&&function(e,t){return I?t.getElementsByClassName(e):void 0},j=[],A=[],(E.qsa=me.test(o.querySelectorAll))&&(r(function(e){S.appendChild(e).innerHTML="<a id='"+U+"'></a><select id='"+U+"-\f]' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&A.push("[*^$]="+ne+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||A.push("\\["+ne+"*(?:value|"+te+")"),e.querySelectorAll("[id~="+U+"-]").length||A.push("~="),e.querySelectorAll(":checked").length||A.push(":checked"),e.querySelectorAll("a#"+U+"+*").length||A.push(".#.+[+~]")}),r(function(e){var t=o.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&A.push("name"+ne+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||A.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),A.push(",.*:")})),(E.matchesSelector=me.test(L=S.matches||S.webkitMatchesSelector||S.mozMatchesSelector||S.oMatchesSelector||S.msMatchesSelector))&&r(function(e){E.disconnectedMatch=L.call(e,"div"),L.call(e,"[s!='']:x"),j.push("!=",ae)}),A=A.length&&new RegExp(A.join("|")),j=j.length&&new RegExp(j.join("|")),t=me.test(S.compareDocumentPosition),V=t||me.test(S.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,o=t&&t.parentNode;return e===o||!(!o||1!==o.nodeType||!(n.contains?n.contains(o):e.compareDocumentPosition&&16&e.compareDocumentPosition(o)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},Y=t?function(e,t){if(e===t)return R=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n?n:(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&n||!E.sortDetached&&t.compareDocumentPosition(e)===n?e===o||e.ownerDocument===F&&V(F,e)?-1:t===o||t.ownerDocument===F&&V(F,t)?1:T?ee(T,e)-ee(T,t):0:4&n?-1:1)}:function(e,t){if(e===t)return R=!0,0;var n,r=0,i=e.parentNode,l=t.parentNode,s=[e],c=[t];if(!i||!l)return e===o?-1:t===o?1:i?-1:l?1:T?ee(T,e)-ee(T,t):0;if(i===l)return a(e,t);for(n=e;n=n.parentNode;)s.unshift(n);for(n=t;n=n.parentNode;)c.unshift(n);for(;s[r]===c[r];)r++;return r?a(s[r],c[r]):s[r]===F?-1:c[r]===F?1:0},o):P},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==P&&M(e),n=n.replace(pe,"='$1']"),E.matchesSelector&&I&&(!j||!j.test(n))&&(!A||!A.test(n)))try{var o=L.call(e,n);if(o||E.disconnectedMatch||e.document&&11!==e.document.nodeType)return o}catch(r){}return t(n,P,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==P&&M(e),V(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==P&&M(e);var n=w.attrHandle[t.toLowerCase()],o=n&&$.call(w.attrHandle,t.toLowerCase())?n(e,t,!I):void 0;return void 0!==o?o:E.attributes||!I?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],o=0,r=0;if(R=!E.detectDuplicates,T=!E.sortStable&&e.slice(0),e.sort(Y),R){for(;t=e[r++];)t===e[r]&&(o=n.push(r));for(;o--;)e.splice(n[o],1)}return T=null,e},N=t.getText=function(e){var t,n="",o=0,r=e.nodeType;if(r){if(1===r||9===r||11===r){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=N(e)}else if(3===r||4===r)return e.nodeValue}else for(;t=e[o++];)n+=N(t);return n},w=t.selectors={cacheLength:50,createPseudo:o,match:he,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Ee,we),e[3]=(e[3]||e[4]||e[5]||"").replace(Ee,we),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return he.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&de.test(n)&&(t=C(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Ee,we).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=H[e+" "];return t||(t=new RegExp("(^|"+ne+")"+e+"("+ne+"|$)"))&&H(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,n,o){return function(r){var i=t.attr(r,e);return null==i?"!="===n:n?(i+="","="===n?i===o:"!="===n?i!==o:"^="===n?o&&0===i.indexOf(o):"*="===n?o&&i.indexOf(o)>-1:"$="===n?o&&i.slice(-o.length)===o:"~="===n?(" "+i.replace(le," ")+" ").indexOf(o)>-1:"|="===n?i===o||i.slice(0,o.length+1)===o+"-":!1):!0}},CHILD:function(e,t,n,o,r){var i="nth"!==e.slice(0,3),a="last"!==e.slice(-4),l="of-type"===t;return 1===o&&0===r?function(e){return!!e.parentNode}:function(t,n,s){var c,u,p,d,f,h,g=i!==a?"nextSibling":"previousSibling",b=t.parentNode,m=l&&t.nodeName.toLowerCase(),v=!s&&!l;if(b){if(i){for(;g;){for(p=t;p=p[g];)if(l?p.nodeName.toLowerCase()===m:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?b.firstChild:b.lastChild],a&&v){for(u=b[U]||(b[U]={}),c=u[e]||[],f=c[0]===B&&c[1],d=c[0]===B&&c[2],p=f&&b.childNodes[f];p=++f&&p&&p[g]||(d=f=0)||h.pop();)if(1===p.nodeType&&++d&&p===t){u[e]=[B,f,d];break}}else if(v&&(c=(t[U]||(t[U]={}))[e])&&c[0]===B)d=c[1];else for(;(p=++f&&p&&p[g]||(d=f=0)||h.pop())&&((l?p.nodeName.toLowerCase()!==m:1!==p.nodeType)||!++d||(v&&((p[U]||(p[U]={}))[e]=[B,d]),p!==t)););return d-=r,d===o||d%o===0&&d/o>=0}}},PSEUDO:function(e,n){var r,i=w.pseudos[e]||w.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return i[U]?i(n):i.length>1?(r=[e,e,"",n],w.setFilters.hasOwnProperty(e.toLowerCase())?o(function(e,t){for(var o,r=i(e,n),a=r.length;a--;)o=ee(e,r[a]),e[o]=!(t[o]=r[a])}):function(e){return i(e,0,r)}):i}},pseudos:{not:o(function(e){var t=[],n=[],r=_(e.replace(se,"$1"));return r[U]?o(function(e,t,n,o){for(var i,a=r(e,null,o,[]),l=e.length;l--;)(i=a[l])&&(e[l]=!(t[l]=i))}):function(e,o,i){return t[0]=e,r(t,null,i,n),t[0]=null,!n.pop()}}),has:o(function(e){return function(n){return t(e,n).length>0}}),contains:o(function(e){return e=e.replace(Ee,we),function(t){return(t.textContent||t.innerText||N(t)).indexOf(e)>-1}}),lang:o(function(e){return fe.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(Ee,we).toLowerCase(),function(t){var n;do if(n=I?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===S},focus:function(e){return e===P.activeElement&&(!P.hasFocus||P.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!w.pseudos.empty(e)},header:function(e){return be.test(e.nodeName)},input:function(e){return ge.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:c(function(){return[0]}),last:c(function(e,t){return[t-1]}),eq:c(function(e,t,n){return[0>n?n+t:n]}),even:c(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:c(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:c(function(e,t,n){for(var o=0>n?n+t:n;--o>=0;)e.push(o);return e}),gt:c(function(e,t,n){for(var o=0>n?n+t:n;++o<t;)e.push(o);return e})}},w.pseudos.nth=w.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})w.pseudos[x]=l(x);for(x in{submit:!0,reset:!0})w.pseudos[x]=s(x);return p.prototype=w.filters=w.pseudos,w.setFilters=new p,C=t.tokenize=function(e,n){var o,r,i,a,l,s,c,u=z[e+" "];if(u)return n?0:u.slice(0);for(l=e,s=[],c=w.preFilter;l;){(!o||(r=ce.exec(l)))&&(r&&(l=l.slice(r[0].length)||l),s.push(i=[])),o=!1,(r=ue.exec(l))&&(o=r.shift(),i.push({value:o,type:r[0].replace(se," ")}),l=l.slice(o.length));for(a in w.filter)!(r=he[a].exec(l))||c[a]&&!(r=c[a](r))||(o=r.shift(),i.push({value:o,type:a,matches:r}),l=l.slice(o.length));if(!o)break}return n?l.length:l?t.error(e):z(e,s).slice(0)},_=t.compile=function(e,t){var n,o=[],r=[],i=W[e+" "];if(!i){for(t||(t=C(e)),n=t.length;n--;)i=v(t[n]),i[U]?o.push(i):r.push(i);i=W(e,y(r,o)),i.selector=e}return i},D=t.select=function(e,t,n,o){var r,i,a,l,s,c="function"==typeof e&&e,p=!o&&C(e=c.selector||e);if(n=n||[],1===p.length){if(i=p[0]=p[0].slice(0),i.length>2&&"ID"===(a=i[0]).type&&E.getById&&9===t.nodeType&&I&&w.relative[i[1].type]){if(t=(w.find.ID(a.matches[0].replace(Ee,we),t)||[])[0],!t)return n;c&&(t=t.parentNode),e=e.slice(i.shift().value.length)}for(r=he.needsContext.test(e)?0:i.length;r--&&(a=i[r],!w.relative[l=a.type]);)if((s=w.find[l])&&(o=s(a.matches[0].replace(Ee,we),ye.test(i[0].type)&&u(t.parentNode)||t))){if(i.splice(r,1),e=o.length&&d(i),!e)return J.apply(n,o),n;break}}return(c||_(e,p))(o,t,!I,n,ye.test(e)&&u(t.parentNode)||t),n},E.sortStable=U.split("").sort(Y).join("")===U,E.detectDuplicates=!!R,M(),E.sortDetached=r(function(e){return 1&e.compareDocumentPosition(P.createElement("div"))}),r(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||i("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),E.attributes&&r(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||i("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),r(function(e){return null==e.getAttribute("disabled")})||i(te,function(e,t,n){var o;return n?void 0:e[t]===!0?t.toLowerCase():(o=e.getAttributeNode(t))&&o.specified?o.value:null}),t}(n);oe.find=se,oe.expr=se.selectors,oe.expr[":"]=oe.expr.pseudos,oe.unique=se.uniqueSort,oe.text=se.getText,oe.isXMLDoc=se.isXML,oe.contains=se.contains;var ce=oe.expr.match.needsContext,ue=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,pe=/^.[^:#\[\.,]*$/;oe.filter=function(e,t,n){var o=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===o.nodeType?oe.find.matchesSelector(o,e)?[o]:[]:oe.find.matches(e,oe.grep(t,function(e){return 1===e.nodeType}))},oe.fn.extend({find:function(e){var t,n=this.length,o=[],r=this;if("string"!=typeof e)return this.pushStack(oe(e).filter(function(){for(t=0;n>t;t++)if(oe.contains(r[t],this))return!0}));for(t=0;n>t;t++)oe.find(e,r[t],o);return o=this.pushStack(n>1?oe.unique(o):o),o.selector=this.selector?this.selector+" "+e:e,o},filter:function(e){return this.pushStack(l(this,e||[],!1))},not:function(e){return this.pushStack(l(this,e||[],!0))},is:function(e){return!!l(this,"string"==typeof e&&ce.test(e)?oe(e):e||[],!1).length}});var de,fe=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,he=oe.fn.init=function(e,t){var n,o;if(!e)return this;if("string"==typeof e){if(n="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:fe.exec(e),!n||!n[1]&&t)return!t||t.jquery?(t||de).find(e):this.constructor(t).find(e);if(n[1]){if(t=t instanceof oe?t[0]:t,oe.merge(this,oe.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:te,!0)),ue.test(n[1])&&oe.isPlainObject(t))for(n in t)oe.isFunction(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}return o=te.getElementById(n[2]),o&&o.parentNode&&(this.length=1,this[0]=o),this.context=te,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):oe.isFunction(e)?"undefined"!=typeof de.ready?de.ready(e):e(oe):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),oe.makeArray(e,this))};he.prototype=oe.fn,de=oe(te);var ge=/^(?:parents|prev(?:Until|All))/,be={children:!0,contents:!0,next:!0,prev:!0};oe.extend({dir:function(e,t,n){for(var o=[],r=void 0!==n;(e=e[t])&&9!==e.nodeType;)if(1===e.nodeType){if(r&&oe(e).is(n))break;o.push(e)}return o},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}}),oe.fn.extend({has:function(e){var t=oe(e,this),n=t.length;return this.filter(function(){for(var e=0;n>e;e++)if(oe.contains(this,t[e]))return!0})},closest:function(e,t){for(var n,o=0,r=this.length,i=[],a=ce.test(e)||"string"!=typeof e?oe(e,t||this.context):0;r>o;o++)for(n=this[o];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&oe.find.matchesSelector(n,e))){i.push(n);break}return this.pushStack(i.length>1?oe.unique(i):i)},index:function(e){return e?"string"==typeof e?X.call(oe(e),this[0]):X.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(oe.unique(oe.merge(this.get(),oe(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),oe.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return oe.dir(e,"parentNode")},parentsUntil:function(e,t,n){return oe.dir(e,"parentNode",n)},next:function(e){return s(e,"nextSibling")},prev:function(e){return s(e,"previousSibling")},nextAll:function(e){return oe.dir(e,"nextSibling")},prevAll:function(e){return oe.dir(e,"previousSibling")},nextUntil:function(e,t,n){return oe.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return oe.dir(e,"previousSibling",n)},siblings:function(e){return oe.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return oe.sibling(e.firstChild)},contents:function(e){return e.contentDocument||oe.merge([],e.childNodes)}},function(e,t){oe.fn[e]=function(n,o){var r=oe.map(this,t,n);return"Until"!==e.slice(-5)&&(o=n),o&&"string"==typeof o&&(r=oe.filter(o,r)),this.length>1&&(be[e]||oe.unique(r),ge.test(e)&&r.reverse()),this.pushStack(r)}});var me=/\S+/g,ve={};oe.Callbacks=function(e){e="string"==typeof e?ve[e]||c(e):oe.extend({},e);var t,n,o,r,i,a,l=[],s=!e.once&&[],u=function(c){for(t=e.memory&&c,n=!0,a=r||0,r=0,i=l.length,o=!0;l&&i>a;a++)if(l[a].apply(c[0],c[1])===!1&&e.stopOnFalse){t=!1;break}o=!1,l&&(s?s.length&&u(s.shift()):t?l=[]:p.disable())},p={add:function(){if(l){var n=l.length;!function a(t){oe.each(t,function(t,n){var o=oe.type(n);"function"===o?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==o&&a(n)})}(arguments),o?i=l.length:t&&(r=n,u(t))}return this},remove:function(){return l&&oe.each(arguments,function(e,t){for(var n;(n=oe.inArray(t,l,n))>-1;)l.splice(n,1),o&&(i>=n&&i--,a>=n&&a--)}),this},has:function(e){return e?oe.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],i=0,this},disable:function(){return l=s=t=void 0,this},disabled:function(){return!l},lock:function(){return s=void 0,t||p.disable(),this},locked:function(){return!s},fireWith:function(e,t){return!l||n&&!s||(t=t||[],t=[e,t.slice?t.slice():t],o?s.push(t):u(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!n}};return p},oe.extend({Deferred:function(e){var t=[["resolve","done",oe.Callbacks("once memory"),"resolved"],["reject","fail",oe.Callbacks("once memory"),"rejected"],["notify","progress",oe.Callbacks("memory")]],n="pending",o={state:function(){return n},always:function(){return r.done(arguments).fail(arguments),this},then:function(){var e=arguments;return oe.Deferred(function(n){oe.each(t,function(t,i){var a=oe.isFunction(e[t])&&e[t];r[i[1]](function(){var e=a&&a.apply(this,arguments);e&&oe.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[i[0]+"With"](this===o?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?oe.extend(e,o):o}},r={};return o.pipe=o.then,oe.each(t,function(e,i){var a=i[2],l=i[3];o[i[1]]=a.add,l&&a.add(function(){n=l},t[1^e][2].disable,t[2][2].lock),r[i[0]]=function(){return r[i[0]+"With"](this===r?o:this,arguments),this},r[i[0]+"With"]=a.fireWith}),o.promise(r),e&&e.call(r,r),r},when:function(e){var t,n,o,r=0,i=K.call(arguments),a=i.length,l=1!==a||e&&oe.isFunction(e.promise)?a:0,s=1===l?e:oe.Deferred(),c=function(e,n,o){return function(r){n[e]=this,o[e]=arguments.length>1?K.call(arguments):r,o===t?s.notifyWith(n,o):--l||s.resolveWith(n,o)}};if(a>1)for(t=new Array(a),n=new Array(a),o=new Array(a);a>r;r++)i[r]&&oe.isFunction(i[r].promise)?i[r].promise().done(c(r,o,i)).fail(s.reject).progress(c(r,n,t)):--l;return l||s.resolveWith(o,i),s.promise()}});var ye;oe.fn.ready=function(e){return oe.ready.promise().done(e),this},oe.extend({isReady:!1,readyWait:1,holdReady:function(e){e?oe.readyWait++:oe.ready(!0)},ready:function(e){(e===!0?--oe.readyWait:oe.isReady)||(oe.isReady=!0,e!==!0&&--oe.readyWait>0||(ye.resolveWith(te,[oe]),oe.fn.triggerHandler&&(oe(te).triggerHandler("ready"),oe(te).off("ready"))))}}),oe.ready.promise=function(e){return ye||(ye=oe.Deferred(),"complete"===te.readyState?setTimeout(oe.ready):(te.addEventListener("DOMContentLoaded",u,!1),n.addEventListener("load",u,!1))),ye.promise(e)},oe.ready.promise();var xe=oe.access=function(e,t,n,o,r,i,a){var l=0,s=e.length,c=null==n;if("object"===oe.type(n)){r=!0;for(l in n)oe.access(e,t,l,n[l],!0,i,a)}else if(void 0!==o&&(r=!0,oe.isFunction(o)||(a=!0),c&&(a?(t.call(e,o),t=null):(c=t,t=function(e,t,n){return c.call(oe(e),n)})),t))for(;s>l;l++)t(e[l],n,a?o:o.call(e[l],l,t(e[l],n)));return r?e:c?t.call(e):s?t(e[0],n):i};oe.acceptData=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType},p.uid=1,p.accepts=oe.acceptData,p.prototype={key:function(e){if(!p.accepts(e))return 0;var t={},n=e[this.expando];if(!n){n=p.uid++;try{t[this.expando]={value:n},Object.defineProperties(e,t)}catch(o){t[this.expando]=n,oe.extend(e,t)}}return this.cache[n]||(this.cache[n]={}),n},set:function(e,t,n){var o,r=this.key(e),i=this.cache[r];if("string"==typeof t)i[t]=n;else if(oe.isEmptyObject(i))oe.extend(this.cache[r],t);else for(o in t)i[o]=t[o];return i},get:function(e,t){var n=this.cache[this.key(e)];return void 0===t?n:n[t]},access:function(e,t,n){var o;return void 0===t||t&&"string"==typeof t&&void 0===n?(o=this.get(e,t),void 0!==o?o:this.get(e,oe.camelCase(t))):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,o,r,i=this.key(e),a=this.cache[i];if(void 0===t)this.cache[i]={};else{oe.isArray(t)?o=t.concat(t.map(oe.camelCase)):(r=oe.camelCase(t),t in a?o=[t,r]:(o=r,o=o in a?[o]:o.match(me)||[])),n=o.length;for(;n--;)delete a[o[n]]}},hasData:function(e){return!oe.isEmptyObject(this.cache[e[this.expando]]||{})},discard:function(e){e[this.expando]&&delete this.cache[e[this.expando]]}};var Ee=new p,we=new p,Ne=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,ke=/([A-Z])/g;oe.extend({hasData:function(e){return we.hasData(e)||Ee.hasData(e)},data:function(e,t,n){return we.access(e,t,n)},removeData:function(e,t){we.remove(e,t)},_data:function(e,t,n){return Ee.access(e,t,n)},_removeData:function(e,t){Ee.remove(e,t)}}),oe.fn.extend({data:function(e,t){var n,o,r,i=this[0],a=i&&i.attributes;if(void 0===e){if(this.length&&(r=we.get(i),1===i.nodeType&&!Ee.get(i,"hasDataAttrs"))){for(n=a.length;n--;)a[n]&&(o=a[n].name,0===o.indexOf("data-")&&(o=oe.camelCase(o.slice(5)),d(i,o,r[o])));Ee.set(i,"hasDataAttrs",!0)}return r}return"object"==typeof e?this.each(function(){we.set(this,e)}):xe(this,function(t){var n,o=oe.camelCase(e);if(i&&void 0===t){if(n=we.get(i,e),void 0!==n)return n;if(n=we.get(i,o),void 0!==n)return n;if(n=d(i,o,void 0),void 0!==n)return n}else this.each(function(){var n=we.get(this,o);we.set(this,o,t),-1!==e.indexOf("-")&&void 0!==n&&we.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){we.remove(this,e)})}}),oe.extend({queue:function(e,t,n){var o;return e?(t=(t||"fx")+"queue",o=Ee.get(e,t),n&&(!o||oe.isArray(n)?o=Ee.access(e,t,oe.makeArray(n)):o.push(n)),o||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=oe.queue(e,t),o=n.length,r=n.shift(),i=oe._queueHooks(e,t),a=function(){oe.dequeue(e,t)};"inprogress"===r&&(r=n.shift(),o--),r&&("fx"===t&&n.unshift("inprogress"),delete i.stop,r.call(e,a,i)),!o&&i&&i.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return Ee.get(e,n)||Ee.access(e,n,{empty:oe.Callbacks("once memory").add(function(){Ee.remove(e,[t+"queue",n])})})}}),oe.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?oe.queue(this[0],e):void 0===t?this:this.each(function(){var n=oe.queue(this,e,t);oe._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&oe.dequeue(this,e)})},dequeue:function(e){return this.each(function(){oe.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,o=1,r=oe.Deferred(),i=this,a=this.length,l=function(){--o||r.resolveWith(i,[i])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";a--;)n=Ee.get(i[a],e+"queueHooks"),n&&n.empty&&(o++,n.empty.add(l));return l(),r.promise(t)}});var Ce=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,_e=["Top","Right","Bottom","Left"],De=function(e,t){return e=t||e,"none"===oe.css(e,"display")||!oe.contains(e.ownerDocument,e)},Oe=/^(?:checkbox|radio)$/i;!function(){var e=te.createDocumentFragment(),t=e.appendChild(te.createElement("div")),n=te.createElement("input");n.setAttribute("type","radio"),n.setAttribute("checked","checked"),n.setAttribute("name","t"),t.appendChild(n),ee.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,t.innerHTML="<textarea>x</textarea>",ee.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue}();var Te="undefined";ee.focusinBubbles="onfocusin"in n;var Re=/^key/,Me=/^(?:mouse|pointer|contextmenu)|click/,Pe=/^(?:focusinfocus|focusoutblur)$/,Se=/^([^.]*)(?:\.(.+)|)$/;oe.event={global:{},add:function(e,t,n,o,r){var i,a,l,s,c,u,p,d,f,h,g,b=Ee.get(e);if(b)for(n.handler&&(i=n,n=i.handler,r=i.selector),n.guid||(n.guid=oe.guid++),(s=b.events)||(s=b.events={}),(a=b.handle)||(a=b.handle=function(t){return typeof oe!==Te&&oe.event.triggered!==t.type?oe.event.dispatch.apply(e,arguments):void 0}),t=(t||"").match(me)||[""],c=t.length;c--;)l=Se.exec(t[c])||[],f=g=l[1],h=(l[2]||"").split(".").sort(),f&&(p=oe.event.special[f]||{},f=(r?p.delegateType:p.bindType)||f,p=oe.event.special[f]||{},u=oe.extend({type:f,origType:g,data:o,handler:n,guid:n.guid,selector:r,needsContext:r&&oe.expr.match.needsContext.test(r),namespace:h.join(".")},i),(d=s[f])||(d=s[f]=[],d.delegateCount=0,p.setup&&p.setup.call(e,o,h,a)!==!1||e.addEventListener&&e.addEventListener(f,a,!1)),p.add&&(p.add.call(e,u),u.handler.guid||(u.handler.guid=n.guid)),r?d.splice(d.delegateCount++,0,u):d.push(u),oe.event.global[f]=!0)},remove:function(e,t,n,o,r){var i,a,l,s,c,u,p,d,f,h,g,b=Ee.hasData(e)&&Ee.get(e);if(b&&(s=b.events)){for(t=(t||"").match(me)||[""],c=t.length;c--;)if(l=Se.exec(t[c])||[],f=g=l[1],h=(l[2]||"").split(".").sort(),f){for(p=oe.event.special[f]||{},f=(o?p.delegateType:p.bindType)||f,d=s[f]||[],l=l[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=i=d.length;i--;)u=d[i],!r&&g!==u.origType||n&&n.guid!==u.guid||l&&!l.test(u.namespace)||o&&o!==u.selector&&("**"!==o||!u.selector)||(d.splice(i,1),u.selector&&d.delegateCount--,p.remove&&p.remove.call(e,u));a&&!d.length&&(p.teardown&&p.teardown.call(e,h,b.handle)!==!1||oe.removeEvent(e,f,b.handle),delete s[f])}else for(f in s)oe.event.remove(e,f+t[c],n,o,!0);oe.isEmptyObject(s)&&(delete b.handle,Ee.remove(e,"events"))}},trigger:function(e,t,o,r){var i,a,l,s,c,u,p,d=[o||te],f=Z.call(e,"type")?e.type:e,h=Z.call(e,"namespace")?e.namespace.split("."):[];if(a=l=o=o||te,3!==o.nodeType&&8!==o.nodeType&&!Pe.test(f+oe.event.triggered)&&(f.indexOf(".")>=0&&(h=f.split("."),f=h.shift(),h.sort()),c=f.indexOf(":")<0&&"on"+f,e=e[oe.expando]?e:new oe.Event(f,"object"==typeof e&&e), e.isTrigger=r?2:3,e.namespace=h.join("."),e.namespace_re=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=o),t=null==t?[e]:oe.makeArray(t,[e]),p=oe.event.special[f]||{},r||!p.trigger||p.trigger.apply(o,t)!==!1)){if(!r&&!p.noBubble&&!oe.isWindow(o)){for(s=p.delegateType||f,Pe.test(s+f)||(a=a.parentNode);a;a=a.parentNode)d.push(a),l=a;l===(o.ownerDocument||te)&&d.push(l.defaultView||l.parentWindow||n)}for(i=0;(a=d[i++])&&!e.isPropagationStopped();)e.type=i>1?s:p.bindType||f,u=(Ee.get(a,"events")||{})[e.type]&&Ee.get(a,"handle"),u&&u.apply(a,t),u=c&&a[c],u&&u.apply&&oe.acceptData(a)&&(e.result=u.apply(a,t),e.result===!1&&e.preventDefault());return e.type=f,r||e.isDefaultPrevented()||p._default&&p._default.apply(d.pop(),t)!==!1||!oe.acceptData(o)||c&&oe.isFunction(o[f])&&!oe.isWindow(o)&&(l=o[c],l&&(o[c]=null),oe.event.triggered=f,o[f](),oe.event.triggered=void 0,l&&(o[c]=l)),e.result}},dispatch:function(e){e=oe.event.fix(e);var t,n,o,r,i,a=[],l=K.call(arguments),s=(Ee.get(this,"events")||{})[e.type]||[],c=oe.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){for(a=oe.event.handlers.call(this,e,s),t=0;(r=a[t++])&&!e.isPropagationStopped();)for(e.currentTarget=r.elem,n=0;(i=r.handlers[n++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,o=((oe.event.special[i.origType]||{}).handle||i.handler).apply(r.elem,l),void 0!==o&&(e.result=o)===!1&&(e.preventDefault(),e.stopPropagation()));return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,o,r,i,a=[],l=t.delegateCount,s=e.target;if(l&&s.nodeType&&(!e.button||"click"!==e.type))for(;s!==this;s=s.parentNode||this)if(s.disabled!==!0||"click"!==e.type){for(o=[],n=0;l>n;n++)i=t[n],r=i.selector+" ",void 0===o[r]&&(o[r]=i.needsContext?oe(r,this).index(s)>=0:oe.find(r,this,null,[s]).length),o[r]&&o.push(i);o.length&&a.push({elem:s,handlers:o})}return l<t.length&&a.push({elem:this,handlers:t.slice(l)}),a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,o,r,i=t.button;return null==e.pageX&&null!=t.clientX&&(n=e.target.ownerDocument||te,o=n.documentElement,r=n.body,e.pageX=t.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=t.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),e.which||void 0===i||(e.which=1&i?1:2&i?3:4&i?2:0),e}},fix:function(e){if(e[oe.expando])return e;var t,n,o,r=e.type,i=e,a=this.fixHooks[r];for(a||(this.fixHooks[r]=a=Me.test(r)?this.mouseHooks:Re.test(r)?this.keyHooks:{}),o=a.props?this.props.concat(a.props):this.props,e=new oe.Event(i),t=o.length;t--;)n=o[t],e[n]=i[n];return e.target||(e.target=te),3===e.target.nodeType&&(e.target=e.target.parentNode),a.filter?a.filter(e,i):e},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==g()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===g()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&oe.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(e){return oe.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,o){var r=oe.extend(new oe.Event,n,{type:e,isSimulated:!0,originalEvent:{}});o?oe.event.trigger(r,null,t):oe.event.dispatch.call(t,r),r.isDefaultPrevented()&&n.preventDefault()}},oe.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)},oe.Event=function(e,t){return this instanceof oe.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:h):this.type=e,t&&oe.extend(this,t),this.timeStamp=e&&e.timeStamp||oe.now(),void(this[oe.expando]=!0)):new oe.Event(e,t)},oe.Event.prototype={isDefaultPrevented:h,isPropagationStopped:h,isImmediatePropagationStopped:h,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f,e&&e.preventDefault&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f,e&&e.stopPropagation&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=f,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},oe.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){oe.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,o=this,r=e.relatedTarget,i=e.handleObj;return(!r||r!==o&&!oe.contains(o,r))&&(e.type=i.origType,n=i.handler.apply(this,arguments),e.type=t),n}}}),ee.focusinBubbles||oe.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){oe.event.simulate(t,e.target,oe.event.fix(e),!0)};oe.event.special[t]={setup:function(){var o=this.ownerDocument||this,r=Ee.access(o,t);r||o.addEventListener(e,n,!0),Ee.access(o,t,(r||0)+1)},teardown:function(){var o=this.ownerDocument||this,r=Ee.access(o,t)-1;r?Ee.access(o,t,r):(o.removeEventListener(e,n,!0),Ee.remove(o,t))}}}),oe.fn.extend({on:function(e,t,n,o,r){var i,a;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=void 0);for(a in e)this.on(a,t,n,e[a],r);return this}if(null==n&&null==o?(o=t,n=t=void 0):null==o&&("string"==typeof t?(o=n,n=void 0):(o=n,n=t,t=void 0)),o===!1)o=h;else if(!o)return this;return 1===r&&(i=o,o=function(e){return oe().off(e),i.apply(this,arguments)},o.guid=i.guid||(i.guid=oe.guid++)),this.each(function(){oe.event.add(this,e,o,n,t)})},one:function(e,t,n,o){return this.on(e,t,n,o,1)},off:function(e,t,n){var o,r;if(e&&e.preventDefault&&e.handleObj)return o=e.handleObj,oe(e.delegateTarget).off(o.namespace?o.origType+"."+o.namespace:o.origType,o.selector,o.handler),this;if("object"==typeof e){for(r in e)this.off(r,t,e[r]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=void 0),n===!1&&(n=h),this.each(function(){oe.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){oe.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?oe.event.trigger(e,t,n,!0):void 0}});var Ie=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Ae=/<([\w:]+)/,je=/<|&#?\w+;/,Le=/<(?:script|style|link)/i,Ve=/checked\s*(?:[^=]|=\s*.checked.)/i,Ue=/^$|\/(?:java|ecma)script/i,Fe=/^true\/(.*)/,Be=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,qe={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};qe.optgroup=qe.option,qe.tbody=qe.tfoot=qe.colgroup=qe.caption=qe.thead,qe.th=qe.td,oe.extend({clone:function(e,t,n){var o,r,i,a,l=e.cloneNode(!0),s=oe.contains(e.ownerDocument,e);if(!(ee.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||oe.isXMLDoc(e)))for(a=E(l),i=E(e),o=0,r=i.length;r>o;o++)w(i[o],a[o]);if(t)if(n)for(i=i||E(e),a=a||E(l),o=0,r=i.length;r>o;o++)x(i[o],a[o]);else x(e,l);return a=E(l,"script"),a.length>0&&y(a,!s&&E(e,"script")),l},buildFragment:function(e,t,n,o){for(var r,i,a,l,s,c,u=t.createDocumentFragment(),p=[],d=0,f=e.length;f>d;d++)if(r=e[d],r||0===r)if("object"===oe.type(r))oe.merge(p,r.nodeType?[r]:r);else if(je.test(r)){for(i=i||u.appendChild(t.createElement("div")),a=(Ae.exec(r)||["",""])[1].toLowerCase(),l=qe[a]||qe._default,i.innerHTML=l[1]+r.replace(Ie,"<$1></$2>")+l[2],c=l[0];c--;)i=i.lastChild;oe.merge(p,i.childNodes),i=u.firstChild,i.textContent=""}else p.push(t.createTextNode(r));for(u.textContent="",d=0;r=p[d++];)if((!o||-1===oe.inArray(r,o))&&(s=oe.contains(r.ownerDocument,r),i=E(u.appendChild(r),"script"),s&&y(i),n))for(c=0;r=i[c++];)Ue.test(r.type||"")&&n.push(r);return u},cleanData:function(e){for(var t,n,o,r,i=oe.event.special,a=0;void 0!==(n=e[a]);a++){if(oe.acceptData(n)&&(r=n[Ee.expando],r&&(t=Ee.cache[r]))){if(t.events)for(o in t.events)i[o]?oe.event.remove(n,o):oe.removeEvent(n,o,t.handle);Ee.cache[r]&&delete Ee.cache[r]}delete we.cache[n[we.expando]]}}}),oe.fn.extend({text:function(e){return xe(this,function(e){return void 0===e?oe.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=e)})},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=b(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=b(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var n,o=e?oe.filter(e,this):this,r=0;null!=(n=o[r]);r++)t||1!==n.nodeType||oe.cleanData(E(n)),n.parentNode&&(t&&oe.contains(n.ownerDocument,n)&&y(E(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(oe.cleanData(E(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return oe.clone(this,e,t)})},html:function(e){return xe(this,function(e){var t=this[0]||{},n=0,o=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Le.test(e)&&!qe[(Ae.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(Ie,"<$1></$2>");try{for(;o>n;n++)t=this[n]||{},1===t.nodeType&&(oe.cleanData(E(t,!1)),t.innerHTML=e);t=0}catch(r){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,oe.cleanData(E(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=$.apply([],e);var n,o,r,i,a,l,s=0,c=this.length,u=this,p=c-1,d=e[0],f=oe.isFunction(d);if(f||c>1&&"string"==typeof d&&!ee.checkClone&&Ve.test(d))return this.each(function(n){var o=u.eq(n);f&&(e[0]=d.call(this,n,o.html())),o.domManip(e,t)});if(c&&(n=oe.buildFragment(e,this[0].ownerDocument,!1,this),o=n.firstChild,1===n.childNodes.length&&(n=o),o)){for(r=oe.map(E(n,"script"),m),i=r.length;c>s;s++)a=n,s!==p&&(a=oe.clone(a,!0,!0),i&&oe.merge(r,E(a,"script"))),t.call(this[s],a,s);if(i)for(l=r[r.length-1].ownerDocument,oe.map(r,v),s=0;i>s;s++)a=r[s],Ue.test(a.type||"")&&!Ee.access(a,"globalEval")&&oe.contains(l,a)&&(a.src?oe._evalUrl&&oe._evalUrl(a.src):oe.globalEval(a.textContent.replace(Be,"")))}return this}}),oe.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){oe.fn[e]=function(e){for(var n,o=[],r=oe(e),i=r.length-1,a=0;i>=a;a++)n=a===i?this:this.clone(!0),oe(r[a])[t](n),G.apply(o,n.get());return this.pushStack(o)}});var He,ze={},We=/^margin/,Ye=new RegExp("^("+Ce+")(?!px)[a-z%]+$","i"),Ke=function(e){return e.ownerDocument.defaultView.opener?e.ownerDocument.defaultView.getComputedStyle(e,null):n.getComputedStyle(e,null)};!function(){function e(){a.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",a.innerHTML="",r.appendChild(i);var e=n.getComputedStyle(a,null);t="1%"!==e.top,o="4px"===e.width,r.removeChild(i)}var t,o,r=te.documentElement,i=te.createElement("div"),a=te.createElement("div");a.style&&(a.style.backgroundClip="content-box",a.cloneNode(!0).style.backgroundClip="",ee.clearCloneStyle="content-box"===a.style.backgroundClip,i.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute",i.appendChild(a),n.getComputedStyle&&oe.extend(ee,{pixelPosition:function(){return e(),t},boxSizingReliable:function(){return null==o&&e(),o},reliableMarginRight:function(){var e,t=a.appendChild(te.createElement("div"));return t.style.cssText=a.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",t.style.marginRight=t.style.width="0",a.style.width="1px",r.appendChild(i),e=!parseFloat(n.getComputedStyle(t,null).marginRight),r.removeChild(i),a.removeChild(t),e}}))}(),oe.swap=function(e,t,n,o){var r,i,a={};for(i in t)a[i]=e.style[i],e.style[i]=t[i];r=n.apply(e,o||[]);for(i in t)e.style[i]=a[i];return r};var $e=/^(none|table(?!-c[ea]).+)/,Ge=new RegExp("^("+Ce+")(.*)$","i"),Xe=new RegExp("^([+-])=("+Ce+")","i"),Qe={position:"absolute",visibility:"hidden",display:"block"},Je={letterSpacing:"0",fontWeight:"400"},Ze=["Webkit","O","Moz","ms"];oe.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=C(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(e,t,n,o){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var r,i,a,l=oe.camelCase(t),s=e.style;return t=oe.cssProps[l]||(oe.cssProps[l]=D(s,l)),a=oe.cssHooks[t]||oe.cssHooks[l],void 0===n?a&&"get"in a&&void 0!==(r=a.get(e,!1,o))?r:s[t]:(i=typeof n,"string"===i&&(r=Xe.exec(n))&&(n=(r[1]+1)*r[2]+parseFloat(oe.css(e,t)),i="number"),null!=n&&n===n&&("number"!==i||oe.cssNumber[l]||(n+="px"),ee.clearCloneStyle||""!==n||0!==t.indexOf("background")||(s[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,o))||(s[t]=n)),void 0)}},css:function(e,t,n,o){var r,i,a,l=oe.camelCase(t);return t=oe.cssProps[l]||(oe.cssProps[l]=D(e.style,l)),a=oe.cssHooks[t]||oe.cssHooks[l],a&&"get"in a&&(r=a.get(e,!0,n)),void 0===r&&(r=C(e,t,o)),"normal"===r&&t in Je&&(r=Je[t]),""===n||n?(i=parseFloat(r),n===!0||oe.isNumeric(i)?i||0:r):r}}),oe.each(["height","width"],function(e,t){oe.cssHooks[t]={get:function(e,n,o){return n?$e.test(oe.css(e,"display"))&&0===e.offsetWidth?oe.swap(e,Qe,function(){return R(e,t,o)}):R(e,t,o):void 0},set:function(e,n,o){var r=o&&Ke(e);return O(e,n,o?T(e,t,o,"border-box"===oe.css(e,"boxSizing",!1,r),r):0)}}}),oe.cssHooks.marginRight=_(ee.reliableMarginRight,function(e,t){return t?oe.swap(e,{display:"inline-block"},C,[e,"marginRight"]):void 0}),oe.each({margin:"",padding:"",border:"Width"},function(e,t){oe.cssHooks[e+t]={expand:function(n){for(var o=0,r={},i="string"==typeof n?n.split(" "):[n];4>o;o++)r[e+_e[o]+t]=i[o]||i[o-2]||i[0];return r}},We.test(e)||(oe.cssHooks[e+t].set=O)}),oe.fn.extend({css:function(e,t){return xe(this,function(e,t,n){var o,r,i={},a=0;if(oe.isArray(t)){for(o=Ke(e),r=t.length;r>a;a++)i[t[a]]=oe.css(e,t[a],!1,o);return i}return void 0!==n?oe.style(e,t,n):oe.css(e,t)},e,t,arguments.length>1)},show:function(){return M(this,!0)},hide:function(){return M(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){De(this)?oe(this).show():oe(this).hide()})}}),oe.Tween=P,P.prototype={constructor:P,init:function(e,t,n,o,r,i){this.elem=e,this.prop=n,this.easing=r||"swing",this.options=t,this.start=this.now=this.cur(),this.end=o,this.unit=i||(oe.cssNumber[n]?"":"px")},cur:function(){var e=P.propHooks[this.prop];return e&&e.get?e.get(this):P.propHooks._default.get(this)},run:function(e){var t,n=P.propHooks[this.prop];return this.options.duration?this.pos=t=oe.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):P.propHooks._default.set(this),this}},P.prototype.init.prototype=P.prototype,P.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=oe.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){oe.fx.step[e.prop]?oe.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[oe.cssProps[e.prop]]||oe.cssHooks[e.prop])?oe.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},P.propHooks.scrollTop=P.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},oe.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},oe.fx=P.prototype.init,oe.fx.step={};var et,tt,nt=/^(?:toggle|show|hide)$/,ot=new RegExp("^(?:([+-])=|)("+Ce+")([a-z%]*)$","i"),rt=/queueHooks$/,it=[j],at={"*":[function(e,t){var n=this.createTween(e,t),o=n.cur(),r=ot.exec(t),i=r&&r[3]||(oe.cssNumber[e]?"":"px"),a=(oe.cssNumber[e]||"px"!==i&&+o)&&ot.exec(oe.css(n.elem,e)),l=1,s=20;if(a&&a[3]!==i){i=i||a[3],r=r||[],a=+o||1;do l=l||".5",a/=l,oe.style(n.elem,e,a+i);while(l!==(l=n.cur()/o)&&1!==l&&--s)}return r&&(a=n.start=+a||+o||0,n.unit=i,n.end=r[1]?a+(r[1]+1)*r[2]:+r[2]),n}]};oe.Animation=oe.extend(V,{tweener:function(e,t){oe.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,o=0,r=e.length;r>o;o++)n=e[o],at[n]=at[n]||[],at[n].unshift(t)},prefilter:function(e,t){t?it.unshift(e):it.push(e)}}),oe.speed=function(e,t,n){var o=e&&"object"==typeof e?oe.extend({},e):{complete:n||!n&&t||oe.isFunction(e)&&e,duration:e,easing:n&&t||t&&!oe.isFunction(t)&&t};return o.duration=oe.fx.off?0:"number"==typeof o.duration?o.duration:o.duration in oe.fx.speeds?oe.fx.speeds[o.duration]:oe.fx.speeds._default,(null==o.queue||o.queue===!0)&&(o.queue="fx"),o.old=o.complete,o.complete=function(){oe.isFunction(o.old)&&o.old.call(this),o.queue&&oe.dequeue(this,o.queue)},o},oe.fn.extend({fadeTo:function(e,t,n,o){return this.filter(De).css("opacity",0).show().end().animate({opacity:t},e,n,o)},animate:function(e,t,n,o){var r=oe.isEmptyObject(e),i=oe.speed(t,n,o),a=function(){var t=V(this,oe.extend({},e),i);(r||Ee.get(this,"finish"))&&t.stop(!0)};return a.finish=a,r||i.queue===!1?this.each(a):this.queue(i.queue,a)},stop:function(e,t,n){var o=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,r=null!=e&&e+"queueHooks",i=oe.timers,a=Ee.get(this);if(r)a[r]&&a[r].stop&&o(a[r]);else for(r in a)a[r]&&a[r].stop&&rt.test(r)&&o(a[r]);for(r=i.length;r--;)i[r].elem!==this||null!=e&&i[r].queue!==e||(i[r].anim.stop(n),t=!1,i.splice(r,1));(t||!n)&&oe.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=Ee.get(this),o=n[e+"queue"],r=n[e+"queueHooks"],i=oe.timers,a=o?o.length:0;for(n.finish=!0,oe.queue(this,e,[]),r&&r.stop&&r.stop.call(this,!0),t=i.length;t--;)i[t].elem===this&&i[t].queue===e&&(i[t].anim.stop(!0),i.splice(t,1));for(t=0;a>t;t++)o[t]&&o[t].finish&&o[t].finish.call(this);delete n.finish})}}),oe.each(["toggle","show","hide"],function(e,t){var n=oe.fn[t];oe.fn[t]=function(e,o,r){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(I(t,!0),e,o,r)}}),oe.each({slideDown:I("show"),slideUp:I("hide"),slideToggle:I("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){oe.fn[e]=function(e,n,o){return this.animate(t,e,n,o)}}),oe.timers=[],oe.fx.tick=function(){var e,t=0,n=oe.timers;for(et=oe.now();t<n.length;t++)e=n[t],e()||n[t]!==e||n.splice(t--,1);n.length||oe.fx.stop(),et=void 0},oe.fx.timer=function(e){oe.timers.push(e),e()?oe.fx.start():oe.timers.pop()},oe.fx.interval=13,oe.fx.start=function(){tt||(tt=setInterval(oe.fx.tick,oe.fx.interval))},oe.fx.stop=function(){clearInterval(tt),tt=null},oe.fx.speeds={slow:600,fast:200,_default:400},oe.fn.delay=function(e,t){return e=oe.fx?oe.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var o=setTimeout(t,e);n.stop=function(){clearTimeout(o)}})},function(){var e=te.createElement("input"),t=te.createElement("select"),n=t.appendChild(te.createElement("option"));e.type="checkbox",ee.checkOn=""!==e.value,ee.optSelected=n.selected,t.disabled=!0,ee.optDisabled=!n.disabled,e=te.createElement("input"),e.value="t",e.type="radio",ee.radioValue="t"===e.value}();var lt,st,ct=oe.expr.attrHandle;oe.fn.extend({attr:function(e,t){return xe(this,oe.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){oe.removeAttr(this,e)})}}),oe.extend({attr:function(e,t,n){var o,r,i=e.nodeType;if(e&&3!==i&&8!==i&&2!==i)return typeof e.getAttribute===Te?oe.prop(e,t,n):(1===i&&oe.isXMLDoc(e)||(t=t.toLowerCase(),o=oe.attrHooks[t]||(oe.expr.match.bool.test(t)?st:lt)),void 0===n?o&&"get"in o&&null!==(r=o.get(e,t))?r:(r=oe.find.attr(e,t),null==r?void 0:r):null!==n?o&&"set"in o&&void 0!==(r=o.set(e,n,t))?r:(e.setAttribute(t,n+""),n):void oe.removeAttr(e,t))},removeAttr:function(e,t){var n,o,r=0,i=t&&t.match(me);if(i&&1===e.nodeType)for(;n=i[r++];)o=oe.propFix[n]||n,oe.expr.match.bool.test(n)&&(e[o]=!1),e.removeAttribute(n)},attrHooks:{type:{set:function(e,t){if(!ee.radioValue&&"radio"===t&&oe.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}}}),st={set:function(e,t,n){return t===!1?oe.removeAttr(e,n):e.setAttribute(n,n),n}},oe.each(oe.expr.match.bool.source.match(/\w+/g),function(e,t){var n=ct[t]||oe.find.attr;ct[t]=function(e,t,o){var r,i;return o||(i=ct[t],ct[t]=r,r=null!=n(e,t,o)?t.toLowerCase():null,ct[t]=i),r}});var ut=/^(?:input|select|textarea|button)$/i;oe.fn.extend({prop:function(e,t){return xe(this,oe.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[oe.propFix[e]||e]})}}),oe.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var o,r,i,a=e.nodeType;if(e&&3!==a&&8!==a&&2!==a)return i=1!==a||!oe.isXMLDoc(e),i&&(t=oe.propFix[t]||t,r=oe.propHooks[t]),void 0!==n?r&&"set"in r&&void 0!==(o=r.set(e,n,t))?o:e[t]=n:r&&"get"in r&&null!==(o=r.get(e,t))?o:e[t]},propHooks:{tabIndex:{get:function(e){return e.hasAttribute("tabindex")||ut.test(e.nodeName)||e.href?e.tabIndex:-1}}}}),ee.optSelected||(oe.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null}}),oe.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){oe.propFix[this.toLowerCase()]=this});var pt=/[\t\r\n\f]/g;oe.fn.extend({addClass:function(e){var t,n,o,r,i,a,l="string"==typeof e&&e,s=0,c=this.length;if(oe.isFunction(e))return this.each(function(t){oe(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(me)||[];c>s;s++)if(n=this[s],o=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(pt," "):" ")){for(i=0;r=t[i++];)o.indexOf(" "+r+" ")<0&&(o+=r+" ");a=oe.trim(o),n.className!==a&&(n.className=a)}return this},removeClass:function(e){var t,n,o,r,i,a,l=0===arguments.length||"string"==typeof e&&e,s=0,c=this.length;if(oe.isFunction(e))return this.each(function(t){oe(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(me)||[];c>s;s++)if(n=this[s],o=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(pt," "):"")){for(i=0;r=t[i++];)for(;o.indexOf(" "+r+" ")>=0;)o=o.replace(" "+r+" "," ");a=e?oe.trim(o):"",n.className!==a&&(n.className=a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):oe.isFunction(e)?this.each(function(n){oe(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n)for(var t,o=0,r=oe(this),i=e.match(me)||[];t=i[o++];)r.hasClass(t)?r.removeClass(t):r.addClass(t);else(n===Te||"boolean"===n)&&(this.className&&Ee.set(this,"__className__",this.className),this.className=this.className||e===!1?"":Ee.get(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,o=this.length;o>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(pt," ").indexOf(t)>=0)return!0;return!1}});var dt=/\r/g;oe.fn.extend({val:function(e){var t,n,o,r=this[0];{if(arguments.length)return o=oe.isFunction(e),this.each(function(n){var r;1===this.nodeType&&(r=o?e.call(this,n,oe(this).val()):e,null==r?r="":"number"==typeof r?r+="":oe.isArray(r)&&(r=oe.map(r,function(e){return null==e?"":e+""})),t=oe.valHooks[this.type]||oe.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,r,"value")||(this.value=r))});if(r)return t=oe.valHooks[r.type]||oe.valHooks[r.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(r,"value"))?n:(n=r.value,"string"==typeof n?n.replace(dt,""):null==n?"":n)}}}),oe.extend({valHooks:{option:{get:function(e){var t=oe.find.attr(e,"value");return null!=t?t:oe.trim(oe.text(e))}},select:{get:function(e){for(var t,n,o=e.options,r=e.selectedIndex,i="select-one"===e.type||0>r,a=i?null:[],l=i?r+1:o.length,s=0>r?l:i?r:0;l>s;s++)if(n=o[s],(n.selected||s===r)&&(ee.optDisabled?!n.disabled:null===n.getAttribute("disabled"))&&(!n.parentNode.disabled||!oe.nodeName(n.parentNode,"optgroup"))){if(t=oe(n).val(),i)return t;a.push(t)}return a},set:function(e,t){for(var n,o,r=e.options,i=oe.makeArray(t),a=r.length;a--;)o=r[a],(o.selected=oe.inArray(o.value,i)>=0)&&(n=!0);return n||(e.selectedIndex=-1),i}}}}),oe.each(["radio","checkbox"],function(){oe.valHooks[this]={set:function(e,t){return oe.isArray(t)?e.checked=oe.inArray(oe(e).val(),t)>=0:void 0}},ee.checkOn||(oe.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),oe.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){oe.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),oe.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,o){return this.on(t,e,n,o)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var ft=oe.now(),ht=/\?/;oe.parseJSON=function(e){return JSON.parse(e+"")},oe.parseXML=function(e){var t,n;if(!e||"string"!=typeof e)return null;try{n=new DOMParser,t=n.parseFromString(e,"text/xml")}catch(o){t=void 0}return(!t||t.getElementsByTagName("parsererror").length)&&oe.error("Invalid XML: "+e),t};var gt=/#.*$/,bt=/([?&])_=[^&]*/,mt=/^(.*?):[ \t]*([^\r\n]*)$/gm,vt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,yt=/^(?:GET|HEAD)$/,xt=/^\/\//,Et=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,wt={},Nt={},kt="*/".concat("*"),Ct=n.location.href,_t=Et.exec(Ct.toLowerCase())||[];oe.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ct,type:"GET",isLocal:vt.test(_t[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":kt,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":oe.parseJSON,"text xml":oe.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?B(B(e,oe.ajaxSettings),t):B(oe.ajaxSettings,e)},ajaxPrefilter:U(wt),ajaxTransport:U(Nt),ajax:function(e,t){function n(e,t,n,a){var s,u,m,v,x,w=t;2!==y&&(y=2,l&&clearTimeout(l),o=void 0,i=a||"",E.readyState=e>0?4:0,s=e>=200&&300>e||304===e,n&&(v=q(p,E,n)),v=H(p,v,E,s),s?(p.ifModified&&(x=E.getResponseHeader("Last-Modified"),x&&(oe.lastModified[r]=x),x=E.getResponseHeader("etag"),x&&(oe.etag[r]=x)),204===e||"HEAD"===p.type?w="nocontent":304===e?w="notmodified":(w=v.state,u=v.data,m=v.error,s=!m)):(m=w,(e||!w)&&(w="error",0>e&&(e=0))),E.status=e,E.statusText=(t||w)+"",s?h.resolveWith(d,[u,w,E]):h.rejectWith(d,[E,w,m]),E.statusCode(b),b=void 0,c&&f.trigger(s?"ajaxSuccess":"ajaxError",[E,p,s?u:m]),g.fireWith(d,[E,w]),c&&(f.trigger("ajaxComplete",[E,p]),--oe.active||oe.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var o,r,i,a,l,s,c,u,p=oe.ajaxSetup({},t),d=p.context||p,f=p.context&&(d.nodeType||d.jquery)?oe(d):oe.event,h=oe.Deferred(),g=oe.Callbacks("once memory"),b=p.statusCode||{},m={},v={},y=0,x="canceled",E={readyState:0,getResponseHeader:function(e){var t;if(2===y){if(!a)for(a={};t=mt.exec(i);)a[t[1].toLowerCase()]=t[2];t=a[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===y?i:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return y||(e=v[n]=v[n]||e,m[e]=t),this},overrideMimeType:function(e){return y||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>y)for(t in e)b[t]=[b[t],e[t]];else E.always(e[E.status]);return this},abort:function(e){var t=e||x;return o&&o.abort(t),n(0,t),this}};if(h.promise(E).complete=g.add,E.success=E.done,E.error=E.fail,p.url=((e||p.url||Ct)+"").replace(gt,"").replace(xt,_t[1]+"//"),p.type=t.method||t.type||p.method||p.type,p.dataTypes=oe.trim(p.dataType||"*").toLowerCase().match(me)||[""],null==p.crossDomain&&(s=Et.exec(p.url.toLowerCase()),p.crossDomain=!(!s||s[1]===_t[1]&&s[2]===_t[2]&&(s[3]||("http:"===s[1]?"80":"443"))===(_t[3]||("http:"===_t[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=oe.param(p.data,p.traditional)),F(wt,p,t,E),2===y)return E;c=oe.event&&p.global,c&&0===oe.active++&&oe.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!yt.test(p.type),r=p.url,p.hasContent||(p.data&&(r=p.url+=(ht.test(r)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=bt.test(r)?r.replace(bt,"$1_="+ft++):r+(ht.test(r)?"&":"?")+"_="+ft++)),p.ifModified&&(oe.lastModified[r]&&E.setRequestHeader("If-Modified-Since",oe.lastModified[r]),oe.etag[r]&&E.setRequestHeader("If-None-Match",oe.etag[r])),(p.data&&p.hasContent&&p.contentType!==!1||t.contentType)&&E.setRequestHeader("Content-Type",p.contentType),E.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+kt+"; q=0.01":""):p.accepts["*"]);for(u in p.headers)E.setRequestHeader(u,p.headers[u]);if(p.beforeSend&&(p.beforeSend.call(d,E,p)===!1||2===y))return E.abort();x="abort";for(u in{success:1,error:1,complete:1})E[u](p[u]);if(o=F(Nt,p,t,E)){E.readyState=1,c&&f.trigger("ajaxSend",[E,p]),p.async&&p.timeout>0&&(l=setTimeout(function(){E.abort("timeout")},p.timeout));try{y=1,o.send(m,n)}catch(w){if(!(2>y))throw w;n(-1,w)}}else n(-1,"No Transport");return E},getJSON:function(e,t,n){return oe.get(e,t,n,"json")},getScript:function(e,t){return oe.get(e,void 0,t,"script")}}),oe.each(["get","post"],function(e,t){oe[t]=function(e,n,o,r){return oe.isFunction(n)&&(r=r||o,o=n,n=void 0),oe.ajax({url:e,type:t,dataType:r,data:n,success:o})}}),oe._evalUrl=function(e){return oe.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},oe.fn.extend({wrapAll:function(e){var t;return oe.isFunction(e)?this.each(function(t){oe(this).wrapAll(e.call(this,t))}):(this[0]&&(t=oe(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstElementChild;)e=e.firstElementChild;return e}).append(this)),this)},wrapInner:function(e){return oe.isFunction(e)?this.each(function(t){oe(this).wrapInner(e.call(this,t))}):this.each(function(){var t=oe(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=oe.isFunction(e);return this.each(function(n){oe(this).wrapAll(t?e.call(this,n):e); })},unwrap:function(){return this.parent().each(function(){oe.nodeName(this,"body")||oe(this).replaceWith(this.childNodes)}).end()}}),oe.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0},oe.expr.filters.visible=function(e){return!oe.expr.filters.hidden(e)};var Dt=/%20/g,Ot=/\[\]$/,Tt=/\r?\n/g,Rt=/^(?:submit|button|image|reset|file)$/i,Mt=/^(?:input|select|textarea|keygen)/i;oe.param=function(e,t){var n,o=[],r=function(e,t){t=oe.isFunction(t)?t():null==t?"":t,o[o.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=oe.ajaxSettings&&oe.ajaxSettings.traditional),oe.isArray(e)||e.jquery&&!oe.isPlainObject(e))oe.each(e,function(){r(this.name,this.value)});else for(n in e)z(n,e[n],t,r);return o.join("&").replace(Dt,"+")},oe.fn.extend({serialize:function(){return oe.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=oe.prop(this,"elements");return e?oe.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!oe(this).is(":disabled")&&Mt.test(this.nodeName)&&!Rt.test(e)&&(this.checked||!Oe.test(e))}).map(function(e,t){var n=oe(this).val();return null==n?null:oe.isArray(n)?oe.map(n,function(e){return{name:t.name,value:e.replace(Tt,"\r\n")}}):{name:t.name,value:n.replace(Tt,"\r\n")}}).get()}}),oe.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(e){}};var Pt=0,St={},It={0:200,1223:204},At=oe.ajaxSettings.xhr();n.attachEvent&&n.attachEvent("onunload",function(){for(var e in St)St[e]()}),ee.cors=!!At&&"withCredentials"in At,ee.ajax=At=!!At,oe.ajaxTransport(function(e){var t;return ee.cors||At&&!e.crossDomain?{send:function(n,o){var r,i=e.xhr(),a=++Pt;if(i.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(r in e.xhrFields)i[r]=e.xhrFields[r];e.mimeType&&i.overrideMimeType&&i.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(r in n)i.setRequestHeader(r,n[r]);t=function(e){return function(){t&&(delete St[a],t=i.onload=i.onerror=null,"abort"===e?i.abort():"error"===e?o(i.status,i.statusText):o(It[i.status]||i.status,i.statusText,"string"==typeof i.responseText?{text:i.responseText}:void 0,i.getAllResponseHeaders()))}},i.onload=t(),i.onerror=t("error"),t=St[a]=t("abort");try{i.send(e.hasContent&&e.data||null)}catch(l){if(t)throw l}},abort:function(){t&&t()}}:void 0}),oe.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return oe.globalEval(e),e}}}),oe.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),oe.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(o,r){t=oe("<script>").prop({async:!0,charset:e.scriptCharset,src:e.url}).on("load error",n=function(e){t.remove(),n=null,e&&r("error"===e.type?404:200,e.type)}),te.head.appendChild(t[0])},abort:function(){n&&n()}}}});var jt=[],Lt=/(=)\?(?=&|$)|\?\?/;oe.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=jt.pop()||oe.expando+"_"+ft++;return this[e]=!0,e}}),oe.ajaxPrefilter("json jsonp",function(e,t,o){var r,i,a,l=e.jsonp!==!1&&(Lt.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Lt.test(e.data)&&"data");return l||"jsonp"===e.dataTypes[0]?(r=e.jsonpCallback=oe.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,l?e[l]=e[l].replace(Lt,"$1"+r):e.jsonp!==!1&&(e.url+=(ht.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return a||oe.error(r+" was not called"),a[0]},e.dataTypes[0]="json",i=n[r],n[r]=function(){a=arguments},o.always(function(){n[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,jt.push(r)),a&&oe.isFunction(i)&&i(a[0]),a=i=void 0}),"script"):void 0}),oe.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||te;var o=ue.exec(e),r=!n&&[];return o?[t.createElement(o[1])]:(o=oe.buildFragment([e],t,r),r&&r.length&&oe(r).remove(),oe.merge([],o.childNodes))};var Vt=oe.fn.load;oe.fn.load=function(e,t,n){if("string"!=typeof e&&Vt)return Vt.apply(this,arguments);var o,r,i,a=this,l=e.indexOf(" ");return l>=0&&(o=oe.trim(e.slice(l)),e=e.slice(0,l)),oe.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(r="POST"),a.length>0&&oe.ajax({url:e,type:r,dataType:"html",data:t}).done(function(e){i=arguments,a.html(o?oe("<div>").append(oe.parseHTML(e)).find(o):e)}).complete(n&&function(e,t){a.each(n,i||[e.responseText,t,e])}),this},oe.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){oe.fn[t]=function(e){return this.on(t,e)}}),oe.expr.filters.animated=function(e){return oe.grep(oe.timers,function(t){return e===t.elem}).length};var Ut=n.document.documentElement;oe.offset={setOffset:function(e,t,n){var o,r,i,a,l,s,c,u=oe.css(e,"position"),p=oe(e),d={};"static"===u&&(e.style.position="relative"),l=p.offset(),i=oe.css(e,"top"),s=oe.css(e,"left"),c=("absolute"===u||"fixed"===u)&&(i+s).indexOf("auto")>-1,c?(o=p.position(),a=o.top,r=o.left):(a=parseFloat(i)||0,r=parseFloat(s)||0),oe.isFunction(t)&&(t=t.call(e,n,l)),null!=t.top&&(d.top=t.top-l.top+a),null!=t.left&&(d.left=t.left-l.left+r),"using"in t?t.using.call(e,d):p.css(d)}},oe.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){oe.offset.setOffset(this,e,t)});var t,n,o=this[0],r={top:0,left:0},i=o&&o.ownerDocument;if(i)return t=i.documentElement,oe.contains(t,o)?(typeof o.getBoundingClientRect!==Te&&(r=o.getBoundingClientRect()),n=W(i),{top:r.top+n.pageYOffset-t.clientTop,left:r.left+n.pageXOffset-t.clientLeft}):r},position:function(){if(this[0]){var e,t,n=this[0],o={top:0,left:0};return"fixed"===oe.css(n,"position")?t=n.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),oe.nodeName(e[0],"html")||(o=e.offset()),o.top+=oe.css(e[0],"borderTopWidth",!0),o.left+=oe.css(e[0],"borderLeftWidth",!0)),{top:t.top-o.top-oe.css(n,"marginTop",!0),left:t.left-o.left-oe.css(n,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||Ut;e&&!oe.nodeName(e,"html")&&"static"===oe.css(e,"position");)e=e.offsetParent;return e||Ut})}}),oe.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var o="pageYOffset"===t;oe.fn[e]=function(r){return xe(this,function(e,r,i){var a=W(e);return void 0===i?a?a[t]:e[r]:void(a?a.scrollTo(o?n.pageXOffset:i,o?i:n.pageYOffset):e[r]=i)},e,r,arguments.length,null)}}),oe.each(["top","left"],function(e,t){oe.cssHooks[t]=_(ee.pixelPosition,function(e,n){return n?(n=C(e,t),Ye.test(n)?oe(e).position()[t]+"px":n):void 0})}),oe.each({Height:"height",Width:"width"},function(e,t){oe.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,o){oe.fn[o]=function(o,r){var i=arguments.length&&(n||"boolean"!=typeof o),a=n||(o===!0||r===!0?"margin":"border");return xe(this,function(t,n,o){var r;return oe.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(r=t.documentElement,Math.max(t.body["scroll"+e],r["scroll"+e],t.body["offset"+e],r["offset"+e],r["client"+e])):void 0===o?oe.css(t,n,a):oe.style(t,n,o,a)},t,i?o:void 0,i,null)}})}),oe.fn.size=function(){return this.length},oe.fn.andSelf=oe.fn.addBack,o=[],r=function(){return oe}.apply(t,o),!(void 0!==r&&(e.exports=r));var Ft=n.jQuery,Bt=n.$;return oe.noConflict=function(e){return n.$===oe&&(n.$=Bt),e&&n.jQuery===oe&&(n.jQuery=Ft),oe},typeof i===Te&&(n.jQuery=n.$=oe),oe})},function(e,t,n){try{(function(){"use strict";function t(e){return e&&e.__esModule?e:{"default":e}}var o=n(7),r=t(o),i=n(46),a=r["default"].createClass({displayName:"App",render:function(){return r["default"].createElement("div",{className:"container"},r["default"].createElement("h1",{className:"text-center"},"Search Engine"),r["default"].createElement(i.RouteHandler,null))}});e.exports=a}).call(this)}finally{}},function(e,t,n){try{(function(){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=function(e,t,n){for(var o=!0;o;){var r=e,i=t,a=n;l=c=s=void 0,o=!1,null===r&&(r=Function.prototype);var l=Object.getOwnPropertyDescriptor(r,i);if(void 0!==l){if("value"in l)return l.value;var s=l.get;return void 0===s?void 0:s.call(a)}var c=Object.getPrototypeOf(r);if(null===c)return void 0;e=c,t=i,n=a,o=!0}},s=n(7),c=o(s),u=n(34),p=o(u),d=function(e){function t(){r(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).call(this);var e=p["default"].getContent();this.state={content:e}}return i(t,e),a(t,[{key:"render",value:function(){var e={fontFamily:"Arial",fontSize:"20"};return c["default"].createElement("div",{style:e,className:"content"},this.state.content)}}]),t}(c["default"].Component);t["default"]=d,e.exports=t["default"]}).call(this)}finally{}},function(e,t,n){try{(function(){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=function(e,t,n){for(var o=!0;o;){var r=e,i=t,a=n;l=c=s=void 0,o=!1,null===r&&(r=Function.prototype);var l=Object.getOwnPropertyDescriptor(r,i);if(void 0!==l){if("value"in l)return l.value;var s=l.get;return void 0===s?void 0:s.call(a)}var c=Object.getPrototypeOf(r);if(null===c)return void 0;e=c,t=i,n=a,o=!0}},s=n(7),c=o(s),u=n(112),p=o(u),d=n(70),f=o(d),h=n(34),g=o(h),b=function(e){function t(){r(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).call(this),this.state={documents:!1}}return i(t,e),a(t,[{key:"handleSubmit",value:function(e){e.preventDefault();var t=document.getElementById("request").value;f["default"].fetchDocuments(t)}},{key:"onChange",value:function(){var e=g["default"].getDocuments();e===[]&&(e=!1),this.setState({documents:e})}},{key:"conponentWillUnmount",value:function(){this.setState({})}},{key:"componentDidMount",value:function(){g["default"].onChange=this.onChange.bind(this)}},{key:"render",value:function(){return c["default"].createElement("div",{className:"container"},c["default"].createElement("form",{className:"homePage",onSubmit:this.handleSubmit,action:"return false;"},c["default"].createElement("input",{type:"text",className:"form-control",id:"request",placeholder:"your request"}),c["default"].createElement("input",{className:"btn btn-default",type:"submit",value:"search"})),c["default"].createElement(p["default"],{list:this.state.documents}))}}]),t}(c["default"].Component);t["default"]=b,e.exports=t["default"]}).call(this)}finally{}},function(e,t,n){try{(function(){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=function(e,t,n){for(var o=!0;o;){var r=e,i=t,a=n;l=c=s=void 0,o=!1,null===r&&(r=Function.prototype);var l=Object.getOwnPropertyDescriptor(r,i);if(void 0!==l){if("value"in l)return l.value;var s=l.get;return void 0===s?void 0:s.call(a)}var c=Object.getPrototypeOf(r);if(null===c)return void 0;e=c,t=i,n=a,o=!0}},s=n(7),c=o(s),u=n(114),p=o(u),d=n(46),f=n(70),h=o(f),g=n(34),b=o(g),m=function(e){function t(){r(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),a(t,[{key:"handleClick",value:function(e){e.preventDefault(),h["default"].fetchContent(e.target.textContent)}},{key:"onChange",value:function(){this.transitionTo("content")}},{key:"componentDidMount",value:function(){b["default"].onChangeContent=this.onChange.bind(this)}},{key:"render",value:function(){var e="",t={fontFamily:"Arial",fontSize:"20"};this.props.list!==!1&&(e=this.props.list.map(function(e){return c["default"].createElement("tr",{className:"RequestList",onClick:this.handleClick},c["default"].createElement("th",null," ",e.document," "),c["default"].createElement("th",null,e.ponderation))}.bind(this)));var n=c["default"].createElement("table",{className:"table"},c["default"].createElement("thead",null,c["default"].createElement("tr",null,c["default"].createElement("th",null,"Document Name"),c["default"].createElement("th",null,"Ponderation "))),c["default"].createElement("tbody",null,e));return c["default"].createElement("div",{style:t},this.props.list!==!1?{tableInstance:n}:{RequestNode:e})}}]),t}(c["default"].Component);t["default"]=m,p["default"].onClass(m,d.Navigation),e.exports=t["default"]}).call(this)}finally{}},function(e,t,n){try{(function(){"use strict";function e(e){return e&&e.__esModule?e:{"default":e}}var t=n(109),o=e(t),r=n(111),i=e(r),a=n(110),l=e(a),s=n(7),c=e(s),u=n(46),p=e(u);n(211);var d=c["default"].createElement(u.Route,{name:"app",path:"/",handler:o["default"]},c["default"].createElement(u.Route,{name:"content",handler:l["default"]}),c["default"].createElement(u.Route,{name:"home",handler:i["default"]}),c["default"].createElement(u.DefaultRoute,{handler:i["default"]}));p["default"].run(d,p["default"].HashLocalion,function(e){c["default"].render(c["default"].createElement(e,null),document.body)})}).call(this)}finally{}},function(e,t,n){function o(e){var t=e.getDefaultProps;t&&(e.defaultProps=t(),delete e.getDefaultProps)}function r(e){function t(e){var t=e.state||{};l(t,n.call(e)),e.state=t}var n=e.getInitialState,o=e.componentWillMount;n&&(o?e.componentWillMount=function(){t(this),o.call(this)}:e.componentWillMount=function(){t(this)},delete e.getInitialState)}function i(e,t){o(t),r(t);var n={},l={};Object.keys(t).forEach(function(e){"mixins"!==e&&"statics"!==e&&("function"==typeof t[e]?n[e]=t[e]:l[e]=t[e])}),s(e.prototype,n);var c=function(e,t,n){if(!e)return t;if(!t)return e;var o={};return Object.keys(e).forEach(function(n){t[n]||(o[n]=e[n])}),Object.keys(t).forEach(function(n){e[n]?o[n]=function(){return t[n].apply(this,arguments)&&e[n].apply(this,arguments)}:o[n]=t[n]}),o};return a({childContextTypes:c,contextTypes:c,propTypes:a.MANY_MERGED_LOOSE,defaultProps:a.MANY_MERGED_LOOSE})(e,l),t.statics&&Object.getOwnPropertyNames(t.statics).forEach(function(n){var o=e[n],r=t.statics[n];if(void 0!==o&&void 0!==r)throw new TypeError("Cannot mixin statics because statics."+n+" and Component."+n+" are defined.");e[n]=void 0!==o?o:r}),t.mixins&&t.mixins.reverse().forEach(i.bind(null,e)),e}var a=n(116),l=n(115),s=a({componentDidMount:a.MANY,componentWillMount:a.MANY,componentWillReceiveProps:a.MANY,shouldComponentUpdate:a.ONCE,componentWillUpdate:a.MANY,componentDidUpdate:a.MANY,componentWillUnmount:a.MANY,getChildContext:a.MANY_MERGED});e.exports=function(){var e=s;return e.onClass=function(e,t){return i(e,t)},e.decorate=function(t){return function(n){return e.onClass(n,t)}},e}()},function(e,t){"use strict";function n(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=Object.assign||function(e,t){for(var o,r,i=n(e),a=1;a<arguments.length;a++){o=arguments[a],r=Object.keys(Object(o));for(var l=0;l<r.length;l++)i[r[l]]=o[r[l]]}return i}},function(e,t){var n=function(e){return Object.prototype.toString.call(e)},o=function(e){throw e},r=e.exports=function(e,t){function o(e,t,n){t in e?e[t]=n:Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0})}var i=t||{};return i.unknownFunction||(i.unknownFunction=r.ONCE),i.nonFunctionProperty||(i.nonFunctionProperty=function(e,t,o){if(void 0!==e&&void 0!==t){var r=function(e){return e&&e.constructor&&e.constructor.name?e.constructor.name:n(e).slice(8,-1)};throw new TypeError("Cannot mixin key "+o+" because it is provided by multiple sources, and the types are "+r(e)+" and "+r(t))}return void 0===e?t:e}),function(t,n){Object.keys(n).forEach(function(r){var a=t[r],l=n[r],s=e[r];if(void 0!==a||void 0!==l){var c=function(e){return"function"!=typeof e?e:function(){return e.call(this,arguments)}};if(s){var u=s(a,l,r);return void o(t,r,c(u))}var p="function"==typeof a,d="function"==typeof l;return p&&void 0===l||d&&void 0===a||p&&d?void o(t,r,c(i.unknownFunction(a,l,r))):void(t[r]=i.nonFunctionProperty(a,l,r))}})}};r._mergeObjects=function(e,t){var r=function(e,t){var r=n(e);if("[object Object]"!==r){var i=e.constructor?e.constructor.name:"Unknown",a=t.constructor?t.constructor.name:"Unknown";o("cannot merge returned value of type "+i+" with an "+a)}};if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);r(e,t),r(t,e);var i={};return Object.keys(e).forEach(function(n){Object.prototype.hasOwnProperty.call(t,n)&&o("cannot merge returns because both have the "+JSON.stringify(n)+" key"),i[n]=e[n]}),Object.keys(t).forEach(function(e){i[e]=t[e]}),i},r.ONCE=function(e,t,n){if(e&&t)throw new TypeError("Cannot mixin "+n+" because it has a unique constraint.");var o=e||t;return function(e){return o.apply(this,e)}},r.MANY=function(e,t,n){return function(n){return t&&t.apply(this,n),e?e.apply(this,n):void 0}},r.MANY_MERGED_LOOSE=function(e,t,n){return e&&t?r._mergeObjects(e,t):e||t},r.MANY_MERGED=function(e,t,n){return function(n){var o=t&&t.apply(this,n),i=e&&e.apply(this,n);return o&&i?r._mergeObjects(o,i):i||o}},r.REDUCE_LEFT=function(e,t,n){var o=e||function(e){return e},r=t||function(e){return e};return function(e){return r.call(this,o.apply(this,e))}},r.REDUCE_RIGHT=function(e,t,n){var o=e||function(e){return e},r=t||function(e){return e};return function(e){return o.call(this,r.apply(this,e))}}},function(e,t,n){"use strict";function o(e,t,n){var r=e.childRoutes;if(r)for(var i,s,c=0,u=r.length;u>c;++c)if(s=r[c],!s.isDefault&&!s.isNotFound&&(i=o(s,t,n)))return i.routes.unshift(e),i;var p=e.defaultRoute;if(p&&(f=a.extractParams(p.path,t)))return new l(t,f,n,[e,p]);var d=e.notFoundRoute;if(d&&(f=a.extractParams(d.path,t)))return new l(t,f,n,[e,d]);var f=a.extractParams(e.path,t);return f?new l(t,f,n,[e]):null}var r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=n(45),l=function(){function e(t,n,o,i){r(this,e),this.pathname=t,this.params=n,this.query=o,this.routes=i}return i(e,null,[{key:"findMatch",value:function(e,t){for(var n=a.withoutQuery(t),r=a.extractQuery(t),i=null,l=0,s=e.length;null==i&&s>l;++l)i=o(e[l],n,r);return i}}]),e}();e.exports=l},function(e,t,n){"use strict";var o=n(12),r={contextTypes:{router:o.router.isRequired},makePath:function(e,t,n){return this.context.router.makePath(e,t,n)},makeHref:function(e,t,n){return this.context.router.makeHref(e,t,n)},transitionTo:function(e,t,n){this.context.router.transitionTo(e,t,n)},replaceWith:function(e,t,n){this.context.router.replaceWith(e,t,n)},goBack:function(){return this.context.router.goBack()}};e.exports=r},function(e,t,n){"use strict";function o(e,t){if(!t)return!0;if(e.pathname===t.pathname)return!1;var n=e.routes,o=t.routes,r=n.filter(function(e){return-1!==o.indexOf(e)});return!r.some(function(e){return e.ignoreScrollBehavior})}var r=n(2),i=n(6).canUseDOM,a=n(125),l={statics:{recordScrollPosition:function(e){this.scrollHistory||(this.scrollHistory={}),this.scrollHistory[e]=a()},getScrollPosition:function(e){return this.scrollHistory||(this.scrollHistory={}),this.scrollHistory[e]||null}},componentWillMount:function(){r(null==this.constructor.getScrollBehavior()||i,"Cannot use scroll behavior without a DOM")},componentDidMount:function(){this._updateScroll()},componentDidUpdate:function(e,t){this._updateScroll(t)},_updateScroll:function(e){if(o(this.state,e)){var t=this.constructor.getScrollBehavior();t&&t.updateScrollPosition(this.constructor.getScrollPosition(this.state.path),this.state.action)}}};e.exports=l},function(e,t,n){"use strict";var o=n(12),r={contextTypes:{router:o.router.isRequired},getPath:function(){return this.context.router.getCurrentPath()},getPathname:function(){return this.context.router.getCurrentPathname()},getParams:function(){return this.context.router.getCurrentParams()},getQuery:function(){return this.context.router.getCurrentQuery()},getRoutes:function(){return this.context.router.getCurrentRoutes()},isActive:function(e,t,n){return this.context.router.isActive(e,t,n)}};e.exports=r},function(e,t,n){"use strict";function o(e,t){this.path=e,this.abortReason=null,this.retry=t.bind(this)}var r=n(71),i=n(72);o.prototype.abort=function(e){null==this.abortReason&&(this.abortReason=e||"ABORT")},o.prototype.redirect=function(e,t,n){this.abort(new i(e,t,n))},o.prototype.cancel=function(){this.abort(new r)},o.from=function(e,t,n,o){t.reduce(function(t,o,r){return function(i){if(i||e.abortReason)t(i);else if(o.onLeave)try{o.onLeave(e,n[r],t),o.onLeave.length<3&&t()}catch(a){t(a)}else t()}},o)()},o.to=function(e,t,n,o,r){t.reduceRight(function(t,r){return function(i){if(i||e.abortReason)t(i);else if(r.onEnter)try{r.onEnter(e,n,o,t),r.onEnter.length<4&&t()}catch(a){t(a)}else t()}},r)()},e.exports=o},function(e,t){"use strict";var n={updateScrollPosition:function(){window.scrollTo(0,0)}};e.exports=n},function(e,t,n){"use strict";var o=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},r=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),i=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},a=n(7),l=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return i(t,e),r(t,[{key:"render",value:function(){return this.props.children}}]),t}(a.Component);e.exports=l},function(e,t,n){"use strict";function o(e){return 0===e.button}function r(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var i=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},s=n(7),c=n(3),u=n(12),p=function(e){function t(){i(this,t),null!=e&&e.apply(this,arguments)}return l(t,e),a(t,[{key:"handleClick",value:function(e){var t,n=!0;this.props.onClick&&(t=this.props.onClick(e)),!r(e)&&o(e)&&((t===!1||e.defaultPrevented===!0)&&(n=!1),e.preventDefault(),n&&this.context.router.transitionTo(this.props.to,this.props.params,this.props.query))}},{key:"getHref",value:function(){return this.context.router.makeHref(this.props.to,this.props.params,this.props.query)}},{key:"getClassName",value:function(){var e=this.props.className;return this.getActiveState()&&(e+=" "+this.props.activeClassName),e}},{key:"getActiveState",value:function(){return this.context.router.isActive(this.props.to,this.props.params,this.props.query)}},{key:"render",value:function(){var e=c({},this.props,{href:this.getHref(),className:this.getClassName(),onClick:this.handleClick.bind(this)});return e.activeStyle&&this.getActiveState()&&(e.style=e.activeStyle),s.DOM.a(e,this.props.children)}}]),t}(s.Component);p.contextTypes={router:u.router.isRequired},p.propTypes={activeClassName:u.string.isRequired,to:u.oneOfType([u.string,u.route]).isRequired,params:u.object,query:u.object,activeStyle:u.object,onClick:u.func},p.defaultProps={activeClassName:"active",className:""},e.exports=p},function(e,t,n){"use strict";function o(){return r(i,"Cannot get current scroll position without a DOM"),{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}}var r=n(2),i=n(6).canUseDOM;e.exports=o},function(e,t,n){"use strict";function o(e){return null==e||i.isValidElement(e)}function r(e){return o(e)||Array.isArray(e)&&e.every(o)}var i=n(7);e.exports=r},function(e,t,n){"use strict";var o=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},r=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),i=n(2),a=n(27),l=n(22),s=function(){function e(t){o(this,e),this.history=t||[],this.listeners=[],this._updateHistoryLength()}return r(e,[{key:"needsDOM",get:function(){return!1}},{key:"_updateHistoryLength",value:function(){l.length=this.history.length}},{key:"_notifyChange",value:function(e){for(var t={path:this.getCurrentPath(),type:e},n=0,o=this.listeners.length;o>n;++n)this.listeners[n].call(this,t)}},{key:"addChangeListener",value:function(e){this.listeners.push(e)}},{key:"removeChangeListener",value:function(e){this.listeners=this.listeners.filter(function(t){return t!==e})}},{key:"push",value:function(e){this.history.push(e),this._updateHistoryLength(),this._notifyChange(a.PUSH)}},{key:"replace",value:function(e){i(this.history.length,"You cannot replace the current path with no history"),this.history[this.history.length-1]=e,this._notifyChange(a.REPLACE)}},{key:"pop",value:function(){this.history.pop(),this._updateHistoryLength(),this._notifyChange(a.POP)}},{key:"getCurrentPath",value:function(){return this.history[this.history.length-1]}},{key:"toString",value:function(){return"<TestLocation>"}}]),e}();e.exports=s},function(e,t,n){"use strict";function o(e,t,n){"function"==typeof t&&(n=t,t=null);var o=r({routes:e,location:t});return o.run(n),o}var r=n(77);e.exports=o},function(e,t){"use strict";function n(){/*! taken from modernizr * https://github.com/Modernizr/Modernizr/blob/master/LICENSE * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js * changed to avoid false negatives for Windows Phones: https://github.com/rackt/react-router/issues/586 */ var e=navigator.userAgent;return-1===e.indexOf("Android 2.")&&-1===e.indexOf("Android 4.0")||-1===e.indexOf("Mobile Safari")||-1!==e.indexOf("Chrome")||-1!==e.indexOf("Windows Phone")?window.history&&"pushState"in window.history:!1}e.exports=n},function(e,t){"use strict";function n(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=Object.assign||function(e,t){for(var o,r,i=n(e),a=1;a<arguments.length;a++){o=arguments[a],r=Object.keys(Object(o));for(var l=0;l<r.length;l++)i[r[l]]=o[r[l]]}return i}},function(e,t,n){e.exports=n(132)},function(e,t,n){var o=n(134),r=n(133);e.exports={stringify:o,parse:r}},function(e,t,n){var o=n(82),r={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3};r.parseValues=function(e,t){for(var n={},r=e.split(t.delimiter,t.parameterLimit===1/0?void 0:t.parameterLimit),i=0,a=r.length;a>i;++i){var l=r[i],s=-1===l.indexOf("]=")?l.indexOf("="):l.indexOf("]=")+1;if(-1===s)n[o.decode(l)]="";else{var c=o.decode(l.slice(0,s)),u=o.decode(l.slice(s+1));if(Object.prototype.hasOwnProperty(c))continue;n.hasOwnProperty(c)?n[c]=[].concat(n[c]).concat(u):n[c]=u}}return n},r.parseObject=function(e,t,n){if(!e.length)return t;var o=e.shift(),i={};if("[]"===o)i=[],i=i.concat(r.parseObject(e,t,n));else{var a="["===o[0]&&"]"===o[o.length-1]?o.slice(1,o.length-1):o,l=parseInt(a,10),s=""+l;!isNaN(l)&&o!==a&&s===a&&l>=0&&l<=n.arrayLimit?(i=[],i[l]=r.parseObject(e,t,n)):i[a]=r.parseObject(e,t,n)}return i},r.parseKeys=function(e,t,n){if(e){var o=/^([^\[\]]*)/,i=/(\[[^\[\]]*\])/g,a=o.exec(e);if(!Object.prototype.hasOwnProperty(a[1])){var l=[];a[1]&&l.push(a[1]);for(var s=0;null!==(a=i.exec(e))&&s<n.depth;)++s,Object.prototype.hasOwnProperty(a[1].replace(/\[|\]/g,""))||l.push(a[1]);return a&&l.push("["+e.slice(a.index)+"]"),r.parseObject(l,t,n)}}},e.exports=function(e,t){if(""===e||null===e||"undefined"==typeof e)return{};t=t||{},t.delimiter="string"==typeof t.delimiter||o.isRegExp(t.delimiter)?t.delimiter:r.delimiter,t.depth="number"==typeof t.depth?t.depth:r.depth,t.arrayLimit="number"==typeof t.arrayLimit?t.arrayLimit:r.arrayLimit,t.parameterLimit="number"==typeof t.parameterLimit?t.parameterLimit:r.parameterLimit;for(var n="string"==typeof e?r.parseValues(e,t):e,i={},a=Object.keys(n),l=0,s=a.length;s>l;++l){var c=a[l],u=r.parseKeys(c,n[c],t);i=o.merge(i,u)}return o.compact(i)}},function(e,t,n){var o=n(82),r={delimiter:"&",arrayPrefixGenerators:{brackets:function(e,t){return e+"[]"},indices:function(e,t){return e+"["+t+"]"},repeat:function(e,t){return e}}};r.stringify=function(e,t,n){if(o.isBuffer(e)?e=e.toString():e instanceof Date?e=e.toISOString():null===e&&(e=""),"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return[encodeURIComponent(t)+"="+encodeURIComponent(e)];var i=[];if("undefined"==typeof e)return i;for(var a=Object.keys(e),l=0,s=a.length;s>l;++l){var c=a[l];i=Array.isArray(e)?i.concat(r.stringify(e[c],n(t,c),n)):i.concat(r.stringify(e[c],t+"["+c+"]",n))}return i},e.exports=function(e,t){t=t||{};var n="undefined"==typeof t.delimiter?r.delimiter:t.delimiter,o=[];if("object"!=typeof e||null===e)return"";var i;i=t.arrayFormat in r.arrayPrefixGenerators?t.arrayFormat:"indices"in t?t.indices?"indices":"repeat":"indices";for(var a=r.arrayPrefixGenerators[i],l=Object.keys(e),s=0,c=l.length;c>s;++s){var u=l[s];o=o.concat(r.stringify(e[u],u,a))}return o.join(n)}},function(e,t,n){"use strict";function o(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function r(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function i(e){switch(e){case O.topCompositionStart:return T.compositionStart;case O.topCompositionEnd:return T.compositionEnd;case O.topCompositionUpdate:return T.compositionUpdate}}function a(e,t){return e===O.topKeyDown&&t.keyCode===E}function l(e,t){switch(e){case O.topKeyUp:return-1!==x.indexOf(t.keyCode);case O.topKeyDown:return t.keyCode!==E;case O.topKeyPress:case O.topMouseDown:case O.topBlur:return!0;default:return!1}}function s(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function c(e,t,n,o){var r,c;if(w?r=i(e):M?l(e,o)&&(r=T.compositionEnd):a(e,o)&&(r=T.compositionStart),!r)return null;C&&(M||r!==T.compositionStart?r===T.compositionEnd&&M&&(c=M.getData()):M=b.getPooled(t));var u=m.getPooled(r,n,o);if(c)u.data=c;else{var p=s(o);null!==p&&(u.data=p)}return h.accumulateTwoPhaseDispatches(u),u}function u(e,t){switch(e){case O.topCompositionEnd:return s(t);case O.topKeyPress:var n=t.which;return n!==_?null:(R=!0,D);case O.topTextInput:var o=t.data;return o===D&&R?null:o;default:return null}}function p(e,t){if(M){if(e===O.topCompositionEnd||l(e,t)){var n=M.getData();return b.release(M),M=null,n}return null}switch(e){case O.topPaste:return null;case O.topKeyPress:return t.which&&!r(t)?String.fromCharCode(t.which):null;case O.topCompositionEnd:return C?null:t.data;default:return null}}function d(e,t,n,o){var r;if(r=k?u(e,o):p(e,o),!r)return null;var i=v.getPooled(T.beforeInput,n,o);return i.data=r,h.accumulateTwoPhaseDispatches(i),i}var f=n(8),h=n(30),g=n(6),b=n(143),m=n(179),v=n(182),y=n(18),x=[9,13,27,32],E=229,w=g.canUseDOM&&"CompositionEvent"in window,N=null;g.canUseDOM&&"documentMode"in document&&(N=document.documentMode);var k=g.canUseDOM&&"TextEvent"in window&&!N&&!o(),C=g.canUseDOM&&(!w||N&&N>8&&11>=N),_=32,D=String.fromCharCode(_),O=f.topLevelTypes,T={beforeInput:{phasedRegistrationNames:{bubbled:y({onBeforeInput:null}),captured:y({onBeforeInputCapture:null})},dependencies:[O.topCompositionEnd,O.topKeyPress,O.topTextInput,O.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:y({onCompositionEnd:null}),captured:y({onCompositionEndCapture:null})},dependencies:[O.topBlur,O.topCompositionEnd,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:y({onCompositionStart:null}),captured:y({onCompositionStartCapture:null})},dependencies:[O.topBlur,O.topCompositionStart,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:y({onCompositionUpdate:null}),captured:y({onCompositionUpdateCapture:null})},dependencies:[O.topBlur,O.topCompositionUpdate,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]}},R=!1,M=null,P={eventTypes:T,extractEvents:function(e,t,n,o){return[c(e,t,n,o),d(e,t,n,o)]}};e.exports=P},function(e,t,n){"use strict";function o(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function r(e){var t=N.getPooled(O.change,R,e);x.accumulateTwoPhaseDispatches(t),w.batchedUpdates(i,t)}function i(e){y.enqueueEvents(e),y.processEventQueue()}function a(e,t){T=e,R=t,T.attachEvent("onchange",r)}function l(){T&&(T.detachEvent("onchange",r),T=null,R=null)}function s(e,t,n){return e===D.topChange?n:void 0}function c(e,t,n){e===D.topFocus?(l(),a(t,n)):e===D.topBlur&&l()}function u(e,t){T=e,R=t,M=e.value,P=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(T,"value",A),T.attachEvent("onpropertychange",d)}function p(){T&&(delete T.value,T.detachEvent("onpropertychange",d),T=null,R=null,M=null,P=null)}function d(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==M&&(M=t,r(e))}}function f(e,t,n){return e===D.topInput?n:void 0}function h(e,t,n){e===D.topFocus?(p(),u(t,n)):e===D.topBlur&&p()}function g(e,t,n){return e!==D.topSelectionChange&&e!==D.topKeyUp&&e!==D.topKeyDown||!T||T.value===M?void 0:(M=T.value,R)}function b(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function m(e,t,n){return e===D.topClick?n:void 0}var v=n(8),y=n(29),x=n(30),E=n(6),w=n(11),N=n(21),k=n(66),C=n(104),_=n(18),D=v.topLevelTypes,O={change:{phasedRegistrationNames:{bubbled:_({onChange:null}),captured:_({onChangeCapture:null})},dependencies:[D.topBlur,D.topChange,D.topClick,D.topFocus,D.topInput,D.topKeyDown,D.topKeyUp,D.topSelectionChange]}},T=null,R=null,M=null,P=null,S=!1;E.canUseDOM&&(S=k("change")&&(!("documentMode"in document)||document.documentMode>8));var I=!1;E.canUseDOM&&(I=k("input")&&(!("documentMode"in document)||document.documentMode>9));var A={get:function(){return P.get.call(this)},set:function(e){M=""+e,P.set.call(this,e)}},j={eventTypes:O,extractEvents:function(e,t,n,r){var i,a;if(o(t)?S?i=s:a=c:C(t)?I?i=f:(i=g,a=h):b(t)&&(i=m),i){var l=i(e,t,n);if(l){var u=N.getPooled(O.change,l,r);return x.accumulateTwoPhaseDispatches(u),u}}a&&a(e,t,n)}};e.exports=j},function(e,t){"use strict";var n=0,o={createReactRootIndex:function(){return n++}};e.exports=o},function(e,t,n){(function(t){"use strict";function o(e,t,n){e.insertBefore(t,e.childNodes[n]||null)}var r=n(139),i=n(91),a=n(207),l=n(2),s={dangerouslyReplaceNodeWithMarkup:r.dangerouslyReplaceNodeWithMarkup,updateTextContent:a,processUpdates:function(e,n){for(var s,c=null,u=null,p=0;p<e.length;p++)if(s=e[p],s.type===i.MOVE_EXISTING||s.type===i.REMOVE_NODE){var d=s.fromIndex,f=s.parentNode.childNodes[d],h=s.parentID;"production"!==t.env.NODE_ENV?l(f,"processUpdates(): Unable to find child %s of element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID `%s`.",d,h):l(f),c=c||{},c[h]=c[h]||[],c[h][d]=f,u=u||[],u.push(f)}var g=r.dangerouslyRenderMarkup(n);if(u)for(var b=0;b<u.length;b++)u[b].parentNode.removeChild(u[b]);for(var m=0;m<e.length;m++)switch(s=e[m],s.type){case i.INSERT_MARKUP:o(s.parentNode,g[s.markupIndex],s.toIndex);break;case i.MOVE_EXISTING:o(s.parentNode,c[s.parentID][s.fromIndex],s.toIndex);break;case i.TEXT_CONTENT:a(s.parentNode,s.textContent);break;case i.REMOVE_NODE:}}};e.exports=s}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e){return e.substring(1,e.indexOf(" "))}var r=n(6),i=n(191),a=n(17),l=n(101),s=n(2),c=/^(<[^ \/>]+)/,u="data-danger-index",p={dangerouslyRenderMarkup:function(e){"production"!==t.env.NODE_ENV?s(r.canUseDOM,"dangerouslyRenderMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use React.renderToString for server rendering."):s(r.canUseDOM);for(var n,p={},d=0;d<e.length;d++)"production"!==t.env.NODE_ENV?s(e[d],"dangerouslyRenderMarkup(...): Missing markup."):s(e[d]),n=o(e[d]),n=l(n)?n:"*",p[n]=p[n]||[],p[n][d]=e[d];var f=[],h=0;for(n in p)if(p.hasOwnProperty(n)){var g,b=p[n];for(g in b)if(b.hasOwnProperty(g)){var m=b[g];b[g]=m.replace(c,"$1 "+u+'="'+g+'" ')}for(var v=i(b.join(""),a),y=0;y<v.length;++y){var x=v[y];x.hasAttribute&&x.hasAttribute(u)?(g=+x.getAttribute(u),x.removeAttribute(u),"production"!==t.env.NODE_ENV?s(!f.hasOwnProperty(g),"Danger: Assigning to an already-occupied result index."):s(!f.hasOwnProperty(g)),f[g]=x,h+=1):"production"!==t.env.NODE_ENV&&console.error("Danger: Discarding unexpected node:",x)}}return"production"!==t.env.NODE_ENV?s(h===f.length,"Danger: Did not assign to every index of resultList."):s(h===f.length),"production"!==t.env.NODE_ENV?s(f.length===e.length,"Danger: Expected markup to render %s nodes, but rendered %s.",e.length,f.length):s(f.length===e.length),f},dangerouslyReplaceNodeWithMarkup:function(e,n){"production"!==t.env.NODE_ENV?s(r.canUseDOM,"dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use React.renderToString for server rendering."):s(r.canUseDOM),"production"!==t.env.NODE_ENV?s(n,"dangerouslyReplaceNodeWithMarkup(...): Missing markup."):s(n),"production"!==t.env.NODE_ENV?s("html"!==e.tagName.toLowerCase(),"dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See React.renderToString()."):s("html"!==e.tagName.toLowerCase());var o=i(n,a)[0];e.parentNode.replaceChild(o,e)}};e.exports=p}).call(t,n(1))},function(e,t,n){"use strict";var o=n(18),r=[o({ResponderEventPlugin:null}),o({SimpleEventPlugin:null}),o({TapEventPlugin:null}),o({EnterLeaveEventPlugin:null}),o({ChangeEventPlugin:null}),o({SelectEventPlugin:null}),o({BeforeInputEventPlugin:null}),o({AnalyticsEventPlugin:null}),o({MobileSafariClickEventPlugin:null})];e.exports=r},function(e,t,n){"use strict";var o=n(8),r=n(30),i=n(41),a=n(10),l=n(18),s=o.topLevelTypes,c=a.getFirstReactDOM,u={mouseEnter:{registrationName:l({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:l({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},p=[null,null],d={eventTypes:u,extractEvents:function(e,t,n,o){if(e===s.topMouseOver&&(o.relatedTarget||o.fromElement))return null;if(e!==s.topMouseOut&&e!==s.topMouseOver)return null;var l;if(t.window===t)l=t;else{var d=t.ownerDocument;l=d?d.defaultView||d.parentWindow:window}var f,h;if(e===s.topMouseOut?(f=t,h=c(o.relatedTarget||o.toElement)||l):(f=l,h=t),f===h)return null;var g=f?a.getID(f):"",b=h?a.getID(h):"",m=i.getPooled(u.mouseLeave,g,o);m.type="mouseleave",m.target=f,m.relatedTarget=h;var v=i.getPooled(u.mouseEnter,b,o);return v.type="mouseenter",v.target=h,v.relatedTarget=f,r.accumulateEnterLeaveDispatches(m,v,g,b),p[0]=m,p[1]=v,p}};e.exports=d},function(e,t,n){(function(t){var o=n(17),r={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,n,r){return e.addEventListener?(e.addEventListener(n,r,!0),{remove:function(){e.removeEventListener(n,r,!0)}}):("production"!==t.env.NODE_ENV&&console.error("Attempted to listen to events during the capture phase on a browser that does not support the capture phase. Your application will not receive some events."),{remove:o})},registerDefault:function(){}};e.exports=r}).call(t,n(1))},function(e,t,n){"use strict";function o(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var r=n(13),i=n(3),a=n(102);i(o.prototype,{getText:function(){return"value"in this._root?this._root.value:this._root[a()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,o=n.length,r=this.getText(),i=r.length;for(e=0;o>e&&n[e]===r[e];e++);var a=o-e;for(t=1;a>=t&&n[o-t]===r[i-t];t++);var l=t>1?1-t:void 0;return this._fallbackText=r.slice(e,l),this._fallbackText}}),r.addPoolingTo(o),e.exports=o},function(e,t,n){"use strict";var o,r=n(20),i=n(6),a=r.injection.MUST_USE_ATTRIBUTE,l=r.injection.MUST_USE_PROPERTY,s=r.injection.HAS_BOOLEAN_VALUE,c=r.injection.HAS_SIDE_EFFECTS,u=r.injection.HAS_NUMERIC_VALUE,p=r.injection.HAS_POSITIVE_NUMERIC_VALUE,d=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(i.canUseDOM){var f=document.implementation;o=f&&f.hasFeature&&f.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var h={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:a|s,allowTransparency:a,alt:null,async:s,autoComplete:null,autoPlay:s,cellPadding:null,cellSpacing:null,charSet:a,checked:l|s,classID:a,className:o?a:l,cols:a|p,colSpan:null,content:null,contentEditable:null,contextMenu:a,controls:l|s,coords:null,crossOrigin:null,data:null,dateTime:a,defer:s,dir:null,disabled:a|s,download:d,draggable:null,encType:null,form:a,formAction:a,formEncType:a,formMethod:a,formNoValidate:s,formTarget:a,frameBorder:a,headers:null,height:a,hidden:a|s,high:null,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:l,label:null,lang:null,list:a,loop:l|s,low:null,manifest:a,marginHeight:null,marginWidth:null,max:null,maxLength:a,media:a,mediaGroup:null,method:null,min:null,multiple:l|s,muted:l|s,name:null,noValidate:s,open:s,optimum:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:l|s,rel:null,required:s,role:a,rows:a|p,rowSpan:null,sandbox:null,scope:null,scoped:s,scrolling:null,seamless:a|s,selected:l|s,shape:null,size:a|p,sizes:a,span:p,spellCheck:null,src:null,srcDoc:l,srcSet:a,start:u,step:null,style:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:l|c,width:a,wmode:a,autoCapitalize:null,autoCorrect:null,itemProp:a,itemScope:a|s,itemType:a,itemID:a,itemRef:a,property:null,unselectable:a},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};e.exports=h},function(e,t,n){"use strict";var o=n(8),r=n(17),i=o.topLevelTypes,a={eventTypes:null,extractEvents:function(e,t,n,o){if(e===i.topTouchStart){var a=o.target;a&&!a.onclick&&(a.onclick=r)}}};e.exports=a},function(e,t,n){(function(t){"use strict";var o=n(49),r=n(148),i=n(86),a=n(9),l=n(54),s=n(15),c=n(5),u=n(31),p=n(150),d=n(88),f=n(161),h=n(24),g=n(10),b=n(16),m=n(92),v=n(26),y=n(172),x=n(3),E=n(97),w=n(203);f.inject();var N=c.createElement,k=c.createFactory,C=c.cloneElement;"production"!==t.env.NODE_ENV&&(N=u.createElement,k=u.createFactory,C=u.cloneElement);var _=b.measure("React","render",g.render),D={Children:{map:r.map,forEach:r.forEach,count:r.count,only:w},Component:i,DOM:p,PropTypes:m,initializeTouchEvents:function(e){o.useTouchEvents=e},createClass:a.createClass,createElement:N,cloneElement:C,createFactory:k,createMixin:function(e){return e},constructAndRenderComponent:g.constructAndRenderComponent,constructAndRenderComponentByID:g.constructAndRenderComponentByID,findDOMNode:E,render:_,renderToString:y.renderToString,renderToStaticMarkup:y.renderToStaticMarkup,unmountComponentAtNode:g.unmountComponentAtNode,isValidElement:c.isValidElement,withContext:l.withContext,__spread:x};if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({CurrentOwner:s,InstanceHandles:h,Mount:g,Reconciler:v,TextComponent:d}),"production"!==t.env.NODE_ENV){var O=n(6);if(O.canUseDOM&&window.top===window.self){navigator.userAgent.indexOf("Chrome")>-1&&"undefined"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&console.debug("Download the React DevTools for a better development experience: https://fb.me/react-devtools");for(var T=[Array.isArray,Array.prototype.every,Array.prototype.forEach,Array.prototype.indexOf,Array.prototype.map,Date.now,Function.prototype.bind,Object.keys,String.prototype.split,String.prototype.trim,Object.create,Object.freeze],R=0;R<T.length;R++)if(!T[R]){console.error("One or more ES5 shim/shams expected by React are not available: https://fb.me/react-warning-polyfills");break}}}D.version="0.13.3",e.exports=D}).call(t,n(1))},function(e,t,n){"use strict";var o=n(26),r=n(193),i=n(65),a=n(68),l={instantiateChildren:function(e,t,n){var o=r(e);for(var a in o)if(o.hasOwnProperty(a)){var l=o[a],s=i(l,null);o[a]=s}return o},updateChildren:function(e,t,n,l){var s=r(t);if(!s&&!e)return null;var c;for(c in s)if(s.hasOwnProperty(c)){var u=e&&e[c],p=u&&u._currentElement,d=s[c];if(a(p,d))o.receiveComponent(u,d,n,l),s[c]=u;else{u&&o.unmountComponent(u,c);var f=i(d,null);s[c]=f}}for(c in e)!e.hasOwnProperty(c)||s&&s.hasOwnProperty(c)||o.unmountComponent(e[c]);return s},unmountChildren:function(e){for(var t in e){var n=e[t];o.unmountComponent(n)}}};e.exports=l},function(e,t,n){(function(t){"use strict";function o(e,t){this.forEachFunction=e,this.forEachContext=t}function r(e,t,n,o){var r=e;r.forEachFunction.call(r.forEachContext,t,o)}function i(e,t,n){if(null==e)return e;var i=o.getPooled(t,n);f(e,r,i),o.release(i)}function a(e,t,n){this.mapResult=e,this.mapFunction=t,this.mapContext=n}function l(e,n,o,r){var i=e,a=i.mapResult,l=!a.hasOwnProperty(o);if("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?h(l,"ReactChildren.map(...): Encountered two children with the same key, `%s`. Child keys must be unique; when two children share a key, only the first child will be used.",o):null),l){var s=i.mapFunction.call(i.mapContext,n,r);a[o]=s}}function s(e,t,n){if(null==e)return e;var o={},r=a.getPooled(o,t,n);return f(e,l,r),a.release(r),d.create(o)}function c(e,t,n,o){return null}function u(e,t){return f(e,c,null)}var p=n(13),d=n(38),f=n(105),h=n(4),g=p.twoArgumentPooler,b=p.threeArgumentPooler;p.addPoolingTo(o,g),p.addPoolingTo(a,b);var m={forEach:i,map:s,count:u};e.exports=m}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}var r=n(53),i=n(54),a=n(15),l=n(5),s=n(31),c=n(25),u=n(57),p=n(39),d=n(16),f=n(58),h=n(40),g=n(26),b=n(11),m=n(3),v=n(43),y=n(2),x=n(68),E=n(4),w=1,N={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._isTopLevel=!1,this._pendingCallbacks=null},mountComponent:function(e,n,o){this._context=o,this._mountOrder=w++,this._rootNodeID=e;var r=this._processProps(this._currentElement.props),i=this._processContext(this._currentElement._context),a=p.getComponentClassForElement(this._currentElement),l=new a(r,i);"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?E(null!=l.render,"%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render` in your component or you may have accidentally tried to render an element whose type is a function that isn't a React component.",a.displayName||a.name||"Component"):null),l.props=r,l.context=i,l.refs=v,this._instance=l,c.set(l,this),"production"!==t.env.NODE_ENV&&this._warnIfContextsDiffer(this._currentElement._context,o),"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?E(!l.getInitialState||l.getInitialState.isReactClassApproved,"getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?",this.getName()||"a component"):null,"production"!==t.env.NODE_ENV?E(!l.getDefaultProps||l.getDefaultProps.isReactClassApproved,"getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.",this.getName()||"a component"):null,"production"!==t.env.NODE_ENV?E(!l.propTypes,"propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.",this.getName()||"a component"):null,"production"!==t.env.NODE_ENV?E(!l.contextTypes,"contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.",this.getName()||"a component"):null,"production"!==t.env.NODE_ENV?E("function"!=typeof l.componentShouldUpdate,"%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",this.getName()||"A component"):null);var s=l.state;void 0===s&&(l.state=s=null),"production"!==t.env.NODE_ENV?y("object"==typeof s&&!Array.isArray(s),"%s.state: must be set to an object or null",this.getName()||"ReactCompositeComponent"):y("object"==typeof s&&!Array.isArray(s)),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var d,f,h=u.currentlyMountingInstance;u.currentlyMountingInstance=this;try{l.componentWillMount&&(l.componentWillMount(),this._pendingStateQueue&&(l.state=this._processPendingState(l.props,l.context))),d=this._getValidatedChildContext(o),f=this._renderValidatedComponent(d)}finally{u.currentlyMountingInstance=h}this._renderedComponent=this._instantiateReactComponent(f,this._currentElement.type);var b=g.mountComponent(this._renderedComponent,e,n,this._mergeChildContext(o,d));return l.componentDidMount&&n.getReactMountReady().enqueue(l.componentDidMount,l),b},unmountComponent:function(){var e=this._instance;if(e.componentWillUnmount){var t=u.currentlyUnmountingInstance;u.currentlyUnmountingInstance=this;try{e.componentWillUnmount()}finally{u.currentlyUnmountingInstance=t}}g.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,c.remove(e)},_setPropsInternal:function(e,t){var n=this._pendingElement||this._currentElement;this._pendingElement=l.cloneAndReplaceProps(n,m({},n.props,e)),b.enqueueUpdate(this,t)},_maskContext:function(e){var t=null;if("string"==typeof this._currentElement.type)return v;var n=this._currentElement.type.contextTypes;if(!n)return v;t={};for(var o in n)t[o]=e[o];return t},_processContext:function(e){var n=this._maskContext(e);if("production"!==t.env.NODE_ENV){var o=p.getComponentClassForElement(this._currentElement);o.contextTypes&&this._checkPropTypes(o.contextTypes,n,f.context)}return n},_getValidatedChildContext:function(e){var n=this._instance,o=n.getChildContext&&n.getChildContext();if(o){"production"!==t.env.NODE_ENV?y("object"==typeof n.constructor.childContextTypes,"%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().",this.getName()||"ReactCompositeComponent"):y("object"==typeof n.constructor.childContextTypes),"production"!==t.env.NODE_ENV&&this._checkPropTypes(n.constructor.childContextTypes,o,f.childContext);for(var r in o)"production"!==t.env.NODE_ENV?y(r in n.constructor.childContextTypes,'%s.getChildContext(): key "%s" is not defined in childContextTypes.',this.getName()||"ReactCompositeComponent",r):y(r in n.constructor.childContextTypes);return o}return null},_mergeChildContext:function(e,t){return t?m({},e,t):e},_processProps:function(e){if("production"!==t.env.NODE_ENV){var n=p.getComponentClassForElement(this._currentElement);n.propTypes&&this._checkPropTypes(n.propTypes,e,f.prop)}return e},_checkPropTypes:function(e,n,r){var i=this.getName();for(var a in e)if(e.hasOwnProperty(a)){var l;try{"production"!==t.env.NODE_ENV?y("function"==typeof e[a],"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",i||"React class",h[r],a):y("function"==typeof e[a]),l=e[a](n,a,i,r)}catch(s){l=s}if(l instanceof Error){var c=o(this);r===f.prop?"production"!==t.env.NODE_ENV?E(!1,"Failed Composite propType: %s%s",l.message,c):null:"production"!==t.env.NODE_ENV?E(!1,"Failed Context Types: %s%s",l.message,c):null}}},receiveComponent:function(e,t,n){var o=this._currentElement,r=this._context;this._pendingElement=null,this.updateComponent(t,o,e,r,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&g.receiveComponent(this,this._pendingElement||this._currentElement,e,this._context),(null!==this._pendingStateQueue||this._pendingForceUpdate)&&("production"!==t.env.NODE_ENV&&s.checkAndWarnForMutatedProps(this._currentElement),this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context))},_warnIfContextsDiffer:function(e,n){e=this._maskContext(e),n=this._maskContext(n);for(var o=Object.keys(n).sort(),r=this.getName()||"ReactCompositeComponent",i=0;i<o.length;i++){var a=o[i];"production"!==t.env.NODE_ENV?E(e[a]===n[a],"owner-based and parent-based contexts differ (values: `%s` vs `%s`) for key (%s) while mounting %s (see: http://fb.me/react-context-by-parent)",e[a],n[a],a,r):null}},updateComponent:function(e,n,o,r,i){var a=this._instance,l=a.context,s=a.props;n!==o&&(l=this._processContext(o._context),s=this._processProps(o.props),"production"!==t.env.NODE_ENV&&null!=i&&this._warnIfContextsDiffer(o._context,i),a.componentWillReceiveProps&&a.componentWillReceiveProps(s,l));var c=this._processPendingState(s,l),u=this._pendingForceUpdate||!a.shouldComponentUpdate||a.shouldComponentUpdate(s,c,l);"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?E("undefined"!=typeof u,"%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.",this.getName()||"ReactCompositeComponent"):null),u?(this._pendingForceUpdate=!1,this._performComponentUpdate(o,s,c,l,e,i)):(this._currentElement=o,this._context=i,a.props=s,a.state=c,a.context=l)},_processPendingState:function(e,t){var n=this._instance,o=this._pendingStateQueue,r=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!o)return n.state;if(r&&1===o.length)return o[0];for(var i=m({},r?o[0]:n.state),a=r?1:0;a<o.length;a++){var l=o[a];m(i,"function"==typeof l?l.call(n,i,e,t):l)}return i},_performComponentUpdate:function(e,t,n,o,r,i){var a=this._instance,l=a.props,s=a.state,c=a.context;a.componentWillUpdate&&a.componentWillUpdate(t,n,o),this._currentElement=e,this._context=i,a.props=t,a.state=n,a.context=o,this._updateRenderedComponent(r,i),a.componentDidUpdate&&r.getReactMountReady().enqueue(a.componentDidUpdate.bind(a,l,s,c),a)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,o=n._currentElement,r=this._getValidatedChildContext(),i=this._renderValidatedComponent(r);if(x(o,i))g.receiveComponent(n,i,e,this._mergeChildContext(t,r));else{var a=this._rootNodeID,l=n._rootNodeID;g.unmountComponent(n),this._renderedComponent=this._instantiateReactComponent(i,this._currentElement.type);var s=g.mountComponent(this._renderedComponent,a,e,this._mergeChildContext(t,r));this._replaceNodeWithMarkupByID(l,s)}},_replaceNodeWithMarkupByID:function(e,t){r.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,n=e.render();return"production"!==t.env.NODE_ENV&&"undefined"==typeof n&&e.render._isMockFunction&&(n=null),n},_renderValidatedComponent:function(e){var n,o=i.current;i.current=this._mergeChildContext(this._currentElement._context,e),a.current=this;try{n=this._renderValidatedComponentWithoutOwnerOrContext()}finally{i.current=o,a.current=null}return"production"!==t.env.NODE_ENV?y(null===n||n===!1||l.isValidElement(n),"%s.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.",this.getName()||"ReactCompositeComponent"):y(null===n||n===!1||l.isValidElement(n)),n},attachRef:function(e,t){var n=this.getPublicInstance(),o=n.refs===v?n.refs={}:n.refs;o[e]=t.getPublicInstance()},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){return this._instance},_instantiateReactComponent:null};d.measureMethods(N,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var k={Mixin:N};e.exports=k}).call(t,n(1))},function(e,t,n){(function(t){"use strict";function o(e){return"production"!==t.env.NODE_ENV?i.createFactory(e):r.createFactory(e)}var r=n(5),i=n(31),a=n(201),l=a({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset", figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta",meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script",section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong",style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time",title:"title",tr:"tr",track:"track",u:"u",ul:"ul","var":"var",video:"video",wbr:"wbr",circle:"circle",clipPath:"clipPath",defs:"defs",ellipse:"ellipse",g:"g",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},o);e.exports=l}).call(t,n(1))},function(e,t,n){"use strict";var o=n(37),r=n(14),i=n(9),a=n(5),l=n(33),s=a.createFactory("button"),c=l({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),u=i.createClass({displayName:"ReactDOMButton",tagName:"BUTTON",mixins:[o,r],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&c[t]||(e[t]=this.props[t]);return s(e,this.props.children)}});e.exports=u},function(e,t,n){"use strict";var o=n(8),r=n(51),i=n(14),a=n(9),l=n(5),s=l.createFactory("form"),c=a.createClass({displayName:"ReactDOMForm",tagName:"FORM",mixins:[i,r],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(o.topLevelTypes.topReset,"reset"),this.trapBubbledEvent(o.topLevelTypes.topSubmit,"submit")}});e.exports=c},function(e,t,n){"use strict";var o=n(8),r=n(51),i=n(14),a=n(9),l=n(5),s=l.createFactory("iframe"),c=a.createClass({displayName:"ReactDOMIframe",tagName:"IFRAME",mixins:[i,r],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(o.topLevelTypes.topLoad,"load")}});e.exports=c},function(e,t,n){"use strict";var o=n(8),r=n(51),i=n(14),a=n(9),l=n(5),s=l.createFactory("img"),c=a.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[i,r],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(o.topLevelTypes.topLoad,"load"),this.trapBubbledEvent(o.topLevelTypes.topError,"error")}});e.exports=c},function(e,t,n){(function(t){"use strict";function o(){this.isMounted()&&this.forceUpdate()}var r=n(37),i=n(28),a=n(50),l=n(14),s=n(9),c=n(5),u=n(10),p=n(11),d=n(3),f=n(2),h=c.createFactory("input"),g={},b=s.createClass({displayName:"ReactDOMInput",tagName:"INPUT",mixins:[r,a.Mixin,l],getInitialState:function(){var e=this.props.defaultValue;return{initialChecked:this.props.defaultChecked||!1,initialValue:null!=e?e:null}},render:function(){var e=d({},this.props);e.defaultChecked=null,e.defaultValue=null;var t=a.getValue(this);e.value=null!=t?t:this.state.initialValue;var n=a.getChecked(this);return e.checked=null!=n?n:this.state.initialChecked,e.onChange=this._handleChange,h(e,this.props.children)},componentDidMount:function(){var e=u.getID(this.getDOMNode());g[e]=this},componentWillUnmount:function(){var e=this.getDOMNode(),t=u.getID(e);delete g[t]},componentDidUpdate:function(e,t,n){var o=this.getDOMNode();null!=this.props.checked&&i.setValueForProperty(o,"checked",this.props.checked||!1);var r=a.getValue(this);null!=r&&i.setValueForProperty(o,"value",""+r)},_handleChange:function(e){var n,r=a.getOnChange(this);r&&(n=r.call(this,e)),p.asap(o,this);var i=this.props.name;if("radio"===this.props.type&&null!=i){for(var l=this.getDOMNode(),s=l;s.parentNode;)s=s.parentNode;for(var c=s.querySelectorAll("input[name="+JSON.stringify(""+i)+'][type="radio"]'),d=0,h=c.length;h>d;d++){var b=c[d];if(b!==l&&b.form===l.form){var m=u.getID(b);"production"!==t.env.NODE_ENV?f(m,"ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."):f(m);var v=g[m];"production"!==t.env.NODE_ENV?f(v,"ReactDOMInput: Unknown radio button ID %s.",m):f(v),p.asap(o,v)}}}return n}});e.exports=b}).call(t,n(1))},function(e,t,n){(function(t){"use strict";var o=n(14),r=n(9),i=n(5),a=n(4),l=i.createFactory("option"),s=r.createClass({displayName:"ReactDOMOption",tagName:"OPTION",mixins:[o],componentWillMount:function(){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?a(null==this.props.selected,"Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>."):null)},render:function(){return l(this.props,this.props.children)}});e.exports=s}).call(t,n(1))},function(e,t,n){"use strict";function o(){if(this._pendingUpdate){this._pendingUpdate=!1;var e=l.getValue(this);null!=e&&this.isMounted()&&i(this,e)}}function r(e,t,n){if(null==e[t])return null;if(e.multiple){if(!Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be an array if `multiple` is true.")}else if(Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be a scalar value if `multiple` is false.")}function i(e,t){var n,o,r,i=e.getDOMNode().options;if(e.props.multiple){for(n={},o=0,r=t.length;r>o;o++)n[""+t[o]]=!0;for(o=0,r=i.length;r>o;o++){var a=n.hasOwnProperty(i[o].value);i[o].selected!==a&&(i[o].selected=a)}}else{for(n=""+t,o=0,r=i.length;r>o;o++)if(i[o].value===n)return void(i[o].selected=!0);i.length&&(i[0].selected=!0)}}var a=n(37),l=n(50),s=n(14),c=n(9),u=n(5),p=n(11),d=n(3),f=u.createFactory("select"),h=c.createClass({displayName:"ReactDOMSelect",tagName:"SELECT",mixins:[a,l.Mixin,s],propTypes:{defaultValue:r,value:r},render:function(){var e=d({},this.props);return e.onChange=this._handleChange,e.value=null,f(e,this.props.children)},componentWillMount:function(){this._pendingUpdate=!1},componentDidMount:function(){var e=l.getValue(this);null!=e?i(this,e):null!=this.props.defaultValue&&i(this,this.props.defaultValue)},componentDidUpdate:function(e){var t=l.getValue(this);null!=t?(this._pendingUpdate=!1,i(this,t)):!e.multiple!=!this.props.multiple&&(null!=this.props.defaultValue?i(this,this.props.defaultValue):i(this,this.props.multiple?[]:""))},_handleChange:function(e){var t,n=l.getOnChange(this);return n&&(t=n.call(this,e)),this._pendingUpdate=!0,p.asap(o,this),t}});e.exports=h},function(e,t,n){"use strict";function o(e,t,n,o){return e===n&&t===o}function r(e){var t=document.selection,n=t.createRange(),o=n.text.length,r=n.duplicate();r.moveToElementText(e),r.setEndPoint("EndToStart",n);var i=r.text.length,a=i+o;return{start:i,end:a}}function i(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,r=t.anchorOffset,i=t.focusNode,a=t.focusOffset,l=t.getRangeAt(0),s=o(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=s?0:l.toString().length,u=l.cloneRange();u.selectNodeContents(e),u.setEnd(l.startContainer,l.startOffset);var p=o(u.startContainer,u.startOffset,u.endContainer,u.endOffset),d=p?0:u.toString().length,f=d+c,h=document.createRange();h.setStart(n,r),h.setEnd(i,a);var g=h.collapsed;return{start:g?f:d,end:g?d:f}}function a(e,t){var n,o,r=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,o=n):t.start>t.end?(n=t.end,o=t.start):(n=t.start,o=t.end),r.moveToElementText(e),r.moveStart("character",n),r.setEndPoint("EndToStart",r),r.moveEnd("character",o-n),r.select()}function l(e,t){if(window.getSelection){var n=window.getSelection(),o=e[u()].length,r=Math.min(t.start,o),i="undefined"==typeof t.end?r:Math.min(t.end,o);if(!n.extend&&r>i){var a=i;i=r,r=a}var l=c(e,r),s=c(e,i);if(l&&s){var p=document.createRange();p.setStart(l.node,l.offset),n.removeAllRanges(),r>i?(n.addRange(p),n.extend(s.node,s.offset)):(p.setEnd(s.node,s.offset),n.addRange(p))}}}var s=n(6),c=n(195),u=n(102),p=s.canUseDOM&&"selection"in document&&!("getSelection"in window),d={getOffsets:p?r:i,setOffsets:p?a:l};e.exports=d},function(e,t,n){(function(t){"use strict";function o(){this.isMounted()&&this.forceUpdate()}var r=n(37),i=n(28),a=n(50),l=n(14),s=n(9),c=n(5),u=n(11),p=n(3),d=n(2),f=n(4),h=c.createFactory("textarea"),g=s.createClass({displayName:"ReactDOMTextarea",tagName:"TEXTAREA",mixins:[r,a.Mixin,l],getInitialState:function(){var e=this.props.defaultValue,n=this.props.children;null!=n&&("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?f(!1,"Use the `defaultValue` or `value` props instead of setting children on <textarea>."):null),"production"!==t.env.NODE_ENV?d(null==e,"If you supply `defaultValue` on a <textarea>, do not pass children."):d(null==e),Array.isArray(n)&&("production"!==t.env.NODE_ENV?d(n.length<=1,"<textarea> can only have at most one child."):d(n.length<=1),n=n[0]),e=""+n),null==e&&(e="");var o=a.getValue(this);return{initialValue:""+(null!=o?o:e)}},render:function(){var e=p({},this.props);return"production"!==t.env.NODE_ENV?d(null==e.dangerouslySetInnerHTML,"`dangerouslySetInnerHTML` does not make sense on <textarea>."):d(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null,e.onChange=this._handleChange,h(e,this.state.initialValue)},componentDidUpdate:function(e,t,n){var o=a.getValue(this);if(null!=o){var r=this.getDOMNode();i.setValueForProperty(r,"value",""+o)}},_handleChange:function(e){var t,n=a.getOnChange(this);return n&&(t=n.call(this,e)),u.asap(o,this),t}});e.exports=g}).call(t,n(1))},function(e,t,n){"use strict";function o(){this.reinitializeTransaction()}var r=n(11),i=n(42),a=n(3),l=n(17),s={initialize:l,close:function(){d.isBatchingUpdates=!1}},c={initialize:l,close:r.flushBatchedUpdates.bind(r)},u=[c,s];a(o.prototype,i.Mixin,{getTransactionWrappers:function(){return u}});var p=new o,d={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,o,r){var i=d.isBatchingUpdates;d.isBatchingUpdates=!0,i?e(t,n,o,r):p.perform(e,null,t,n,o,r)}};e.exports=d},function(e,t,n){(function(t){"use strict";function o(e){return h.createClass({tagName:e.toUpperCase(),render:function(){return new O(e,null,null,null,null,this.props)}})}function r(){if(R.EventEmitter.injectReactEventListener(T),R.EventPluginHub.injectEventPluginOrder(s),R.EventPluginHub.injectInstanceHandle(M),R.EventPluginHub.injectMount(P),R.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:j,EnterLeaveEventPlugin:c,ChangeEventPlugin:a,MobileSafariClickEventPlugin:d,SelectEventPlugin:I,BeforeInputEventPlugin:i}),R.NativeComponent.injectGenericComponentClass(m),R.NativeComponent.injectTextComponentClass(D),R.NativeComponent.injectAutoWrapper(o),R.Class.injectMixin(f),R.NativeComponent.injectComponentClasses({button:v,form:y,iframe:w,img:x,input:N,option:k,select:C,textarea:_,html:V("html"),head:V("head"),body:V("body")}),R.DOMProperty.injectDOMPropertyConfig(p),R.DOMProperty.injectDOMPropertyConfig(L),R.EmptyComponent.injectEmptyComponent("noscript"),R.Updates.injectReconcileTransaction(S),R.Updates.injectBatchingStrategy(b),R.RootIndex.injectCreateReactRootIndex(u.canUseDOM?l.createReactRootIndex:A.createReactRootIndex),R.Component.injectEnvironment(g),R.DOMComponent.injectIDOperations(E),"production"!==t.env.NODE_ENV){var e=u.canUseDOM&&window.location.href||"";if(/[?&]react_perf\b/.test(e)){var r=n(162);r.start()}}}var i=n(135),a=n(136),l=n(137),s=n(140),c=n(141),u=n(6),p=n(144),d=n(145),f=n(14),h=n(9),g=n(52),b=n(160),m=n(55),v=n(151),y=n(152),x=n(154),E=n(87),w=n(153),N=n(155),k=n(156),C=n(157),_=n(159),D=n(88),O=n(5),T=n(166),R=n(167),M=n(24),P=n(10),S=n(170),I=n(175),A=n(176),j=n(177),L=n(174),V=n(190);e.exports={inject:r}}).call(t,n(1))},function(e,t,n){"use strict";function o(e){return Math.floor(100*e)/100}function r(e,t,n){e[t]=(e[t]||0)+n}var i=n(20),a=n(163),l=n(10),s=n(16),c=n(205),u={_allMeasurements:[],_mountStack:[0],_injected:!1,start:function(){u._injected||s.injection.injectMeasure(u.measure),u._allMeasurements.length=0,s.enableMeasure=!0},stop:function(){s.enableMeasure=!1},getLastMeasurements:function(){return u._allMeasurements},printExclusive:function(e){e=e||u._allMeasurements;var t=a.getExclusiveSummary(e);console.table(t.map(function(e){return{"Component class name":e.componentName,"Total inclusive time (ms)":o(e.inclusive),"Exclusive mount time (ms)":o(e.exclusive),"Exclusive render time (ms)":o(e.render),"Mount time per instance (ms)":o(e.exclusive/e.count),"Render time per instance (ms)":o(e.render/e.count),Instances:e.count}}))},printInclusive:function(e){e=e||u._allMeasurements;var t=a.getInclusiveSummary(e);console.table(t.map(function(e){return{"Owner > component":e.componentName,"Inclusive time (ms)":o(e.time),Instances:e.count}})),console.log("Total time:",a.getTotalTime(e).toFixed(2)+" ms")},getMeasurementsSummaryMap:function(e){var t=a.getInclusiveSummary(e,!0);return t.map(function(e){return{"Owner > component":e.componentName,"Wasted time (ms)":e.time,Instances:e.count}})},printWasted:function(e){e=e||u._allMeasurements,console.table(u.getMeasurementsSummaryMap(e)),console.log("Total time:",a.getTotalTime(e).toFixed(2)+" ms")},printDOM:function(e){e=e||u._allMeasurements;var t=a.getDOMSummary(e);console.table(t.map(function(e){var t={};return t[i.ID_ATTRIBUTE_NAME]=e.id,t.type=e.type,t.args=JSON.stringify(e.args),t})),console.log("Total time:",a.getTotalTime(e).toFixed(2)+" ms")},_recordWrite:function(e,t,n,o){var r=u._allMeasurements[u._allMeasurements.length-1].writes;r[e]=r[e]||[],r[e].push({type:t,time:n,args:o})},measure:function(e,t,n){return function(){for(var o=[],i=0,a=arguments.length;a>i;i++)o.push(arguments[i]);var s,p,d;if("_renderNewRootComponent"===t||"flushBatchedUpdates"===t)return u._allMeasurements.push({exclusive:{},inclusive:{},render:{},counts:{},writes:{},displayNames:{},totalTime:0}),d=c(),p=n.apply(this,o),u._allMeasurements[u._allMeasurements.length-1].totalTime=c()-d,p;if("_mountImageIntoNode"===t||"ReactDOMIDOperations"===e){if(d=c(),p=n.apply(this,o),s=c()-d,"_mountImageIntoNode"===t){var f=l.getID(o[1]);u._recordWrite(f,t,s,o[0])}else"dangerouslyProcessChildrenUpdates"===t?o[0].forEach(function(e){var t={};null!==e.fromIndex&&(t.fromIndex=e.fromIndex),null!==e.toIndex&&(t.toIndex=e.toIndex),null!==e.textContent&&(t.textContent=e.textContent),null!==e.markupIndex&&(t.markup=o[1][e.markupIndex]),u._recordWrite(e.parentID,e.type,s,t)}):u._recordWrite(o[0],t,s,Array.prototype.slice.call(o,1));return p}if("ReactCompositeComponent"!==e||"mountComponent"!==t&&"updateComponent"!==t&&"_renderValidatedComponent"!==t)return n.apply(this,o);if("string"==typeof this._currentElement.type)return n.apply(this,o);var h="mountComponent"===t?o[0]:this._rootNodeID,g="_renderValidatedComponent"===t,b="mountComponent"===t,m=u._mountStack,v=u._allMeasurements[u._allMeasurements.length-1];if(g?r(v.counts,h,1):b&&m.push(0),d=c(),p=n.apply(this,o),s=c()-d,g)r(v.render,h,s);else if(b){var y=m.pop();m[m.length-1]+=s,r(v.exclusive,h,s-y),r(v.inclusive,h,s)}else r(v.inclusive,h,s);return v.displayNames[h]={current:this.getName(),owner:this._currentElement._owner?this._currentElement._owner.getName():"<root>"},p}}};e.exports=u},function(e,t,n){function o(e){for(var t=0,n=0;n<e.length;n++){var o=e[n];t+=o.totalTime}return t}function r(e){for(var t=[],n=0;n<e.length;n++){var o,r=e[n];for(o in r.writes)r.writes[o].forEach(function(e){t.push({id:o,type:u[e.type]||e.type,args:e.args})})}return t}function i(e){for(var t,n={},o=0;o<e.length;o++){var r=e[o],i=s({},r.exclusive,r.inclusive);for(var a in i)t=r.displayNames[a].current,n[t]=n[t]||{componentName:t,inclusive:0,exclusive:0,render:0,count:0},r.render[a]&&(n[t].render+=r.render[a]),r.exclusive[a]&&(n[t].exclusive+=r.exclusive[a]),r.inclusive[a]&&(n[t].inclusive+=r.inclusive[a]),r.counts[a]&&(n[t].count+=r.counts[a])}var l=[];for(t in n)n[t].exclusive>=c&&l.push(n[t]);return l.sort(function(e,t){return t.exclusive-e.exclusive}),l}function a(e,t){for(var n,o={},r=0;r<e.length;r++){var i,a=e[r],u=s({},a.exclusive,a.inclusive);t&&(i=l(a));for(var p in u)if(!t||i[p]){var d=a.displayNames[p];n=d.owner+" > "+d.current,o[n]=o[n]||{componentName:n,time:0,count:0},a.inclusive[p]&&(o[n].time+=a.inclusive[p]),a.counts[p]&&(o[n].count+=a.counts[p])}}var f=[];for(n in o)o[n].time>=c&&f.push(o[n]);return f.sort(function(e,t){return t.time-e.time}),f}function l(e){var t={},n=Object.keys(e.writes),o=s({},e.exclusive,e.inclusive);for(var r in o){for(var i=!1,a=0;a<n.length;a++)if(0===n[a].indexOf(r)){i=!0;break}!i&&e.counts[r]>0&&(t[r]=!0)}return t}var s=n(3),c=1.2,u={_mountImageIntoNode:"set innerHTML",INSERT_MARKUP:"set innerHTML",MOVE_EXISTING:"move",REMOVE_NODE:"remove",TEXT_CONTENT:"set textContent",updatePropertyByID:"update attribute",deletePropertyByID:"delete attribute",updateStylesByID:"update styles",updateInnerHTMLByID:"set innerHTML",dangerouslyReplaceNodeWithMarkupByID:"replace"},p={getExclusiveSummary:i,getInclusiveSummary:a,getDOMSummary:r,getTotalTime:o};e.exports=p},function(e,t){"use strict";var n={guard:function(e,t){return e}};e.exports=n},function(e,t,n){"use strict";function o(e){r.enqueueEvents(e),r.processEventQueue()}var r=n(29),i={handleTopLevel:function(e,t,n,i){var a=r.extractEvents(e,t,n,i);o(a)}};e.exports=i},function(e,t,n){"use strict";function o(e){var t=p.getID(e),n=u.getReactRootIDFromNodeID(t),o=p.findReactContainerForID(n),r=p.getFirstReactDOM(o);return r}function r(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){for(var t=p.getFirstReactDOM(h(e.nativeEvent))||window,n=t;n;)e.ancestors.push(n),n=o(n);for(var r=0,i=e.ancestors.length;i>r;r++){t=e.ancestors[r];var a=p.getID(t)||"";b._handleTopLevel(e.topLevelType,t,a,e.nativeEvent)}}function a(e){var t=g(window);e(t)}var l=n(142),s=n(6),c=n(13),u=n(24),p=n(10),d=n(11),f=n(3),h=n(64),g=n(197);f(r.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),c.addPoolingTo(r,c.twoArgumentPooler);var b={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:s.canUseDOM?window:null,setHandleTopLevel:function(e){b._handleTopLevel=e},setEnabled:function(e){b._enabled=!!e},isEnabled:function(){return b._enabled},trapBubbledEvent:function(e,t,n){var o=n;return o?l.listen(o,t,b.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var o=n;return o?l.capture(o,t,b.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=a.bind(null,e);l.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(b._enabled){var n=r.getPooled(e,t);try{d.batchedUpdates(i,n)}finally{r.release(n)}}}};e.exports=b},function(e,t,n){"use strict";var o=n(20),r=n(29),i=n(53),a=n(9),l=n(56),s=n(23),c=n(39),u=n(55),p=n(16),d=n(94),f=n(11),h={Component:i.injection,Class:a.injection,DOMComponent:u.injection,DOMProperty:o.injection,EmptyComponent:l.injection,EventPluginHub:r.injection,EventEmitter:s.injection,NativeComponent:c.injection,Perf:p.injection,RootIndex:d.injection,Updates:f.injection};e.exports=h},function(e,t,n){"use strict";function o(e,t,n){h.push({parentID:e,parentNode:null,type:u.INSERT_MARKUP,markupIndex:g.push(t)-1,textContent:null,fromIndex:null,toIndex:n})}function r(e,t,n){h.push({parentID:e,parentNode:null,type:u.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:t,toIndex:n})}function i(e,t){h.push({parentID:e,parentNode:null,type:u.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:t,toIndex:null})}function a(e,t){h.push({parentID:e,parentNode:null,type:u.TEXT_CONTENT,markupIndex:null,textContent:t,fromIndex:null,toIndex:null})}function l(){h.length&&(c.processChildrenUpdates(h,g),s())}function s(){h.length=0,g.length=0}var c=n(53),u=n(91),p=n(26),d=n(147),f=0,h=[],g=[],b={Mixin:{mountChildren:function(e,t,n){var o=d.instantiateChildren(e,t,n);this._renderedChildren=o;var r=[],i=0;for(var a in o)if(o.hasOwnProperty(a)){var l=o[a],s=this._rootNodeID+a,c=p.mountComponent(l,s,t,n);l._mountIndex=i,r.push(c),i++}return r},updateTextContent:function(e){f++;var t=!0;try{var n=this._renderedChildren;d.unmountChildren(n);for(var o in n)n.hasOwnProperty(o)&&this._unmountChildByName(n[o],o);this.setTextContent(e),t=!1}finally{f--,f||(t?s():l())}},updateChildren:function(e,t,n){f++;var o=!0;try{this._updateChildren(e,t,n),o=!1}finally{f--,f||(o?s():l())}},_updateChildren:function(e,t,n){var o=this._renderedChildren,r=d.updateChildren(o,e,t,n);if(this._renderedChildren=r,r||o){var i,a=0,l=0;for(i in r)if(r.hasOwnProperty(i)){var s=o&&o[i],c=r[i];s===c?(this.moveChild(s,l,a),a=Math.max(s._mountIndex,a),s._mountIndex=l):(s&&(a=Math.max(s._mountIndex,a),this._unmountChildByName(s,i)),this._mountChildByNameAtIndex(c,i,l,t,n)),l++}for(i in o)!o.hasOwnProperty(i)||r&&r.hasOwnProperty(i)||this._unmountChildByName(o[i],i)}},unmountChildren:function(){var e=this._renderedChildren;d.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&r(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){o(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){i(this._rootNodeID,e._mountIndex)},setTextContent:function(e){a(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,o,r){var i=this._rootNodeID+t,a=p.mountComponent(e,i,o,r);e._mountIndex=n,this.createChild(e,a)},_unmountChildByName:function(e,t){this.removeChild(e),e._mountIndex=null}}};e.exports=b},function(e,t,n){(function(t){"use strict";var o=n(2),r={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,n,i){"production"!==t.env.NODE_ENV?o(r.isValidOwner(i),"addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's `render` method). Try rendering this component inside of a new top-level component which will hold the ref."):o(r.isValidOwner(i)),i.attachRef(n,e)},removeComponentAsRefFrom:function(e,n,i){"production"!==t.env.NODE_ENV?o(r.isValidOwner(i),"removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This usually means that you're trying to remove a ref to a component that doesn't have an owner (that is, was not created inside of another component's `render` method). Try rendering this component inside of a new top-level component which will hold the ref."):o(r.isValidOwner(i)),i.getPublicInstance().refs[n]===e.getPublicInstance()&&i.detachRef(n)}};e.exports=r}).call(t,n(1))},function(e,t,n){"use strict";function o(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=r.getPooled(null),this.putListenerQueue=s.getPooled()}var r=n(48),i=n(13),a=n(23),l=n(89),s=n(93),c=n(42),u=n(3),p={initialize:l.getSelectionInformation,close:l.restoreSelection},d={initialize:function(){var e=a.isEnabled();return a.setEnabled(!1),e},close:function(e){a.setEnabled(e)}},f={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},h={initialize:function(){this.putListenerQueue.reset()},close:function(){this.putListenerQueue.putListeners()}},g=[h,p,d,f],b={getTransactionWrappers:function(){return g},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){r.release(this.reactMountReady),this.reactMountReady=null,s.release(this.putListenerQueue),this.putListenerQueue=null}};u(o.prototype,c.Mixin,b),i.addPoolingTo(o),e.exports=o},function(e,t,n){"use strict";function o(e,t,n){"function"==typeof e?e(t.getPublicInstance()):i.addComponentAsRefTo(t,e,n)}function r(e,t,n){"function"==typeof e?e(null):i.removeComponentAsRefFrom(t,e,n)}var i=n(169),a={};a.attachRefs=function(e,t){var n=t.ref;null!=n&&o(n,e,t._owner)},a.shouldUpdateRefs=function(e,t){return t._owner!==e._owner||t.ref!==e.ref},a.detachRefs=function(e,t){var n=t.ref;null!=n&&r(n,e,t._owner)},e.exports=a},function(e,t,n){(function(t){"use strict";function o(e){"production"!==t.env.NODE_ENV?p(i.isValidElement(e),"renderToString(): You must pass a valid ReactElement."):p(i.isValidElement(e));var n;try{var o=a.createReactRootID();return n=s.getPooled(!1),n.perform(function(){var t=u(e,null),r=t.mountComponent(o,n,c);return l.addChecksumToMarkup(r)},null)}finally{s.release(n)}}function r(e){"production"!==t.env.NODE_ENV?p(i.isValidElement(e),"renderToStaticMarkup(): You must pass a valid ReactElement."):p(i.isValidElement(e));var n;try{var o=a.createReactRootID();return n=s.getPooled(!0),n.perform(function(){var t=u(e,null);return t.mountComponent(o,n,c)},null)}finally{s.release(n)}}var i=n(5),a=n(24),l=n(90),s=n(173),c=n(43),u=n(65),p=n(2);e.exports={renderToString:o,renderToStaticMarkup:r}}).call(t,n(1))},function(e,t,n){"use strict";function o(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=i.getPooled(null),this.putListenerQueue=a.getPooled()}var r=n(13),i=n(48),a=n(93),l=n(42),s=n(3),c=n(17),u={initialize:function(){this.reactMountReady.reset()},close:c},p={initialize:function(){this.putListenerQueue.reset()},close:c},d=[p,u],f={getTransactionWrappers:function(){return d},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null,a.release(this.putListenerQueue),this.putListenerQueue=null}};s(o.prototype,l.Mixin,f),r.addPoolingTo(o),e.exports=o},function(e,t,n){"use strict";var o=n(20),r=o.injection.MUST_USE_ATTRIBUTE,i={Properties:{clipPath:r,cx:r,cy:r,d:r,dx:r,dy:r,fill:r,fillOpacity:r,fontFamily:r,fontSize:r,fx:r,fy:r,gradientTransform:r,gradientUnits:r,markerEnd:r,markerMid:r,markerStart:r,offset:r,opacity:r,patternContentUnits:r,patternUnits:r,points:r,preserveAspectRatio:r,r:r,rx:r,ry:r,spreadMethod:r,stopColor:r,stopOpacity:r,stroke:r,strokeDasharray:r,strokeLinecap:r,strokeOpacity:r,strokeWidth:r,textAnchor:r,transform:r,version:r,viewBox:r,x1:r,x2:r,x:r,y1:r,y2:r,y:r},DOMAttributeNames:{clipPath:"clip-path",fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox"}};e.exports=i},function(e,t,n){"use strict";function o(e){if("selectionStart"in e&&l.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function r(e){if(v||null==g||g!==c())return null;var t=o(g);if(!m||!d(m,t)){m=t;var n=s.getPooled(h.select,b,e);return n.type="select",n.target=g,a.accumulateTwoPhaseDispatches(n),n}}var i=n(8),a=n(30),l=n(89),s=n(21),c=n(99),u=n(104),p=n(18),d=n(208),f=i.topLevelTypes,h={select:{phasedRegistrationNames:{bubbled:p({onSelect:null}),captured:p({onSelectCapture:null})},dependencies:[f.topBlur,f.topContextMenu,f.topFocus,f.topKeyDown,f.topMouseDown,f.topMouseUp,f.topSelectionChange]}},g=null,b=null,m=null,v=!1,y={eventTypes:h,extractEvents:function(e,t,n,o){switch(e){case f.topFocus:(u(t)||"true"===t.contentEditable)&&(g=t,b=n,m=null);break;case f.topBlur:g=null,b=null,m=null;break;case f.topMouseDown:v=!0;break;case f.topContextMenu:case f.topMouseUp:return v=!1,r(o);case f.topSelectionChange:case f.topKeyDown:case f.topKeyUp:return r(o)}}};e.exports=y},function(e,t){"use strict";var n=Math.pow(2,53),o={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};e.exports=o},function(e,t,n){(function(t){"use strict";var o=n(8),r=n(49),i=n(30),a=n(178),l=n(21),s=n(181),c=n(183),u=n(41),p=n(180),d=n(184),f=n(32),h=n(185),g=n(62),b=n(2),m=n(18),v=n(4),y=o.topLevelTypes,x={blur:{phasedRegistrationNames:{bubbled:m({onBlur:!0}),captured:m({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:m({onClick:!0}),captured:m({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:m({onContextMenu:!0}),captured:m({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:m({onCopy:!0}),captured:m({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:m({onCut:!0}),captured:m({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:m({onDoubleClick:!0}),captured:m({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:m({onDrag:!0}),captured:m({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:m({onDragEnd:!0}),captured:m({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:m({onDragEnter:!0}),captured:m({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:m({onDragExit:!0}),captured:m({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:m({onDragLeave:!0}),captured:m({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:m({onDragOver:!0}),captured:m({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:m({onDragStart:!0}),captured:m({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:m({onDrop:!0}),captured:m({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:m({onFocus:!0}),captured:m({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:m({onInput:!0}),captured:m({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:m({onKeyDown:!0}),captured:m({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:m({onKeyPress:!0}),captured:m({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:m({onKeyUp:!0}),captured:m({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:m({onLoad:!0}),captured:m({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:m({onError:!0}),captured:m({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:m({onMouseDown:!0}),captured:m({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:m({onMouseMove:!0}),captured:m({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:m({onMouseOut:!0}),captured:m({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:m({onMouseOver:!0}),captured:m({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:m({onMouseUp:!0}),captured:m({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:m({onPaste:!0}),captured:m({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:m({onReset:!0}),captured:m({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:m({onScroll:!0}),captured:m({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:m({onSubmit:!0}),captured:m({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:m({onTouchCancel:!0}),captured:m({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:m({onTouchEnd:!0}),captured:m({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:m({onTouchMove:!0}),captured:m({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:m({onTouchStart:!0}),captured:m({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:m({onWheel:!0}),captured:m({onWheelCapture:!0})}}},E={topBlur:x.blur,topClick:x.click,topContextMenu:x.contextMenu, topCopy:x.copy,topCut:x.cut,topDoubleClick:x.doubleClick,topDrag:x.drag,topDragEnd:x.dragEnd,topDragEnter:x.dragEnter,topDragExit:x.dragExit,topDragLeave:x.dragLeave,topDragOver:x.dragOver,topDragStart:x.dragStart,topDrop:x.drop,topError:x.error,topFocus:x.focus,topInput:x.input,topKeyDown:x.keyDown,topKeyPress:x.keyPress,topKeyUp:x.keyUp,topLoad:x.load,topMouseDown:x.mouseDown,topMouseMove:x.mouseMove,topMouseOut:x.mouseOut,topMouseOver:x.mouseOver,topMouseUp:x.mouseUp,topPaste:x.paste,topReset:x.reset,topScroll:x.scroll,topSubmit:x.submit,topTouchCancel:x.touchCancel,topTouchEnd:x.touchEnd,topTouchMove:x.touchMove,topTouchStart:x.touchStart,topWheel:x.wheel};for(var w in E)E[w].dependencies=[w];var N={eventTypes:x,executeDispatch:function(e,n,o){var i=r.executeDispatch(e,n,o);"production"!==t.env.NODE_ENV?v("boolean"!=typeof i,"Returning `false` from an event handler is deprecated and will be ignored in a future release. Instead, manually call e.stopPropagation() or e.preventDefault(), as appropriate."):null,i===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,n,o,r){var m=E[e];if(!m)return null;var v;switch(e){case y.topInput:case y.topLoad:case y.topError:case y.topReset:case y.topSubmit:v=l;break;case y.topKeyPress:if(0===g(r))return null;case y.topKeyDown:case y.topKeyUp:v=c;break;case y.topBlur:case y.topFocus:v=s;break;case y.topClick:if(2===r.button)return null;case y.topContextMenu:case y.topDoubleClick:case y.topMouseDown:case y.topMouseMove:case y.topMouseOut:case y.topMouseOver:case y.topMouseUp:v=u;break;case y.topDrag:case y.topDragEnd:case y.topDragEnter:case y.topDragExit:case y.topDragLeave:case y.topDragOver:case y.topDragStart:case y.topDrop:v=p;break;case y.topTouchCancel:case y.topTouchEnd:case y.topTouchMove:case y.topTouchStart:v=d;break;case y.topScroll:v=f;break;case y.topWheel:v=h;break;case y.topCopy:case y.topCut:case y.topPaste:v=a}"production"!==t.env.NODE_ENV?b(v,"SimpleEventPlugin: Unhandled event type, `%s`.",e):b(v);var x=v.getPooled(m,o,r);return i.accumulateTwoPhaseDispatches(x),x}};e.exports=N}).call(t,n(1))},function(e,t,n){"use strict";function o(e,t,n){r.call(this,e,t,n)}var r=n(21),i={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};r.augmentClass(o,i),e.exports=o},function(e,t,n){"use strict";function o(e,t,n){r.call(this,e,t,n)}var r=n(21),i={data:null};r.augmentClass(o,i),e.exports=o},function(e,t,n){"use strict";function o(e,t,n){r.call(this,e,t,n)}var r=n(41),i={dataTransfer:null};r.augmentClass(o,i),e.exports=o},function(e,t,n){"use strict";function o(e,t,n){r.call(this,e,t,n)}var r=n(32),i={relatedTarget:null};r.augmentClass(o,i),e.exports=o},function(e,t,n){"use strict";function o(e,t,n){r.call(this,e,t,n)}var r=n(21),i={data:null};r.augmentClass(o,i),e.exports=o},function(e,t,n){"use strict";function o(e,t,n){r.call(this,e,t,n)}var r=n(32),i=n(62),a=n(194),l=n(63),s={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:l,charCode:function(e){return"keypress"===e.type?i(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?i(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};r.augmentClass(o,s),e.exports=o},function(e,t,n){"use strict";function o(e,t,n){r.call(this,e,t,n)}var r=n(32),i=n(63),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:i};r.augmentClass(o,a),e.exports=o},function(e,t,n){"use strict";function o(e,t,n){r.call(this,e,t,n)}var r=n(41),i={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};r.augmentClass(o,i),e.exports=o},function(e,t){"use strict";function n(e){for(var t=1,n=0,r=0;r<e.length;r++)t=(t+e.charCodeAt(r))%o,n=(n+t)%o;return t|n<<16}var o=65521;e.exports=n},function(e,t){function n(e){return e.replace(o,function(e,t){return t.toUpperCase()})}var o=/-(.)/g;e.exports=n},function(e,t,n){"use strict";function o(e){return r(e.replace(i,"ms-"))}var r=n(187),i=/^-ms-/;e.exports=o},function(e,t,n){function o(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function r(e){return o(e)?Array.isArray(e)?e.slice():i(e):[e]}var i=n(209);e.exports=r},function(e,t,n){(function(t){"use strict";function o(e){var n=i.createFactory(e),o=r.createClass({tagName:e.toUpperCase(),displayName:"ReactFullPageComponent"+e,componentWillUnmount:function(){"production"!==t.env.NODE_ENV?a(!1,"%s tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.",this.constructor.displayName):a(!1)},render:function(){return n(this.props)}});return o}var r=n(9),i=n(5),a=n(2);e.exports=o}).call(t,n(1))},function(e,t,n){(function(t){function o(e){var t=e.match(u);return t&&t[1].toLowerCase()}function r(e,n){var r=c;"production"!==t.env.NODE_ENV?s(!!c,"createNodesFromMarkup dummy not initialized"):s(!!c);var i=o(e),u=i&&l(i);if(u){r.innerHTML=u[1]+e+u[2];for(var p=u[0];p--;)r=r.lastChild}else r.innerHTML=e;var d=r.getElementsByTagName("script");d.length&&("production"!==t.env.NODE_ENV?s(n,"createNodesFromMarkup(...): Unexpected <script> element rendered."):s(n),a(d).forEach(n));for(var f=a(r.childNodes);r.lastChild;)r.removeChild(r.lastChild);return f}var i=n(6),a=n(189),l=n(101),s=n(2),c=i.canUseDOM?document.createElement("div"):null,u=/^\s*<(\w+)/;e.exports=r}).call(t,n(1))},function(e,t,n){"use strict";function o(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var o=isNaN(t);return o||0===t||i.hasOwnProperty(e)&&i[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var r=n(83),i=r.isUnitlessNumber;e.exports=o},function(e,t,n){(function(t){"use strict";function o(e,n,o){var r=e,i=!r.hasOwnProperty(o);"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?a(i,"flattenChildren(...): Encountered two children with the same key, `%s`. Child keys must be unique; when two children share a key, only the first child will be used.",o):null),i&&null!=n&&(r[o]=n)}function r(e){if(null==e)return e;var t={};return i(e,o,t),t}var i=n(105),a=n(4);e.exports=r}).call(t,n(1))},function(e,t,n){"use strict";function o(e){if(e.key){var t=i[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=r(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var r=n(62),i={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};e.exports=o},function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function o(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function r(e,t){for(var r=n(e),i=0,a=0;r;){if(3===r.nodeType){if(a=i+r.textContent.length,t>=i&&a>=t)return{node:r,offset:t-i};i=a}r=n(o(r))}}e.exports=r},function(e,t){"use strict";function n(e){return e?e.nodeType===o?e.documentElement:e.firstChild:null}var o=9;e.exports=n},function(e,t){"use strict";function n(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}e.exports=n},function(e,t){function n(e){return e.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;e.exports=n},function(e,t,n){"use strict";function o(e){return r(e).replace(i,"-ms-")}var r=n(198),i=/^ms-/;e.exports=o},function(e,t,n){function o(e){return r(e)&&3==e.nodeType}var r=n(103);e.exports=o},function(e,t){"use strict";function n(e,t,n){if(!e)return null;var r={};for(var i in e)o.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}var o=Object.prototype.hasOwnProperty;e.exports=n},function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}e.exports=n},function(e,t,n){(function(t){"use strict";function o(e){return"production"!==t.env.NODE_ENV?i(r.isValidElement(e),"onlyChild must be passed a children with exactly one child."):i(r.isValidElement(e)),e}var r=n(5),i=n(2);e.exports=o}).call(t,n(1))},function(e,t,n){"use strict";var o,r=n(6);r.canUseDOM&&(o=window.performance||window.msPerformance||window.webkitPerformance),e.exports=o||{}},function(e,t,n){var o=n(204);o&&o.now||(o=Date);var r=o.now.bind(o);e.exports=r},function(e,t,n){"use strict";function o(e){return'"'+r(e)+'"'}var r=n(44);e.exports=o},function(e,t,n){"use strict";var o=n(6),r=n(44),i=n(67),a=function(e,t){e.textContent=t};o.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){i(e,r(t))})),e.exports=a},function(e,t){"use strict";function n(e,t){if(e===t)return!0;var n;for(n in e)if(e.hasOwnProperty(n)&&(!t.hasOwnProperty(n)||e[n]!==t[n]))return!1;for(n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}e.exports=n},function(e,t,n){(function(t){function o(e){var n=e.length;if("production"!==t.env.NODE_ENV?r(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e),"toArray: Array-like object expected"):r(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e)),"production"!==t.env.NODE_ENV?r("number"==typeof n,"toArray: Object needs a length property"):r("number"==typeof n),"production"!==t.env.NODE_ENV?r(0===n||n-1 in e,"toArray: Object should have keys for indices"):r(0===n||n-1 in e),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(o){}for(var i=Array(n),a=0;n>a;a++)i[a]=e[a];return i}var r=n(2);e.exports=o}).call(t,n(1))},function(e,t,n){function o(e,t){for(var n=0;n<e.length;n++){var o=e[n],r=p[o.id];if(r){r.refs++;for(var i=0;i<r.parts.length;i++)r.parts[i](o.parts[i]);for(;i<o.parts.length;i++)r.parts.push(l(o.parts[i],t))}else{for(var a=[],i=0;i<o.parts.length;i++)a.push(l(o.parts[i],t));p[o.id]={id:o.id,refs:1,parts:a}}}}function r(e){for(var t=[],n={},o=0;o<e.length;o++){var r=e[o],i=r[0],a=r[1],l=r[2],s=r[3],c={css:a,media:l,sourceMap:s};n[i]?n[i].parts.push(c):t.push(n[i]={id:i,parts:[c]})}return t}function i(){var e=document.createElement("style"),t=h();return e.type="text/css",t.appendChild(e),e}function a(){var e=document.createElement("link"),t=h();return e.rel="stylesheet",t.appendChild(e),e}function l(e,t){var n,o,r;if(t.singleton){var l=b++;n=g||(g=i()),o=s.bind(null,n,l,!1),r=s.bind(null,n,l,!0)}else e.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=a(),o=u.bind(null,n),r=function(){n.parentNode.removeChild(n),n.href&&URL.revokeObjectURL(n.href)}):(n=i(),o=c.bind(null,n),r=function(){n.parentNode.removeChild(n)});return o(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;o(e=t)}else r()}}function s(e,t,n,o){var r=n?"":o.css;if(e.styleSheet)e.styleSheet.cssText=m(t,r);else{var i=document.createTextNode(r),a=e.childNodes;a[t]&&e.removeChild(a[t]),a.length?e.insertBefore(i,a[t]):e.appendChild(i)}}function c(e,t){var n=t.css,o=t.media;t.sourceMap;if(o&&e.setAttribute("media",o),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}function u(e,t){var n=t.css,o=(t.media,t.sourceMap);o&&(n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(o))))+" */");var r=new Blob([n],{type:"text/css"}),i=e.href;e.href=URL.createObjectURL(r),i&&URL.revokeObjectURL(i)}var p={},d=function(e){var t;return function(){return"undefined"==typeof t&&(t=e.apply(this,arguments)),t}},f=d(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),h=d(function(){return document.head||document.getElementsByTagName("head")[0]}),g=null,b=0;e.exports=function(e,t){t=t||{},"undefined"==typeof t.singleton&&(t.singleton=f());var n=r(e);return o(n,t),function(e){for(var i=[],a=0;a<n.length;a++){var l=n[a],s=p[l.id];s.refs--,i.push(s)}if(e){var c=r(e);o(c,t)}for(var a=0;a<i.length;a++){var s=i[a];if(0===s.refs){for(var u=0;u<s.parts.length;u++)s.parts[u]();delete p[s.id]}}}};var m=function(){var e=[];return function(t,n){return e[t]=n,e.filter(Boolean).join("\n")}}()},function(e,t,n){var o=n(106);"string"==typeof o&&(o=[[e.id,o,""]]);n(210)(o,{});o.locals&&(e.exports=o.locals)},function(e,t,n){e.exports=n.p+"fa2772327f55d8198301fdb8bcfc8158.woff"},function(e,t,n){e.exports=n.p+"448c34a56d699c29117adc64c43affeb.woff2"},function(e,t,n){e.exports=n.p+"e18bbf611f2a2e43afc071aa2f4e1512.ttf"},function(e,t,n){e.exports=n.p+"89889688147bd7575d6327160d64e760.svg"}]);
lib.rs
pub extern crate nalgebra_glm; extern crate rand; pub mod camera; pub mod input; pub mod particle; pub mod scene;
extern crate ggez;
raid_tests.rs
// Copyright © Spelldawn 2021-present // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // https://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use cards::test_cards::WEAPON_COST; use data::card_name::CardName; use data::primitives::{RoomId, Side}; use insta::assert_snapshot; use protos::spelldawn::game_action::Action; use protos::spelldawn::game_object_identifier::Id; use protos::spelldawn::object_position::Position; use protos::spelldawn::{ ClientRoomLocation, GainManaAction, InitiateRaidAction, ObjectPositionBrowser, ObjectPositionIdentity, ObjectPositionIdentityContainer, ObjectPositionRaid, ObjectPositionRoom, PlayerName, }; use test_utils::client::HasText; use test_utils::summarize::Summary; use test_utils::{test_games, *}; #[test] fn initiate_raid() { let (mut g, ids) = test_games::simple_game( Side::Champion, CardName::TestScheme31, CardName::TestMinionEndRaid, CardName::TestWeapon3Attack12Boost3Cost, ); let response = g.perform_action( Action::InitiateRaid(InitiateRaidAction { room_id: CLIENT_ROOM_ID.into() }), g.user_id(), ); assert_eq!(1, g.me().actions()); assert!(g.user.other_player.can_take_action()); assert!(g.opponent.this_player.can_take_action()); assert!(g.user.data.raid_active()); assert!(g.opponent.data.raid_active()); assert_eq!( g.user.data.object_index_position(Id::CardId(ids.scheme_id)), (0, Position::Raid(ObjectPositionRaid {})) ); assert_eq!( g.opponent.data.object_index_position(Id::CardId(ids.scheme_id)), (0, Position::Raid(ObjectPositionRaid {})) ); assert_eq!( g.user.data.object_index_position(Id::CardId(ids.minion_id)), (1, Position::Raid(ObjectPositionRaid {})) ); assert_eq!( g.opponent.data.object_index_position(Id::CardId(ids.minion_id)), (1, Position::Raid(ObjectPositionRaid {})) ); assert_eq!( g.user.data.object_index_position(Id::Identity(PlayerName::User.into())), (2, Position::Raid(ObjectPositionRaid {})) ); assert_eq!( g.opponent.data.object_index_position(Id::Identity(PlayerName::Opponent.into())), (2, Position::Raid(ObjectPositionRaid {})) ); assert!(g.user.interface.controls().has_text("Waiting")); assert!(g.opponent.interface.controls().has_text("Activate")); assert!(g.opponent.interface.controls().has_text("Pass")); assert_snapshot!(Summary::run(&response)); } #[test] fn activate_room() { let (mut g, ids) = test_games::simple_game( Side::Champion, CardName::TestScheme31, CardName::TestMinionEndRaid, CardName::TestWeapon3Attack12Boost3Cost, ); g.perform( Action::InitiateRaid(InitiateRaidAction { room_id: CLIENT_ROOM_ID.into() }), g.user_id(), ); assert_eq!(g.opponent.this_player.mana(), 999); assert!(!g.user.cards.get(ids.minion_id).revealed_to_me()); let response = g.click_on(g.opponent_id(), "Activate"); assert_eq!(g.opponent.this_player.mana(), 996); // Minion costs 3 to summon assert!(g.user.cards.get(ids.minion_id).revealed_to_me()); assert!(g.opponent.cards.get(ids.minion_id).revealed_to_me()); assert!(g.user.this_player.can_take_action()); assert!(g.opponent.other_player.can_take_action()); assert!(g.opponent.interface.controls().has_text("Waiting")); assert!(g.user.interface.controls().has_text("Test Weapon")); assert!(g.user.interface.controls().has_text("1\u{f06d}")); assert!(g.user.interface.controls().has_text("Continue")); assert_eq!( g.user.data.object_index_position(Id::CardId(ids.scheme_id)), (0, Position::Raid(ObjectPositionRaid {})) ); assert_eq!( g.user.data.object_index_position(Id::CardId(ids.minion_id)), (1, Position::Raid(ObjectPositionRaid {})) ); assert_eq!( g.user.data.object_index_position(Id::Identity(PlayerName::User.into())), (2, Position::Raid(ObjectPositionRaid {})) ); assert_snapshot!(Summary::summarize(&response)); } #[test] fn activate_room_weapon_2() { let (mut g, _) = test_games::simple_game( Side::Champion, CardName::TestScheme31, CardName::TestMinionEndRaid, CardName::TestWeapon2Attack, ); g.perform( Action::InitiateRaid(InitiateRaidAction { room_id: CLIENT_ROOM_ID.into() }), g.user_id(), ); g.click_on(g.opponent_id(), "Activate"); assert!(g.opponent.interface.controls().has_text("Waiting")); assert!(!g.user.interface.controls().has_text("Test Weapon")); assert!(g.user.interface.controls().has_text("Continue")); } #[test] fn activate_room_weapon_2_12() { let (mut g, _) = test_games::simple_game( Side::Champion, CardName::TestScheme31, CardName::TestMinionEndRaid, CardName::TestWeapon2Attack12Boost, ); g.perform( Action::InitiateRaid(InitiateRaidAction { room_id: CLIENT_ROOM_ID.into() }), g.user_id(), ); g.click_on(g.opponent_id(), "Activate"); assert!(g.opponent.interface.controls().has_text("Waiting")); assert!(g.user.interface.controls().has_text("Test Weapon")); assert!(g.user.interface.controls().has_text("2\u{f06d}")); assert!(g.user.interface.controls().has_text("Continue")); } #[test] fn activate_room_weapon_4_12() { let (mut g, _) = test_games::simple_game( Side::Champion, CardName::TestScheme31, CardName::TestMinionEndRaid, CardName::TestWeapon4Attack12Boost, ); g.perform( Action::InitiateRaid(InitiateRaidAction { room_id: CLIENT_ROOM_ID.into() }), g.user_id(), ); g.click_on(g.opponent_id(), "Activate"); assert!(g.opponent.interface.controls().has_text("Waiting")); assert!(g.user.interface.controls().has_text("Test Weapon")); assert!(g.user.interface.controls().has_text("1\u{f06d}")); assert!(g.user.interface.controls().has_text("Continue")); } #[test] fn activate_room_weapon_5() { let (mut g, _) = test_games::simple_game( Side::Champion, CardName::TestScheme31, CardName::TestMinionEndRaid, CardName::TestWeapon5Attack, ); g.perform( Action::InitiateRaid(InitiateRaidAction { room_id: CLIENT_ROOM_ID.into() }), g.user_id(), ); g.click_on(g.opponent_id(), "Activate"); assert!(g.opponent.interface.controls().has_text("Waiting")); assert!(g.user.interface.controls().has_text("Test Weapon")); assert!(!g.user.interface.controls().has_text("\u{f06d}")); assert!(g.user.interface.controls().has_text("Continue")); } #[test] fn use_weapon() { let (mut g, ids) = test_games::simple_game( Side::Champion, CardName::TestScheme31, CardName::TestMinionEndRaid, CardName::TestWeapon3Attack12Boost3Cost, ); g.perform( Action::InitiateRaid(InitiateRaidAction { room_id: CLIENT_ROOM_ID.into() }), g.user_id(), ); g.click_on(g.opponent_id(), "Activate"); assert_eq!(g.user.this_player.mana(), 996); // Minion costs 3 to summon let response = g.click_on(g.user_id(), "Test Weapon"); assert_eq!(g.user.this_player.mana(), 995); // Weapon costs 1 to use assert_eq!(g.opponent.other_player.mana(), 995); // Weapon costs 1 to use assert!(g.user.cards.get(ids.scheme_id).revealed_to_me()); assert!(g.opponent.cards.get(ids.scheme_id).revealed_to_me()); assert!(g.user.this_player.can_take_action()); assert!(g.opponent.other_player.can_take_action()); assert!(g.opponent.interface.controls().has_text("Waiting")); assert!(g.user.interface.card_anchor_nodes().has_text("Score!")); assert!(g.user.interface.controls().has_text("End Raid")); assert_eq!( g.user.data.object_index_position(Id::CardId(ids.scheme_id)), (0, Position::Browser(ObjectPositionBrowser {})) ); assert_eq!( g.user.data.object_position(Id::CardId(ids.minion_id)), Position::Room(ObjectPositionRoom { room_id: CLIENT_ROOM_ID.into(), room_location: ClientRoomLocation::Front.into() }) ); assert_eq!( g.user.data.object_position(Id::Identity(PlayerName::User.into())), Position::IdentityContainer(ObjectPositionIdentityContainer { owner: PlayerName::User.into() }) ); assert_snapshot!(Summary::summarize(&response)); } #[test] fn minion_with_shield() { let (mut g, _) = test_games::simple_game( Side::Champion, CardName::TestScheme31, CardName::TestMinionShield1Infernal, CardName::TestWeapon5Attack, ); g.initiate_raid(ROOM_ID); g.click_on(g.opponent_id(), "Activate"); assert_eq!(g.user.this_player.mana(), STARTING_MANA - WEAPON_COST); g.click_on(g.user_id(), "Test Weapon"); assert_eq!(g.user.this_player.mana(), STARTING_MANA - WEAPON_COST - 1); } #[test] fn fire_combat_ability() { let (mut g, ids) = test_games::simple_game( Side::Champion, CardName::TestScheme31, CardName::TestMinionEndRaid, CardName::TestWeapon3Attack12Boost3Cost, ); g.perform( Action::InitiateRaid(InitiateRaidAction { room_id: CLIENT_ROOM_ID.into() }), g.user_id(), ); g.click_on(g.opponent_id(), "Activate"); assert_eq!(g.user.this_player.mana(), 996); // Minion costs 3 to summon let response = g.click_on(g.user_id(), "Continue"); assert_eq!(g.user.this_player.mana(), 996); // Mana is unchanged assert_eq!(g.opponent.other_player.mana(), 996); assert!(!g.user.cards.get(ids.scheme_id).revealed_to_me()); // Scheme is not revealed // Still Champion turn assert!(g.user.this_player.can_take_action()); assert!(g.opponent.other_player.can_take_action()); assert!(!g.user.data.raid_active()); // No raid active due to End Raid ability assert!(!g.opponent.data.raid_active()); assert_eq!( g.user.data.object_position(Id::CardId(ids.minion_id)), Position::Room(ObjectPositionRoom { room_id: CLIENT_ROOM_ID.into(), room_location: ClientRoomLocation::Front.into() }) ); assert_eq!( g.user.data.object_position(Id::CardId(ids.scheme_id)), Position::Room(ObjectPositionRoom { room_id: CLIENT_ROOM_ID.into(), room_location: ClientRoomLocation::Back.into() }) ); assert_eq!( g.user.data.object_position(Id::Identity(PlayerName::User.into())), Position::IdentityContainer(ObjectPositionIdentityContainer { owner: PlayerName::User.into() }) ); assert_snapshot!(Summary::summarize(&response)); } #[test] fn score_scheme_card() { let (mut g, ids) = test_games::simple_game( Side::Champion, CardName::TestScheme31, CardName::TestMinionEndRaid, CardName::TestWeapon3Attack12Boost3Cost, ); g.perform( Action::InitiateRaid(InitiateRaidAction { room_id: CLIENT_ROOM_ID.into() }), g.user_id(), ); g.click_on(g.opponent_id(), "Activate"); g.click_on(g.user_id(), "Test Weapon"); let response = g.click_on(g.user_id(), "Score"); assert_eq!(g.user.this_player.score(), 1); assert_eq!(g.opponent.other_player.score(), 1); assert!(g.user.this_player.can_take_action()); assert!(g.opponent.other_player.can_take_action()); assert!(g.user.data.raid_active()); // Raid still active assert!(g.opponent.data.raid_active()); assert!(g.opponent.interface.controls().has_text("Waiting")); assert!(g.user.interface.controls().has_text("End Raid")); assert_eq!( g.user.data.object_position(Id::CardId(ids.scheme_id)), Position::Identity(ObjectPositionIdentity { owner: PlayerName::User.into() }) ); assert_eq!( g.user.data.object_position(Id::Identity(PlayerName::User.into())), Position::IdentityContainer(ObjectPositionIdentityContainer { owner: PlayerName::User.into() }) ); assert_snapshot!(Summary::summarize(&response)); } #[test] fn complete_raid() { let (mut g, ids) = test_games::simple_game( Side::Champion, CardName::TestScheme31, CardName::TestMinionEndRaid, CardName::TestWeapon3Attack12Boost3Cost, ); // Gain mana to spend an action point. Should be Overlord turn after this raid. g.perform(Action::GainMana(GainManaAction {}), g.user_id()); g.perform( Action::InitiateRaid(InitiateRaidAction { room_id: CLIENT_ROOM_ID.into() }), g.user_id(), ); g.click_on(g.opponent_id(), "Activate"); g.click_on(g.user_id(), "Test Weapon"); g.click_on(g.user_id(), "Score"); let response = g.click_on(g.user_id(), "End Raid"); assert_eq!(g.user.this_player.score(), 1); assert_eq!(g.opponent.other_player.score(), 1); assert!(g.user.other_player.can_take_action()); assert!(g.opponent.this_player.can_take_action()); assert_eq!(g.opponent.interface.main_controls_option(), None); assert_eq!(g.user.interface.main_controls_option(), None); assert!(!g.user.data.raid_active()); // Raid no longer active assert!(!g.opponent.data.raid_active()); assert_eq!( g.user.data.object_position(Id::CardId(ids.scheme_id)), Position::Identity(ObjectPositionIdentity { owner: PlayerName::User.into() }) ); assert_eq!( g.user.data.object_position(Id::Identity(PlayerName::User.into())), Position::IdentityContainer(ObjectPositionIdentityContainer { owner: PlayerName::User.into() }) ); assert_snapshot!(Summary::summarize(&response)); } #[test] fn no_activate() { let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 2, ..Args::default() }, ); g.play_from_hand(CardName::TestScheme31); g.play_from_hand(CardName::TestMinionEndRaid); g.play_from_hand(CardName::TestWeapon3Attack12Boost3Cost); g.initiate_raid(ROOM_ID); let response = g.click_on(g.opponent_id(), "Pass"); assert!(g.user.interface.controls().has_text("Score")); assert!(g.user.interface.controls().has_text("End Raid")); assert!(g.opponent.interface.controls().has_text("Waiting")); assert_snapshot!(Summary::summarize(&response)); } #[test] fn raid_vault() { let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 1, opponent_deck_top: Some(CardName::TestScheme31), ..Args::default() }, ); g.play_with_target_room(CardName::TestMinionEndRaid, RoomId::Vault); g.play_from_hand(CardName::TestWeapon3Attack12Boost3Cost); g.initiate_raid(RoomId::Vault); g.click_on(g.opponent_id(), "Activate"); let response = g.click_on(g.user_id(), "Test Weapon"); assert!(g.user.interface.controls().has_text("Score")); assert!(g.opponent.interface.controls().has_text("Waiting")); // TODO: Deck top should not be revealed to overlord assert_snapshot!(Summary::summarize(&response)); } #[test] fn raid_sanctum() {
#[test] fn raid_crypts() { let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 1, opponent_discard: Some(CardName::TestScheme31), ..Args::default() }, ); g.add_to_hand(CardName::TestScheme31); g.play_with_target_room(CardName::TestMinionEndRaid, RoomId::Crypts); g.play_from_hand(CardName::TestWeapon3Attack12Boost3Cost); g.initiate_raid(RoomId::Crypts); g.click_on(g.opponent_id(), "Activate"); let response = g.click_on(g.user_id(), "Test Weapon"); assert!(g.user.interface.controls().has_text("Score")); assert!(g.opponent.interface.controls().has_text("Waiting")); assert_snapshot!(Summary::summarize(&response)); } #[test] fn raid_vault_twice() { let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 1, opponent_deck_top: Some(CardName::TestScheme31), ..Args::default() }, ); g.play_with_target_room(CardName::TestMinionEndRaid, RoomId::Vault); g.play_from_hand(CardName::TestWeapon3Attack12Boost3Cost); g.initiate_raid(RoomId::Vault); g.click_on(g.opponent_id(), "Activate"); g.click_on(g.user_id(), "Test Weapon"); g.click_on(g.user_id(), "Score"); g.click_on(g.user_id(), "End Raid"); g.initiate_raid(RoomId::Vault); // Should not need to activate when already revealed assert!(!g.opponent.interface.controls().has_text("Activate")); // Champion spent mana on playing + activating weapon, overlord on summoning // minion assert_eq!(g.me().mana(), STARTING_MANA - 4); assert_eq!(g.you().mana(), STARTING_MANA - 3); // Should skip Activation phase: assert!(g.opponent.interface.controls().has_text("Waiting")); assert!(g.user.interface.controls().has_text("Test Weapon")); g.click_on(g.user_id(), "Test Weapon"); // Champion spends mana again to use weapon, Overlord mana is unchanged. assert_eq!(g.me().mana(), STARTING_MANA - 5); assert_eq!(g.you().mana(), STARTING_MANA - 3); // Scheme should not longer be on top for second raid assert!(g.opponent.interface.controls().has_text("Waiting")); assert!(g.user.interface.controls().has_text("End Raid")); assert!(!g.user.interface.controls().has_text("Score")); } #[test] fn raid_no_defenders() { let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 1, ..Args::default() }, ); g.play_from_hand(CardName::TestScheme31); let response = g.initiate_raid(ROOM_ID); // Should immediately jump to the Score action assert!(g.user.interface.controls().has_text("Score")); assert!(g.user.interface.controls().has_text("End Raid")); assert!(g.opponent.interface.controls().has_text("Waiting")); assert_snapshot!(Summary::summarize(&response)); } #[test] fn raid_vault_no_defenders() { let mut g = new_game( Side::Champion, Args { opponent_deck_top: Some(CardName::TestScheme31), ..Args::default() }, ); g.initiate_raid(RoomId::Vault); // Should immediately jump to the Score action assert!(g.user.interface.controls().has_text("Score")); assert!(g.user.interface.controls().has_text("End Raid")); assert!(g.opponent.interface.controls().has_text("Waiting")); } #[test] fn raid_no_occupants() { let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 1, ..Args::default() }, ); g.play_from_hand(CardName::TestMinionEndRaid); g.play_from_hand(CardName::TestWeapon3Attack12Boost3Cost); let result = g.perform_action( Action::InitiateRaid(InitiateRaidAction { room_id: CLIENT_ROOM_ID.into() }), g.user_id(), ); assert_error(result); } #[test] fn raid_no_occupants_or_defenders() { let mut g = new_game(Side::Champion, Args::default()); let response = g.perform_action( Action::InitiateRaid(InitiateRaidAction { room_id: CLIENT_ROOM_ID.into() }), g.user_id(), ); assert_error(response); } #[test] fn raid_two_defenders() { let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 2, opponent_deck_top: Some(CardName::TestScheme31), ..Args::default() }, ); g.play_with_target_room(CardName::TestMinionEndRaid, RoomId::Vault); g.play_with_target_room(CardName::TestMinionDealDamage, RoomId::Vault); g.play_from_hand(CardName::TestWeapon3Attack12Boost3Cost); g.initiate_raid(RoomId::Vault); g.click_on(g.opponent_id(), "Activate"); let response = g.click_on(g.user_id(), "Test Weapon"); assert!(g.user.interface.controls().has_text("Advance")); assert!(g.user.interface.controls().has_text("Retreat")); assert!(g.opponent.interface.controls().has_text("Waiting")); assert_snapshot!(Summary::summarize(&response)); } #[test] fn raid_two_defenders_advance() { let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 2, opponent_deck_top: Some(CardName::TestScheme31), ..Args::default() }, ); g.play_with_target_room(CardName::TestMinionEndRaid, RoomId::Vault); g.play_with_target_room(CardName::TestMinionDealDamage, RoomId::Vault); g.play_from_hand(CardName::TestWeapon3Attack12Boost3Cost); g.initiate_raid(RoomId::Vault); g.click_on(g.opponent_id(), "Activate"); g.click_on(g.user_id(), "Test Weapon"); let response = g.click_on(g.user_id(), "Advance"); assert!(g.user.interface.controls().has_text("Test Weapon")); assert!(g.opponent.interface.controls().has_text("Waiting")); assert_snapshot!(Summary::summarize(&response)); } #[test] fn raid_two_defenders_retreat() { let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 2, opponent_deck_top: Some(CardName::TestScheme31), ..Args::default() }, ); g.play_with_target_room(CardName::TestMinionEndRaid, RoomId::Vault); g.play_with_target_room(CardName::TestMinionDealDamage, RoomId::Vault); g.play_from_hand(CardName::TestWeapon3Attack12Boost3Cost); g.initiate_raid(RoomId::Vault); g.click_on(g.opponent_id(), "Activate"); g.click_on(g.user_id(), "Test Weapon"); let response = g.click_on(g.user_id(), "Retreat"); assert!(!g.user.data.raid_active()); assert!(!g.opponent.data.raid_active()); assert_eq!(g.opponent.interface.main_controls_option(), None); assert_eq!(g.user.interface.main_controls_option(), None); assert_eq!( g.user.data.object_position(Id::Identity(PlayerName::User.into())), Position::IdentityContainer(ObjectPositionIdentityContainer { owner: PlayerName::User.into() }) ); assert_snapshot!(Summary::summarize(&response)); } #[test] fn raid_two_defenders_full_raid() { let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 2, opponent_deck_top: Some(CardName::TestScheme31), ..Args::default() }, ); g.play_with_target_room(CardName::TestMinionEndRaid, RoomId::Vault); g.play_with_target_room(CardName::TestMinionDealDamage, RoomId::Vault); g.play_from_hand(CardName::TestWeapon3Attack12Boost3Cost); g.initiate_raid(RoomId::Vault); g.click_on(g.opponent_id(), "Activate"); g.click_on(g.user_id(), "Test Weapon"); g.click_on(g.user_id(), "Advance"); g.click_on(g.user_id(), "Test Weapon"); let response = g.click_on(g.user_id(), "Score"); assert_eq!(g.me().mana(), STARTING_MANA - 5); assert_eq!(g.you().mana(), STARTING_MANA - 4); assert_snapshot!(Summary::summarize(&response)); } #[test] fn raid_deal_damage_game_over() { let mut g = new_game(Side::Overlord, Args { ..Args::default() }); // Two 'deal 1 damage' defenders are needed because the Champion draws a card // for turn g.play_with_target_room(CardName::TestMinionDealDamage, RoomId::Vault); g.play_with_target_room(CardName::TestMinionDealDamage, RoomId::Vault); spend_actions_until_turn_over(&mut g, Side::Overlord); assert!(g.dawn()); g.initiate_raid(RoomId::Vault); g.click_on(g.user_id(), "Activate"); g.click_on(g.opponent_id(), "Continue"); g.click_on(g.opponent_id(), "Advance"); g.click_on(g.opponent_id(), "Continue"); assert!(g.is_victory_for_player(Side::Overlord)); } #[test] fn raid_two_defenders_cannot_afford_second() { let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 2, opponent_deck_top: Some(CardName::TestScheme31), opponent_mana: 1, ..Args::default() }, ); g.play_with_target_room(CardName::TestMinionDealDamage, RoomId::Vault); g.play_with_target_room(CardName::TestMinionEndRaid, RoomId::Vault); g.play_from_hand(CardName::TestWeapon3Attack12Boost3Cost); g.initiate_raid(RoomId::Vault); g.click_on(g.opponent_id(), "Activate"); g.click_on(g.user_id(), "Test Weapon"); let response = g.click_on(g.user_id(), "Score"); assert_eq!(g.me().mana(), STARTING_MANA - 4); assert_eq!(g.you().mana(), 0); assert_snapshot!(Summary::summarize(&response)); } #[test] fn raid_add_defender() { let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 2, ..Args::default() }, ); g.play_from_hand(CardName::TestMinionEndRaid); g.play_from_hand(CardName::TestScheme31); assert!(g.dawn()); // Raid 1 g.initiate_raid(ROOM_ID); g.click_on(g.opponent_id(), "Activate"); g.click_on(g.user_id(), "Continue"); assert!(!g.user.data.raid_active()); g.play_from_hand(CardName::TestWeapon3Attack12Boost3Cost); // Raid 2, no activate g.initiate_raid(ROOM_ID); g.click_on(g.user_id(), "Test Weapon"); g.click_on(g.user_id(), "Score"); g.click_on(g.user_id(), "End Raid"); assert!(!g.user.data.raid_active()); // Opponent Turn assert!(g.dusk()); g.play_from_hand(CardName::TestMinionDealDamage); g.play_from_hand(CardName::TestScheme31); g.perform(Action::GainMana(GainManaAction {}), g.opponent_id()); // User Turn, Raid 3 assert!(g.dawn()); g.initiate_raid(ROOM_ID); g.click_on(g.opponent_id(), "Activate"); g.click_on(g.user_id(), "Test Weapon"); g.click_on(g.user_id(), "Advance"); let response = g.click_on(g.user_id(), "Test Weapon"); assert_snapshot!(Summary::summarize(&response)); }
let mut g = new_game( Side::Champion, Args { turn: Some(Side::Overlord), actions: 1, ..Args::default() }, ); g.add_to_hand(CardName::TestScheme31); g.play_with_target_room(CardName::TestMinionEndRaid, RoomId::Sanctum); g.play_from_hand(CardName::TestWeapon3Attack12Boost3Cost); g.initiate_raid(RoomId::Sanctum); g.click_on(g.opponent_id(), "Activate"); let response = g.click_on(g.user_id(), "Test Weapon"); assert!(g.user.interface.controls().has_text("Score")); assert!(g.opponent.interface.controls().has_text("Waiting")); assert_snapshot!(Summary::summarize(&response)); }
subprocess_linux.go
// Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build linux // +build linux package subprocess import ( "os/exec" "syscall" ) func applyOSSpecificCmdModifications(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{ // This is Linux-specific and will cause the subprocess to be killed by the OS if // the collector dies Pdeathsig: syscall.SIGTERM, } }
cached_post.py
"""Manages cached post data.""" import math import collections import logging import ujson as json from toolz import partition_all from hive.db.adapter import Db from hive.utils.post import post_basic, post_legacy, post_payout, post_stats from hive.utils.timer import Timer from hive.indexer.accounts import Accounts log = logging.getLogger(__name__) DB = Db.instance() # levels of post dirtiness, in order of decreasing priority LEVELS = ['insert', 'payout', 'update', 'upvote', 'recount'] def _keyify(items): return dict(map(lambda x: ("val_%d" % x[0], x[1]), enumerate(items))) class CachedPost: """Maintain update queue and writing to `hive_posts_cache`.""" # cursor signifying upper bound of cached post span _last_id = -1 # cached id map _ids = {} # urls which are missing from id map _noids = set() # dirty posts; {key: dirty_level} _queue = collections.OrderedDict() # new promoted values, pending write _pending_promoted = {} @classmethod def update_promoted_amount(cls, post_id, amount): """Set a new pending amount for a post for its next update.""" cls._pending_promoted[post_id] = amount @classmethod def _dirty(cls, level, author, permlink, pid=None): """Mark a post as dirty.""" assert level in LEVELS, "invalid level {}".format(level) mode = LEVELS.index(level) url = author + '/' + permlink # add to appropriate queue. if url not in cls._queue: cls._queue[url] = mode # upgrade priority if needed elif cls._queue[url] > mode: cls._queue[url] = mode # add to id map, or register missing if pid and url in cls._ids: assert pid == cls._ids[url], "pid map conflict #78" elif pid: cls._ids[url] = pid else: cls._noids.add(url) @classmethod def _get_id(cls, url): """Given a post url, get its id.""" if url in cls._ids: return cls._ids[url] raise Exception("requested id for %s not in map" % url) @classmethod def recount(cls, author, permlink, pid=None): """Force a child re-count.""" cls._dirty('recount', author, permlink, pid) @classmethod def vote(cls, author, permlink, pid=None): """Handle a post dirtied by a `vote` op.""" cls._dirty('upvote', author, permlink, pid) Accounts.dirty(set([author])) # rep changed @classmethod def insert(cls, author, permlink, pid): """Handle a post created by a `comment` op.""" cls._dirty('insert', author, permlink, pid) @classmethod def update(cls, author, permlink, pid): """Handle a post updated by a `comment` op.""" cls._dirty('update', author, permlink, pid) @classmethod def delete(cls, post_id, author, permlink): """Handle a post deleted by a `delete_comment` op. With steemd, posts can be 'deleted' or unallocated in certain conditions. It requires foregoing convenient assumptions, e.g.: - author/permlink is unique and always references the same post - you can always get_content on any author/permlink you see in an op """ DB.query("DELETE FROM hive_posts_cache WHERE post_id = :id", id=post_id) # if it was queued for a write, remove it url = author+'/'+permlink if url in cls._queue: del cls._queue[url] if url in cls._ids: del cls._ids[url] @classmethod def undelete(cls, post_id, author, permlink): """Handle a post 'undeleted' by a `comment` op. 'Undeletion' occurs when hive detects that a previously deleted author/permlink combination has been reused on a new post. Hive does not delete hive_posts entries because they are currently irreplaceable in case of a fork. Instead, we reuse the slot. It's important to immediately insert a placeholder in the cache table since hive only scans forward. This row's properties push it to the front of update-immediately queue. Alternate ways of handling undeletes: - delete row from hive_posts so that it can be re-indexed (re-id'd) - comes at a risk of losing expensive entry on fork (and no undo) - create undo table for hive_posts, hive_follows, etc, & link to block - rely on steemd's post.id instead of database autoincrement - requires way to query steemd post objects by id to be useful - batch get_content_by_ids in steemd would be /huge/ speedup - create a consistent cache queue table or dirty flag col """ # do not force-write unless cache spans this id. if post_id > cls.last_id(): cls.insert(author, permlink, post_id) return # force-create dummy row to ensure cache is aware. only needed when # cache already spans this id, in case in-mem buffer is lost. default # value for payout_at ensures that it will get picked up for update. DB.query(cls._insert({ 'post_id': post_id, 'author': author, 'permlink': permlink})) cls.update(author, permlink, post_id) @classmethod def
(cls, steem, trx=False, spread=1, full_total=None): """Process all posts which have been marked as dirty.""" cls._load_noids() # load missing ids assert spread == 1, "not fully tested, use with caution" counts = {} tuples = [] for level in LEVELS: tups = cls._get_tuples_for_level(level, spread) counts[level] = len(tups) tuples.extend(tups) if trx or len(tuples) > 250: changed = filter(lambda t: t[1], counts.items()) summary = list(map(lambda group: "%d %ss" % group[::-1], changed)) summary = ', '.join(summary) if summary else 'none' log.info("[PREP] posts cache process: %s", summary) cls._update_batch(steem, tuples, trx, full_total=full_total) for url, _, _ in tuples: del cls._queue[url] if url in cls._ids: del cls._ids[url] return counts @classmethod def _get_tuples_for_level(cls, level, fraction=1): """Query tuples to be updated. Given a specific flush level (insert, payout, update, upvote), returns a list of tuples to be passed to _update_batch, in the form of: `[(url, id, level)*]` """ mode = LEVELS.index(level) urls = [url for url, i in cls._queue.items() if i == mode] if fraction > 1 and level != 'insert': # inserts must be full flush urls = urls[0:math.ceil(len(urls) / fraction)] return [(url, cls._get_id(url), level) for url in urls] @classmethod def _load_noids(cls): """Load ids for posts we don't know the ids of. When posts are marked dirty, specifying the id is optional because a successive call might be able to provide it "for free". Before flushing changes this method should be called to fill in any gaps. """ from hive.indexer.posts import Posts noids = cls._noids - set(cls._ids.keys()) tuples = [(Posts.get_id(*url.split('/')), url) for url in noids] for pid, url in tuples: assert pid, "WARNING: missing id for %s" % url cls._ids[url] = pid cls._noids = set() return len(tuples) @classmethod def _select_paidout_tuples(cls, date): """Query hive_posts_cache for payout sweep. Select all posts which should have been paid out before `date` yet do not have the `is_paidout` flag set. We perform this sweep to ensure that we always have accurate final payout state. Since payout values vary even between votes, we'd have stale data if we didn't sweep, and only waited for incoming votes before an update. """ from hive.indexer.posts import Posts sql = """SELECT post_id FROM hive_posts_cache WHERE is_paidout = '0' AND payout_at <= :date""" ids = DB.query_col(sql, date=date) if not ids: return [] sql = """SELECT id, author, permlink FROM hive_posts WHERE id IN :ids""" results = DB.query_all(sql, ids=tuple(ids)) return Posts.save_ids_from_tuples(results) @classmethod def dirty_paidouts(cls, date): """Mark dirty all paidout posts not yet updated in db.""" paidout = cls._select_paidout_tuples(date) authors = set() for (pid, author, permlink) in paidout: authors.add(author) cls._dirty('payout', author, permlink, pid) Accounts.dirty(authors) # force-update accounts on payout if len(paidout) > 200: log.info("[PREP] Found %d payouts for %d authors since %s", len(paidout), len(authors), date) return len(paidout) @classmethod def _select_missing_tuples(cls, last_cached_id, limit=1000000): """Fetch posts inserted into main posts table but not cache.""" from hive.indexer.posts import Posts sql = """SELECT id, author, permlink, promoted FROM hive_posts WHERE is_deleted = '0' AND id > :id ORDER BY id LIMIT :limit""" results = DB.query_all(sql, id=last_cached_id, limit=limit) return Posts.save_ids_from_tuples(results) @classmethod def dirty_missing(cls, limit=250000): """Mark dirty all hive_posts records not yet written to cache.""" from hive.indexer.posts import Posts # cached posts inserted sequentially, so compare MAX(id)'s last_cached_id = cls.last_id() last_post_id = Posts.last_id() gap = last_post_id - last_cached_id if gap: missing = cls._select_missing_tuples(last_cached_id, limit) for pid, author, permlink, promoted in missing: if promoted > 0: # ensure we don't miss promote amount cls.update_promoted_amount(pid, promoted) cls._dirty('insert', author, permlink, pid) return gap @classmethod def recover_missing_posts(cls, steem): """Startup routine that cycles through missing posts. This is used for (1) initial sync, and (2) recovering missing cache records upon launch if hive fast-sync was interrupted. """ gap = cls.dirty_missing() log.info("[INIT] %d missing post cache entries", gap) while cls.flush(steem, trx=True, full_total=gap)['insert']: gap = cls.dirty_missing() @classmethod def _update_batch(cls, steem, tuples, trx=True, full_total=None): """Fetch, process, and write a batch of posts. Given a set of posts, fetch from steemd and write them to the db. The `tuples` arg is the form of `[(url, id, level)*]` representing posts which are to be fetched from steemd and updated in cache. Regarding _bump_last_id: there's a rare edge case when the last hive_post entry has been deleted "in the future" (ie, we haven't seen the delete op yet). So even when the post is not found (i.e. `not post['author']`), it's important to advance _last_id, because this cursor is used to deduce any missing cache entries. """ timer = Timer(total=len(tuples), entity='post', laps=['rps', 'wps'], full_total=full_total) tuples = sorted(tuples, key=lambda x: x[1]) # enforce ASC id's for tups in partition_all(1000, tuples): timer.batch_start() buffer = [] post_args = [tup[0].split('/') for tup in tups] posts = steem.get_content_batch(post_args) post_ids = [tup[1] for tup in tups] post_levels = [tup[2] for tup in tups] for pid, post, level in zip(post_ids, posts, post_levels): if post['author']: buffer.extend(cls._sql(pid, post, level=level)) else: # When a post has been deleted (or otherwise DNE), # steemd simply returns a blank post object w/ all # fields blank. While it's best to not try to cache # already-deleted posts, it can happen during missed # post sweep and while using `trail_blocks` > 0. pass cls._bump_last_id(pid) timer.batch_lap() DB.batch_queries(buffer, trx) timer.batch_finish(len(posts)) if len(tuples) >= 1000: log.info(timer.batch_status()) @classmethod def last_id(cls): """Retrieve the latest post_id that was cached.""" if cls._last_id == -1: # after initial query, we maintain last_id w/ _bump_last_id() sql = "SELECT COALESCE(MAX(post_id), 0) FROM hive_posts_cache" cls._last_id = DB.query_one(sql) return cls._last_id @classmethod def _bump_last_id(cls, next_id): """Update our last_id based on a recent insert.""" last_id = cls.last_id() if next_id <= last_id: return if next_id - last_id > 2: cls._ensure_safe_gap(last_id, next_id) if next_id - last_id > 4: # gap of 2 is common due to deletions. report on larger gaps. log.warning("skipping post ids %d -> %d", last_id, next_id) cls._last_id = next_id @classmethod def _ensure_safe_gap(cls, last_id, next_id): """Paranoid check of important operating assumption.""" sql = """ SELECT COUNT(*) FROM hive_posts WHERE id BETWEEN :x1 AND :x2 AND is_deleted = '0' """ missing_posts = DB.query_one(sql, x1=(last_id + 1), x2=(next_id - 1)) if not missing_posts: return raise Exception("found large cache gap: %d --> %d (%d)" % (last_id, next_id, missing_posts)) @classmethod def _sql(cls, pid, post, level=None): """Given a post and "update level", generate SQL edit statement. Valid levels are: - `insert`: post does not yet exist in cache - `update`: post was modified - `payout`: post was paidout - `upvote`: post payout/votes changed """ #pylint: disable=bad-whitespace assert post['author'], "post {} is blank".format(pid) # last-minute sanity check to ensure `pid` is correct #78 pid2 = cls._get_id(post['author']+'/'+post['permlink']) assert pid == pid2, "hpc id %d maps to %d" % (pid, pid2) # inserts always sequential. if pid > last_id, this operation # *must* be an insert; so `level` must not be any form of update. if pid > cls.last_id() and level != 'insert': raise Exception("WARNING: new pid, but level=%s. #%d vs %d, %s" % (level, pid, cls.last_id(), repr(post))) # start building the queries tag_sqls = [] values = [('post_id', pid)] # immutable; write only once (*edge case: undeleted posts) if level == 'insert': values.extend([ ('author', post['author']), ('permlink', post['permlink']), ('category', post['category']), ('depth', post['depth'])]) # always write, unless simple vote update if level in ['insert', 'payout', 'update']: basic = post_basic(post) values.extend([ ('created_at', post['created']), # immutable* ('updated_at', post['last_update']), ('title', post['title']), ('payout_at', basic['payout_at']), # immutable* ('preview', basic['preview']), ('body', basic['body']), ('img_url', basic['image']), ('is_nsfw', basic['is_nsfw']), ('is_declined', basic['is_payout_declined']), ('is_full_power', basic['is_full_power']), ('is_paidout', basic['is_paidout']), ('json', json.dumps(basic['json_metadata'])), ('raw_json', json.dumps(post_legacy(post))), ]) # update tags if action is insert/update and is root post if level in ['insert', 'update'] and not post['depth']: diff = level != 'insert' # do not attempt tag diff on insert tag_sqls.extend(cls._tag_sqls(pid, basic['tags'], diff=diff)) # if there's a pending promoted value to write, pull it out if pid in cls._pending_promoted: bal = cls._pending_promoted.pop(pid) values.append(('promoted', bal)) # update unconditionally payout = post_payout(post) stats = post_stats(post) values.extend([ ('payout', "%f" % payout['payout']), ('rshares', "%d" % payout['rshares']), ('votes', "%s" % payout['csvotes']), ('sc_trend', "%f" % payout['sc_trend']), ('sc_hot', "%f" % payout['sc_hot']), ('flag_weight', "%f" % stats['flag_weight']), ('total_votes', "%d" % stats['total_votes']), ('up_votes', "%d" % stats['up_votes']), ('is_hidden', "%d" % stats['hide']), ('is_grayed', "%d" % stats['gray']), ('author_rep', "%f" % stats['author_rep']), ('children', "%d" % min(post['children'], 32767)), ]) # if recounting, update the parent next pass. if level == 'recount' and post['depth']: cls.recount(post['parent_author'], post['parent_permlink']) # build the post insert/update SQL, add tag SQLs if level == 'insert': sql = cls._insert(values) else: sql = cls._update(values) return [sql] + tag_sqls @classmethod def _tag_sqls(cls, pid, tags, diff=True): """Generate SQL "deltas" for a post_id's associated tags.""" next_tags = set(tags) curr_tags = set() if diff: sql = "SELECT tag FROM hive_post_tags WHERE post_id = :id" curr_tags = set(DB.query_col(sql, id=pid)) to_rem = (curr_tags - next_tags) if to_rem: sql = "DELETE FROM hive_post_tags WHERE post_id = :id AND tag IN :tags" yield (sql, dict(id=pid, tags=tuple(to_rem))) to_add = (next_tags - curr_tags) if to_add: params = _keyify(to_add) vals = ["(:id, :%s)" % key for key in params.keys()] sql = "INSERT INTO hive_post_tags (post_id, tag) VALUES %s" sql += " ON CONFLICT DO NOTHING" # (conflicts due to collation) yield (sql % ','.join(vals), {'id': pid, **params}) @classmethod def _insert(cls, values): return DB.build_insert('hive_posts_cache', values, pk='post_id') @classmethod def _update(cls, values): return DB.build_update('hive_posts_cache', values, pk='post_id')
flush
query.py
import six class Query(object): """ Query is used to build complex queries that have more parameters than just the query string. The query string is set in the constructor, and other options have setter functions. The setter functions return the query object, so they can be chained, i.e. `Query("foo").verbatim().filter(...)` etc. """ def __init__(self, query_string): """ Create a new query object. The query string is set in the constructor, and other options have setter functions. """ self._query_string = query_string self._offset = 0 self._num = 10 self._no_content = False self._no_stopwords = False self._fields = None self._verbatim = False self._with_payloads = False self._with_scores = False self._scorer = False self._filters = list() self._ids = None self._slop = -1 self._in_order = False self._sortby = None self._return_fields = [] self._summarize_fields = [] self._highlight_fields = [] self._language = None def query_string(self): """ Return the query string of this query only """ return self._query_string def
(self, *ids): """ Limit the results to a specific set of pre-known document ids of any length """ self._ids = ids return self def return_fields(self, *fields): """ Add fields to return fields """ self._return_fields += fields return self def return_field(self, field, as_field=None): """ Add field to return fields (Optional: add 'AS' name to the field) """ self._return_fields.append(field) if as_field is not None: self._return_fields += ("AS", as_field) return self def _mk_field_list(self, fields): if not fields: return [] return [fields] if isinstance(fields, six.string_types) else list(fields) def summarize(self, fields=None, context_len=None, num_frags=None, sep=None): """ Return an abridged format of the field, containing only the segments of the field which contain the matching term(s). If `fields` is specified, then only the mentioned fields are summarized; otherwise all results are summarized. Server side defaults are used for each option (except `fields`) if not specified - **fields** List of fields to summarize. All fields are summarized if not specified - **context_len** Amount of context to include with each fragment - **num_frags** Number of fragments per document - **sep** Separator string to separate fragments """ args = ['SUMMARIZE'] fields = self._mk_field_list(fields) if fields: args += ['FIELDS', str(len(fields))] + fields if context_len is not None: args += ['LEN', str(context_len)] if num_frags is not None: args += ['FRAGS', str(num_frags)] if sep is not None: args += ['SEPARATOR', sep] self._summarize_fields = args return self def highlight(self, fields=None, tags=None): """ Apply specified markup to matched term(s) within the returned field(s) - **fields** If specified then only those mentioned fields are highlighted, otherwise all fields are highlighted - **tags** A list of two strings to surround the match. """ args = ['HIGHLIGHT'] fields = self._mk_field_list(fields) if fields: args += ['FIELDS', str(len(fields))] + fields if tags: args += ['TAGS'] + list(tags) self._highlight_fields = args return self def language(self, language): """ Analyze the query as being in the specified language :param language: The language (e.g. `chinese` or `english`) """ self._language = language return self def slop(self, slop): """ Allow a masimum of N intervening non matched terms between phrase terms (0 means exact phrase) """ self._slop = slop return self def in_order(self): """ Match only documents where the query terms appear in the same order in the document. i.e. for the query 'hello world', we do not match 'world hello' """ self._in_order = True return self def scorer(self, scorer): """ Use a different scoring function to evaluate document relevance. Default is `TFIDF` :param scorer: The scoring function to use (e.g. `TFIDF.DOCNORM` or `BM25`) """ self._scorer = scorer return self def get_args(self): """ Format the redis arguments for this query and return them """ args = [self._query_string] if self._no_content: args.append('NOCONTENT') if self._fields: args.append('INFIELDS') args.append(len(self._fields)) args += self._fields if self._verbatim: args.append('VERBATIM') if self._no_stopwords: args.append('NOSTOPWORDS') if self._filters: for flt in self._filters: assert isinstance(flt, Filter) args += flt.args if self._with_payloads: args.append('WITHPAYLOADS') if self._scorer: args += ['SCORER', self._scorer] if self._with_scores: args.append('WITHSCORES') if self._ids: args.append('INKEYS') args.append(len(self._ids)) args += self._ids if self._slop >= 0: args += ['SLOP', self._slop] if self._in_order: args.append('INORDER') if self._return_fields: args.append('RETURN') args.append(len(self._return_fields)) args += self._return_fields if self._sortby: assert isinstance(self._sortby, SortbyField) args.append('SORTBY') args += self._sortby.args if self._language: args += ['LANGUAGE', self._language] args += self._summarize_fields + self._highlight_fields args += ["LIMIT", self._offset, self._num] return args def paging(self, offset, num): """ Set the paging for the query (defaults to 0..10). - **offset**: Paging offset for the results. Defaults to 0 - **num**: How many results do we want """ self._offset = offset self._num = num return self def verbatim(self): """ Set the query to be verbatim, i.e. use no query expansion or stemming """ self._verbatim = True return self def no_content(self): """ Set the query to only return ids and not the document content """ self._no_content = True return self def no_stopwords(self): """ Prevent the query from being filtered for stopwords. Only useful in very big queries that you are certain contain no stopwords. """ self._no_stopwords = True return self def with_payloads(self): """ Ask the engine to return document payloads """ self._with_payloads = True return self def with_scores(self): """ Ask the engine to return document search scores """ self._with_scores = True return self def limit_fields(self, *fields): """ Limit the search to specific TEXT fields only - **fields**: A list of strings, case sensitive field names from the defined schema """ self._fields = fields return self def add_filter(self, flt): """ Add a numeric or geo filter to the query. **Currently only one of each filter is supported by the engine** - **flt**: A NumericFilter or GeoFilter object, used on a corresponding field """ self._filters.append(flt) return self def sort_by(self, field, asc=True): """ Add a sortby field to the query - **field** - the name of the field to sort by - **asc** - when `True`, sorting will be done in asceding order """ self._sortby = SortbyField(field, asc) return self class Filter(object): def __init__(self, keyword, field, *args): self.args = [keyword, field] + list(args) class NumericFilter(Filter): INF = '+inf' NEG_INF = '-inf' def __init__(self, field, minval, maxval, minExclusive = False, maxExclusive = False): args = [ minval if not minExclusive else '({}'.format(minval), maxval if not maxExclusive else '({}'.format(maxval), ] Filter.__init__(self, 'FILTER', field, *args) class GeoFilter(Filter): METERS = 'm' KILOMETERS = 'km' FEET = 'ft' MILES = 'mi' def __init__(self, field, lon, lat, radius, unit = KILOMETERS): Filter.__init__(self, 'GEOFILTER', field, lon, lat, radius, unit) class SortbyField(object): def __init__(self, field, asc=True): self.args = [field, 'ASC' if asc else 'DESC']
limit_ids
network_unsafe.go
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sandbox import ( "syscall" "unsafe" "golang.org/x/sys/unix" ) type ethtoolValue struct { cmd uint32 val uint32 } type ifreq struct { ifrName [unix.IFNAMSIZ]byte ifrData *ethtoolValue } const ( _ETHTOOL_GGSO = 0x00000023 ) func isGSOEnabled(fd int, intf string) (bool, error)
{ val := ethtoolValue{ cmd: _ETHTOOL_GGSO, } var name [unix.IFNAMSIZ]byte copy(name[:], []byte(intf)) ifr := ifreq{ ifrName: name, ifrData: &val, } if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), unix.SIOCETHTOOL, uintptr(unsafe.Pointer(&ifr))); err != 0 { return false, err } return val.val != 0, nil }
isolated_creds.py
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import netaddr from tempest import auth from tempest import clients from tempest.common import cred_provider from tempest.common.utils import data_utils from tempest import config from tempest import exceptions from tempest.openstack.common import log as logging CONF = config.CONF LOG = logging.getLogger(__name__) class IsolatedCreds(cred_provider.CredentialProvider): def __init__(self, name, tempest_client=True, interface='json', password='pass', network_resources=None): super(IsolatedCreds, self).__init__(name, tempest_client, interface, password, network_resources) self.network_resources = network_resources self.isolated_creds = {} self.isolated_net_resources = {} self.ports = [] self.tempest_client = tempest_client self.interface = interface self.password = password self.identity_admin_client, self.network_admin_client = ( self._get_admin_clients()) def _get_admin_clients(self): """ Returns a tuple with instances of the following admin clients (in this order): identity network """ if self.tempest_client: os = clients.AdminManager(interface=self.interface) else: os = clients.OfficialClientManager( auth.get_default_credentials('identity_admin') ) return os.identity_client, os.network_client def _create_tenant(self, name, description): if self.tempest_client: _, tenant = self.identity_admin_client.create_tenant( name=name, description=description) else: tenant = self.identity_admin_client.tenants.create( name, description=description) return tenant def _get_tenant_by_name(self, name): if self.tempest_client: _, tenant = self.identity_admin_client.get_tenant_by_name(name) else: tenants = self.identity_admin_client.tenants.list() for ten in tenants: if ten['name'] == name: tenant = ten break else: raise exceptions.NotFound('No such tenant') return tenant def _create_user(self, username, password, tenant, email): if self.tempest_client: _, user = self.identity_admin_client.create_user(username, password, tenant['id'], email) else: user = self.identity_admin_client.users.create(username, password, email, tenant_id=tenant.id) return user def _get_user(self, tenant, username): if self.tempest_client: _, user = self.identity_admin_client.get_user_by_username( tenant['id'], username) else: user = self.identity_admin_client.users.get(username) return user def _list_roles(self): if self.tempest_client: _, roles = self.identity_admin_client.list_roles() else: roles = self.identity_admin_client.roles.list() return roles def _assign_user_role(self, tenant, user, role_name): role = None try: roles = self._list_roles() if self.tempest_client: role = next(r for r in roles if r['name'] == role_name) else: role = next(r for r in roles if r.name == role_name) except StopIteration: msg = 'No "%s" role found' % role_name raise exceptions.NotFound(msg) if self.tempest_client: self.identity_admin_client.assign_user_role(tenant['id'], user['id'], role['id']) else: self.identity_admin_client.roles.add_user_role(user.id, role.id, tenant.id) def _delete_user(self, user): if self.tempest_client: self.identity_admin_client.delete_user(user) else: self.identity_admin_client.users.delete(user) def _delete_tenant(self, tenant): if self.tempest_client: self.identity_admin_client.delete_tenant(tenant) else: self.identity_admin_client.tenants.delete(tenant) def _create_creds(self, suffix="", admin=False): """Create random credentials under the following schema. If the name contains a '.' is the full class path of something, and we don't really care. If it isn't, it's probably a meaningful name, so use it. For logging purposes, -user and -tenant are long and redundant, don't use them. The user# will be sufficient to figure it out. """ if '.' in self.name: root = "" else: root = self.name tenant_name = data_utils.rand_name(root) + suffix tenant_desc = tenant_name + "-desc" tenant = self._create_tenant(name=tenant_name, description=tenant_desc) username = data_utils.rand_name(root) + suffix email = data_utils.rand_name(root) + suffix + "@example.com" user = self._create_user(username, self.password, tenant, email) # NOTE(andrey-mp): user needs this role to create containers in swift swift_operator_role = CONF.object_storage.operator_role self._assign_user_role(tenant, user, swift_operator_role) if admin: self._assign_user_role(tenant, user, CONF.identity.admin_role) return self._get_credentials(user, tenant) def _get_credentials(self, user, tenant): if self.tempest_client: user_get = user.get tenant_get = tenant.get else: user_get = user.__dict__.get tenant_get = tenant.__dict__.get return auth.get_credentials( username=user_get('name'), user_id=user_get('id'), tenant_name=tenant_get('name'), tenant_id=tenant_get('id'), password=self.password) def _create_network_resources(self, tenant_id): network = None subnet = None router = None # Make sure settings if self.network_resources: if self.network_resources['router']: if (not self.network_resources['subnet'] or not self.network_resources['network']): raise exceptions.InvalidConfiguration( 'A router requires a subnet and network') elif self.network_resources['subnet']: if not self.network_resources['network']: raise exceptions.InvalidConfiguration( 'A subnet requires a network') elif self.network_resources['dhcp']: raise exceptions.InvalidConfiguration('DHCP requires a subnet') data_utils.rand_name_root = data_utils.rand_name(self.name) if not self.network_resources or self.network_resources['network']: network_name = data_utils.rand_name_root + "-network" network = self._create_network(network_name, tenant_id) try: if not self.network_resources or self.network_resources['subnet']: subnet_name = data_utils.rand_name_root + "-subnet" subnet = self._create_subnet(subnet_name, tenant_id, network['id']) if not self.network_resources or self.network_resources['router']: router_name = data_utils.rand_name_root + "-router" router = self._create_router(router_name, tenant_id) self._add_router_interface(router['id'], subnet['id']) except Exception: if router: self._clear_isolated_router(router['id'], router['name']) if subnet: self._clear_isolated_subnet(subnet['id'], subnet['name']) if network: self._clear_isolated_network(network['id'], network['name']) raise return network, subnet, router def _create_network(self, name, tenant_id): if self.tempest_client: resp, resp_body = self.network_admin_client.create_network( name=name, tenant_id=tenant_id) else: body = {'network': {'tenant_id': tenant_id, 'name': name}} resp_body = self.network_admin_client.create_network(body) return resp_body['network'] def _create_subnet(self, subnet_name, tenant_id, network_id): if not self.tempest_client: body = {'subnet': {'name': subnet_name, 'tenant_id': tenant_id, 'network_id': network_id, 'ip_version': 4}} if self.network_resources: body['enable_dhcp'] = self.network_resources['dhcp'] base_cidr = netaddr.IPNetwork(CONF.network.tenant_network_cidr) mask_bits = CONF.network.tenant_network_mask_bits for subnet_cidr in base_cidr.subnet(mask_bits): try: if self.tempest_client: if self.network_resources: resp, resp_body = self.network_admin_client.\ create_subnet( network_id=network_id, cidr=str(subnet_cidr), name=subnet_name, tenant_id=tenant_id, enable_dhcp=self.network_resources['dhcp'], ip_version=4) else: resp, resp_body = self.network_admin_client.\ create_subnet(network_id=network_id, cidr=str(subnet_cidr), name=subnet_name, tenant_id=tenant_id, ip_version=4) else: body['subnet']['cidr'] = str(subnet_cidr) resp_body = self.network_admin_client.create_subnet(body) break except exceptions.BadRequest as e: if 'overlaps with another subnet' not in str(e): raise else: e = exceptions.BuildErrorException() e.message = 'Available CIDR for subnet creation could not be found' raise e return resp_body['subnet'] def _create_router(self, router_name, tenant_id): external_net_id = dict( network_id=CONF.network.public_network_id) if self.tempest_client: resp, resp_body = self.network_admin_client.create_router( router_name, external_gateway_info=external_net_id, tenant_id=tenant_id) else: body = {'router': {'name': router_name, 'tenant_id': tenant_id, 'external_gateway_info': external_net_id, 'admin_state_up': True}} resp_body = self.network_admin_client.create_router(body) return resp_body['router'] def _add_router_interface(self, router_id, subnet_id): if self.tempest_client: self.network_admin_client.add_router_interface_with_subnet_id( router_id, subnet_id) else: body = {'subnet_id': subnet_id} self.network_admin_client.add_interface_router(router_id, body) def get_primary_network(self): return self.isolated_net_resources.get('primary')[0] def get_primary_subnet(self): return self.isolated_net_resources.get('primary')[1] def get_primary_router(self): return self.isolated_net_resources.get('primary')[2] def get_admin_network(self): return self.isolated_net_resources.get('admin')[0] def get_admin_subnet(self): return self.isolated_net_resources.get('admin')[1] def get_admin_router(self): return self.isolated_net_resources.get('admin')[2] def get_alt_network(self): return self.isolated_net_resources.get('alt')[0] def get_alt_subnet(self): return self.isolated_net_resources.get('alt')[1] def get_alt_router(self): return self.isolated_net_resources.get('alt')[2] def get_credentials(self, credential_type): if self.isolated_creds.get(credential_type): credentials = self.isolated_creds[credential_type] else: is_admin = (credential_type == 'admin') credentials = self._create_creds(admin=is_admin) self.isolated_creds[credential_type] = credentials # Maintained until tests are ported LOG.info("Acquired isolated creds:\n credentials: %s" % credentials) if (CONF.service_available.neutron and not CONF.baremetal.driver_enabled): network, subnet, router = self._create_network_resources( credentials.tenant_id) self.isolated_net_resources[credential_type] = ( network, subnet, router,) LOG.info("Created isolated network resources for : \n" + " credentials: %s" % credentials) return credentials def get_primary_creds(self): return self.get_credentials('primary') def get_admin_creds(self): return self.get_credentials('admin') def get_alt_creds(self): return self.get_credentials('alt') def
(self, router_id, router_name): net_client = self.network_admin_client try: net_client.delete_router(router_id) except exceptions.NotFound: LOG.warn('router with name: %s not found for delete' % router_name) def _clear_isolated_subnet(self, subnet_id, subnet_name): net_client = self.network_admin_client try: net_client.delete_subnet(subnet_id) except exceptions.NotFound: LOG.warn('subnet with name: %s not found for delete' % subnet_name) def _clear_isolated_network(self, network_id, network_name): net_client = self.network_admin_client try: net_client.delete_network(network_id) except exceptions.NotFound: LOG.warn('network with name: %s not found for delete' % network_name) def _clear_isolated_net_resources(self): net_client = self.network_admin_client for cred in self.isolated_net_resources: network, subnet, router = self.isolated_net_resources.get(cred) LOG.debug("Clearing network: %(network)s, " "subnet: %(subnet)s, router: %(router)s", {'network': network, 'subnet': subnet, 'router': router}) if (not self.network_resources or self.network_resources.get('router')): try: if self.tempest_client: net_client.remove_router_interface_with_subnet_id( router['id'], subnet['id']) else: body = {'subnet_id': subnet['id']} net_client.remove_interface_router(router['id'], body) except exceptions.NotFound: LOG.warn('router with name: %s not found for delete' % router['name']) self._clear_isolated_router(router['id'], router['name']) if (not self.network_resources or self.network_resources.get('subnet')): self._clear_isolated_subnet(subnet['id'], subnet['name']) if (not self.network_resources or self.network_resources.get('network')): self._clear_isolated_network(network['id'], network['name']) def clear_isolated_creds(self): if not self.isolated_creds: return self._clear_isolated_net_resources() for creds in self.isolated_creds.itervalues(): try: self._delete_user(creds.user_id) except exceptions.NotFound: LOG.warn("user with name: %s not found for delete" % creds.username) try: self._delete_tenant(creds.tenant_id) except exceptions.NotFound: LOG.warn("tenant with name: %s not found for delete" % creds.tenant_name)
_clear_isolated_router
FactoryEntityCreator.py
from otp.level import EntityCreator from toontown.coghq import FactoryLevelMgr from toontown.coghq import PlatformEntity from toontown.coghq import ConveyorBelt from toontown.coghq import GearEntity from toontown.coghq import PaintMixer from toontown.coghq import GoonClipPlane from toontown.coghq import MintProduct from toontown.coghq import MintProductPallet from toontown.coghq import MintShelf from toontown.coghq import PathMasterEntity from toontown.coghq import RenderingEntity class FactoryEntityCreator(EntityCreator.EntityCreator): def __init__(self, level):
EntityCreator.EntityCreator.__init__(self, level) nothing = EntityCreator.nothing nonlocal = EntityCreator.nonlocal self.privRegisterTypes({'activeCell': nonlocal, 'crusherCell': nonlocal, 'battleBlocker': nonlocal, 'beanBarrel': nonlocal, 'button': nonlocal, 'conveyorBelt': ConveyorBelt.ConveyorBelt, 'crate': nonlocal, 'door': nonlocal, 'directionalCell': nonlocal, 'gagBarrel': nonlocal, 'gear': GearEntity.GearEntity, 'goon': nonlocal, 'gridGoon': nonlocal, 'golfGreenGame': nonlocal, 'goonClipPlane': GoonClipPlane.GoonClipPlane, 'grid': nonlocal, 'healBarrel': nonlocal, 'levelMgr': FactoryLevelMgr.FactoryLevelMgr, 'lift': nonlocal, 'mintProduct': MintProduct.MintProduct, 'mintProductPallet': MintProductPallet.MintProductPallet, 'mintShelf': MintShelf.MintShelf, 'mover': nonlocal, 'paintMixer': PaintMixer.PaintMixer, 'pathMaster': PathMasterEntity.PathMasterEntity, 'rendering': RenderingEntity.RenderingEntity, 'platform': PlatformEntity.PlatformEntity, 'sinkingPlatform': nonlocal, 'stomper': nonlocal, 'stomperPair': nonlocal, 'laserField': nonlocal, 'securityCamera': nonlocal, 'elevatorMarker': nonlocal, 'trigger': nonlocal, 'moleField': nonlocal, 'maze': nonlocal})
e-chat-box.entry.js
import { r as registerInstance, c as createEvent, h, H as Host } from './index-ab05bccf.js'; const eChatBoxCss = "html{--red-50:#FFF5F5;--red-100:#FED7D7;--red-200:#FEB2B2;--red-300:#FC8181;--red-400:#F56565;--red-500:#E53E3E;--red-600:#C53030;--red-700:#9B2C2C;--red-800:#63171B;--red-900:#63171B;--purple-50:#FAF5FF;--purple-100:#E9D8FD;--purple-200:#D6BCFA;--purple-300:#B794F4;--purple-400:#9F7AEA;--purple-500:#805AD5;--purple-600:#6B46C1;--purple-700:#553C9A;--purple-800:#44337A;--purple-900:#322659;--cyan-50:#EDFDFD;--cyan-100:#C4F1F9;--cyan-200:#9DECF9;--cyan-300:#76E4F7;--cyan-400:#0BC5EA;--cyan-500:#00B5D8;--cyan-600:#00A3C4;--cyan-700:#0987A0;--cyan-800:#086F83;--cyan-900:#065666;--blue-50:#EBF8FF;--blue-100:#CEEDFF;--blue-200:#90CDF4;--blue-300:#63B3ED;--blue-400:#4299E1;--blue-500:#3182CE;--blue-600:#2A69AC;--blue-700:#1E4E8C;--blue-800:#153E75;--blue-900:#1A365D;--teal-50:#E6FFFA;--teal-100:#B2F5EA;--teal-200:#81E6D9;--teal-300:#4FD1C5;--teal-400:#38B2AC;--teal-500:#319795;--teal-600:#2C7A7B;--teal-700:#285E61;--teal-800:#234E52;--teal-900:#1D4044;--green-50:#F0FFF4;--green-100:#C6F6D5;--green-200:#9AE6B4;--green-300:#68D391;--green-400:#48BB78;--green-500:#38A169;--green-600:#2F855A;--green-700:#276749;--green-800:#22543D;--green-900:#1C4532;--yellow-50:#FFFFF0;--yellow-100:#FEFCBF;--yellow-200:#FAF089;--yellow-300:#F6E05E;--yellow-400:#ECC94B;--yellow-500:#D69E2E;--yellow-600:#B7791F;--yellow-700:#975A16;--yellow-800:#744210;--yellow-900:#5F370E;--orange-50:#FFFAF0;--orange-100:#FEEBC8;--orange-200:#FBD38D;--orange-300:#F6AD55;--orange-400:#ED8936;--orange-500:#DD6B20;--orange-600:#C05621;--orange-700:#9C4221;--orange-800:#7B341E;--orange-900:#652B19;--gray-50:#F7FAFC;--gray-100:#EDF2F7;--gray-200:#E2E8F0;--gray-300:#CBD5E0;--gray-400:#A0AEC0;--gray-500:#718096;--gray-600:#4A5568;--gray-700:#2D3748;--gray-800:#1A202C;--gray-900:#171923;--primary:#000000;--equinox:linear-gradient(90deg, #E7CCB4 0%, rgba(255, 255, 255, 0) 100%), #F2F2F2;--sunrise:linear-gradient(135deg, #F6AD55 34.9%, #FAF089 100%);--nightfall:linear-gradient(135deg, #B794F4 34.9%, #0BC5EA 100%)}.silicon-light-weak{background:rgba(255, 255, 255, 0.13);-webkit-backdrop-filter:blur(13px);backdrop-filter:blur(13px)}.silicon-light-medium{background:rgba(255, 255, 255, 0.22);-webkit-backdrop-filter:blur(22px);backdrop-filter:blur(22px)}.silicon-light-strong{background:rgba(255, 255, 255, 0.33);-webkit-backdrop-filter:blur(33px);backdrop-filter:blur(33px)}.silicon-dark-weak{background:rgba(0, 0, 0, 0.13);-webkit-backdrop-filter:blur(13px);backdrop-filter:blur(13px)}.silicon-dark-medium{background:rgba(0, 0, 0, 0.22);-webkit-backdrop-filter:blur(22px);backdrop-filter:blur(22px)}.silicon-dark-strong{background:rgba(0, 0, 0, 0.33);-webkit-backdrop-filter:blur(33px);backdrop-filter:blur(33px)}.e-scroll::-webkit-scrollbar{width:10px}.e-scroll::-webkit-scrollbar-track{background:#f1f1f1}.e-scroll::-webkit-scrollbar-thumb{background:#888}.e-scroll::-webkit-scrollbar-thumb:hover{background:#555}.elevation-1{-webkit-box-shadow:0px 2px 1px -1px rgba(160, 174, 192, 0.2), 0px 1px 1px rgba(160, 174, 192, 0.14), 0px 1px 3px rgba(160, 174, 192, 0.12);box-shadow:0px 2px 1px -1px rgba(160, 174, 192, 0.2), 0px 1px 1px rgba(160, 174, 192, 0.14), 0px 1px 3px rgba(160, 174, 192, 0.12)}.elevation-2{-webkit-box-shadow:0px 3px 1px -2px rgba(160, 174, 192, 0.2), 0px 2px 2px rgba(160, 174, 192, 0.14), 0px 1px 5px rgba(160, 174, 192, 0.12);box-shadow:0px 3px 1px -2px rgba(160, 174, 192, 0.2), 0px 2px 2px rgba(160, 174, 192, 0.14), 0px 1px 5px rgba(160, 174, 192, 0.12)}.elevation-3{-webkit-box-shadow:0px 3px 3px -2px rgba(160, 174, 192, 0.2), 0px 3px 4px rgba(160, 174, 192, 0.14), 0px 1px 8px rgba(160, 174, 192, 0.12);box-shadow:0px 3px 3px -2px rgba(160, 174, 192, 0.2), 0px 3px 4px rgba(160, 174, 192, 0.14), 0px 1px 8px rgba(160, 174, 192, 0.12)}.elevation-4{-webkit-box-shadow:0px 2px 4px -1px rgba(160, 174, 192, 0.2), 0px 4px 5px rgba(160, 174, 192, 0.14), 0px 1px 10px rgba(160, 174, 192, 0.12);box-shadow:0px 2px 4px -1px rgba(160, 174, 192, 0.2), 0px 4px 5px rgba(160, 174, 192, 0.14), 0px 1px 10px rgba(160, 174, 192, 0.12)}.elevation-5{-webkit-box-shadow:0px 3px 5px -1px rgba(160, 174, 192, 0.2), 0px 5px 8px rgba(160, 174, 192, 0.14), 0px 1px 14px rgba(160, 174, 192, 0.12);box-shadow:0px 3px 5px -1px rgba(160, 174, 192, 0.2), 0px 5px 8px rgba(160, 174, 192, 0.14), 0px 1px 14px rgba(160, 174, 192, 0.12)}.elevation-6{-webkit-box-shadow:0px 3px 5px -1px rgba(160, 174, 192, 0.2), 0px 6px 10px rgba(160, 174, 192, 0.14), 0px 1px 18px rgba(160, 174, 192, 0.12);box-shadow:0px 3px 5px -1px rgba(160, 174, 192, 0.2), 0px 6px 10px rgba(160, 174, 192, 0.14), 0px 1px 18px rgba(160, 174, 192, 0.12)}.elevation-7{-webkit-box-shadow:0px 4px 5px -2px rgba(160, 174, 192, 0.2), 0px 7px 10px 1px rgba(160, 174, 192, 0.14), 0px 2px 16px 1px rgba(160, 174, 192, 0.12);box-shadow:0px 4px 5px -2px rgba(160, 174, 192, 0.2), 0px 7px 10px 1px rgba(160, 174, 192, 0.14), 0px 2px 16px 1px rgba(160, 174, 192, 0.12)}.elevation-8{-webkit-box-shadow:0px 5px 5px -3px rgba(160, 174, 192, 0.2), 0px 8px 10px 1px rgba(160, 174, 192, 0.14), 0px 3px 14px 2px rgba(160, 174, 192, 0.12);box-shadow:0px 5px 5px -3px rgba(160, 174, 192, 0.2), 0px 8px 10px 1px rgba(160, 174, 192, 0.14), 0px 3px 14px 2px rgba(160, 174, 192, 0.12)}.elevation-9{-webkit-box-shadow:0px 5px 6px -3px rgba(160, 174, 192, 0.2), 0px 9px 12px 1px rgba(160, 174, 192, 0.14), 0px 3px 16px 2px rgba(160, 174, 192, 0.12);box-shadow:0px 5px 6px -3px rgba(160, 174, 192, 0.2), 0px 9px 12px 1px rgba(160, 174, 192, 0.14), 0px 3px 16px 2px rgba(160, 174, 192, 0.12)}.elevation-10{-webkit-box-shadow:0px 6px 6px -3px rgba(160, 174, 192, 0.2), 0px 10px 14px 1px rgba(160, 174, 192, 0.14), 0px 4px 18px 3px rgba(160, 174, 192, 0.12);box-shadow:0px 6px 6px -3px rgba(160, 174, 192, 0.2), 0px 10px 14px 1px rgba(160, 174, 192, 0.14), 0px 4px 18px 3px rgba(160, 174, 192, 0.12)}.elevation-11{-webkit-box-shadow:0px 6px 7px -4px rgba(160, 174, 192, 0.2), 0px 11px 15px 1px rgba(160, 174, 192, 0.14), 0px 4px 20px 3px rgba(160, 174, 192, 0.12);box-shadow:0px 6px 7px -4px rgba(160, 174, 192, 0.2), 0px 11px 15px 1px rgba(160, 174, 192, 0.14), 0px 4px 20px 3px rgba(160, 174, 192, 0.12)}.elevation-12{-webkit-box-shadow:0px 7px 8px -4px rgba(160, 174, 192, 0.2), 0px 12px 17px 2px rgba(160, 174, 192, 0.14), 0px 5px 22px 4px rgba(160, 174, 192, 0.12);box-shadow:0px 7px 8px -4px rgba(160, 174, 192, 0.2), 0px 12px 17px 2px rgba(160, 174, 192, 0.14), 0px 5px 22px 4px rgba(160, 174, 192, 0.12)}.equinox{background:var(--equinox)}.sunrise{background:var(--sunrise)}.nightfall{background:var(--nightfall)}@font-face{font-family:'Roboto';font-style:italic;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOiCnqEu92Fr1Mu51QrEz0dL_nz.woff2) format('woff2');unicode-range:U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:italic;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOiCnqEu92Fr1Mu51QrEzQdL_nz.woff2) format('woff2');unicode-range:U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116}@font-face{font-family:'Roboto';font-style:italic;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOiCnqEu92Fr1Mu51QrEzwdL_nz.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:italic;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOiCnqEu92Fr1Mu51QrEzMdL_nz.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:italic;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOiCnqEu92Fr1Mu51QrEz8dL_nz.woff2) format('woff2');unicode-range:U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB}@font-face{font-family:'Roboto';font-style:italic;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOiCnqEu92Fr1Mu51QrEz4dL_nz.woff2) format('woff2');unicode-range:U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF}@font-face{font-family:'Roboto';font-style:italic;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOiCnqEu92Fr1Mu51QrEzAdLw.woff2) format('woff2');unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD}@font-face{font-family:'Roboto';font-style:italic;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TjASc3CsTKlA.woff2) format('woff2');unicode-range:U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:italic;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TjASc-CsTKlA.woff2) format('woff2');unicode-range:U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116}@font-face{font-family:'Roboto';font-style:italic;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TjASc2CsTKlA.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:italic;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TjASc5CsTKlA.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:italic;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TjASc1CsTKlA.woff2) format('woff2');unicode-range:U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB}@font-face{font-family:'Roboto';font-style:italic;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TjASc0CsTKlA.woff2) format('woff2');unicode-range:U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF}@font-face{font-family:'Roboto';font-style:italic;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TjASc6CsQ.woff2) format('woff2');unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD}@font-face{font-family:'Roboto';font-style:italic;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1Mu51xFIzIFKw.woff2) format('woff2');unicode-range:U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:italic;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1Mu51xMIzIFKw.woff2) format('woff2');unicode-range:U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116}@font-face{font-family:'Roboto';font-style:italic;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1Mu51xEIzIFKw.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:italic;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1Mu51xLIzIFKw.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:italic;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1Mu51xHIzIFKw.woff2) format('woff2');unicode-range:U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB}@font-face{font-family:'Roboto';font-style:italic;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1Mu51xGIzIFKw.woff2) format('woff2');unicode-range:U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF}@font-face{font-family:'Roboto';font-style:italic;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1Mu51xIIzI.woff2) format('woff2');unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD}@font-face{font-family:'Roboto';font-style:italic;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51S7ACc3CsTKlA.woff2) format('woff2');unicode-range:U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:italic;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51S7ACc-CsTKlA.woff2) format('woff2');unicode-range:U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116}@font-face{font-family:'Roboto';font-style:italic;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51S7ACc2CsTKlA.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:italic;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51S7ACc5CsTKlA.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:italic;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51S7ACc1CsTKlA.woff2) format('woff2');unicode-range:U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB}@font-face{font-family:'Roboto';font-style:italic;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51S7ACc0CsTKlA.woff2) format('woff2');unicode-range:U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF}@font-face{font-family:'Roboto';font-style:italic;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51S7ACc6CsQ.woff2) format('woff2');unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD}@font-face{font-family:'Roboto';font-style:italic;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TzBic3CsTKlA.woff2) format('woff2');unicode-range:U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:italic;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TzBic-CsTKlA.woff2) format('woff2');unicode-range:U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116}@font-face{font-family:'Roboto';font-style:italic;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TzBic2CsTKlA.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:italic;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TzBic5CsTKlA.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:italic;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TzBic1CsTKlA.woff2) format('woff2');unicode-range:U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB}@font-face{font-family:'Roboto';font-style:italic;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TzBic0CsTKlA.woff2) format('woff2');unicode-range:U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF}@font-face{font-family:'Roboto';font-style:italic;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TzBic6CsQ.woff2) format('woff2');unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD}@font-face{font-family:'Roboto';font-style:italic;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TLBCc3CsTKlA.woff2) format('woff2');unicode-range:U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:italic;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TLBCc-CsTKlA.woff2) format('woff2');unicode-range:U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116}@font-face{font-family:'Roboto';font-style:italic;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TLBCc2CsTKlA.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:italic;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TLBCc5CsTKlA.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:italic;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TLBCc1CsTKlA.woff2) format('woff2');unicode-range:U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB}@font-face{font-family:'Roboto';font-style:italic;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TLBCc0CsTKlA.woff2) format('woff2');unicode-range:U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF}@font-face{font-family:'Roboto';font-style:italic;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOjCnqEu92Fr1Mu51TLBCc6CsQ.woff2) format('woff2');unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD}@font-face{font-family:'Roboto';font-style:normal;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1MmgVxFIzIFKw.woff2) format('woff2');unicode-range:U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:normal;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1MmgVxMIzIFKw.woff2) format('woff2');unicode-range:U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116}@font-face{font-family:'Roboto';font-style:normal;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1MmgVxEIzIFKw.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:normal;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1MmgVxLIzIFKw.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1MmgVxHIzIFKw.woff2) format('woff2');unicode-range:U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB}@font-face{font-family:'Roboto';font-style:normal;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1MmgVxGIzIFKw.woff2) format('woff2');unicode-range:U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:100;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOkCnqEu92Fr1MmgVxIIzI.woff2) format('woff2');unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD}@font-face{font-family:'Roboto';font-style:normal;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmSU5fCRc4EsA.woff2) format('woff2');unicode-range:U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:normal;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmSU5fABc4EsA.woff2) format('woff2');unicode-range:U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116}@font-face{font-family:'Roboto';font-style:normal;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmSU5fCBc4EsA.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:normal;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmSU5fBxc4EsA.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmSU5fCxc4EsA.woff2) format('woff2');unicode-range:U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB}@font-face{font-family:'Roboto';font-style:normal;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmSU5fChc4EsA.woff2) format('woff2');unicode-range:U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:300;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmSU5fBBc4.woff2) format('woff2');unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOmCnqEu92Fr1Mu72xKOzY.woff2) format('woff2');unicode-range:U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOmCnqEu92Fr1Mu5mxKOzY.woff2) format('woff2');unicode-range:U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOmCnqEu92Fr1Mu7mxKOzY.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOmCnqEu92Fr1Mu4WxKOzY.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOmCnqEu92Fr1Mu7WxKOzY.woff2) format('woff2');unicode-range:U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOmCnqEu92Fr1Mu7GxKOzY.woff2) format('woff2');unicode-range:U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:400;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOmCnqEu92Fr1Mu4mxK.woff2) format('woff2');unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD}@font-face{font-family:'Roboto';font-style:normal;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmEU9fCRc4EsA.woff2) format('woff2');unicode-range:U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:normal;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmEU9fABc4EsA.woff2) format('woff2');unicode-range:U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116}@font-face{font-family:'Roboto';font-style:normal;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmEU9fCBc4EsA.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:normal;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmEU9fBxc4EsA.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmEU9fCxc4EsA.woff2) format('woff2');unicode-range:U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB}@font-face{font-family:'Roboto';font-style:normal;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmEU9fChc4EsA.woff2) format('woff2');unicode-range:U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:500;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmEU9fBBc4.woff2) format('woff2');unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmWUlfCRc4EsA.woff2) format('woff2');unicode-range:U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmWUlfABc4EsA.woff2) format('woff2');unicode-range:U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmWUlfCBc4EsA.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmWUlfBxc4EsA.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmWUlfCxc4EsA.woff2) format('woff2');unicode-range:U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmWUlfChc4EsA.woff2) format('woff2');unicode-range:U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:700;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmWUlfBBc4.woff2) format('woff2');unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmYUtfCRc4EsA.woff2) format('woff2');unicode-range:U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmYUtfABc4EsA.woff2) format('woff2');unicode-range:U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmYUtfCBc4EsA.woff2) format('woff2');unicode-range:U+1F00-1FFF}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmYUtfBxc4EsA.woff2) format('woff2');unicode-range:U+0370-03FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmYUtfCxc4EsA.woff2) format('woff2');unicode-range:U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmYUtfChc4EsA.woff2) format('woff2');unicode-range:U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF}@font-face{font-family:'Roboto';font-style:normal;font-weight:900;src:url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmYUtfBBc4.woff2) format('woff2');unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD}.weight-normal{font-weight:normal}.weight-bold{font-weight:bold}.decoration-underline{text-decoration:underline}.text-capitalize{text-transform:capitalize}.text-uppercase{text-transform:uppercase}.text-xs{font-size:12px;line-height:150%}.text-sm{font-size:14px;line-height:150%}.text-md{font-size:16px;line-height:150%}.text-lg{font-size:18px;line-height:150%}.text-xl{font-size:20px;line-height:150%}.text-2xl{font-size:24px;line-height:150%}.text-3xl{font-size:28px;line-height:140%}.text-4xl{font-size:36px;line-height:42px}.text-5xl{font-size:48px;line-height:140%}.text-6xl{font-size:64px;line-height:130%}*{font-family:Roboto, serif}:host{display:block}.e-chat-box{border:1px solid var(--gray-200);-webkit-box-sizing:border-box;box-sizing:border-box;border-radius:100px;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;gap:12px;padding:28px 24px}.e-chat-box input{background:transparent;width:100%;border:none;font-size:18px;line-height:150%;color:var(--gray-500);padding-top:2px}.e-chat-box input::-webkit-input-placeholder{color:var(--gray-500)}.e-chat-box input::-moz-placeholder{color:var(--gray-500)}.e-chat-box input:-ms-input-placeholder{color:var(--gray-500)}.e-chat-box input::-ms-input-placeholder{color:var(--gray-500)}.e-chat-box input::placeholder{color:var(--gray-500)}.e-chat-box input:focus-visible{outline:none}.e-chat-box.dark input{color:#fff !important}.e-chat-box.dark input::-webkit-input-placeholder{color:#fff !important}.e-chat-box.dark input::-moz-placeholder{color:#fff !important}.e-chat-box.dark input:-ms-input-placeholder{color:#fff !important}.e-chat-box.dark input::-ms-input-placeholder{color:#fff !important}.e-chat-box.dark input::placeholder{color:#fff !important}"; const EChatBox = class { constructor(hostRef) { registerInstance(this, hostRef); this.outerPrependClick = createEvent(this, "outerPrependClick", 7); this.prependClick = createEvent(this, "prependClick", 7); this.appendClick = createEvent(this, "appendClick", 7); this.outerAppendClick = createEvent(this, "outerAppendClick", 7); this.valueChange = createEvent(this, "valueChange", 7); this.type = 'text'; this.placeholder = "Message to..."; this.outerPrependIcon = "ph-plus"; this.prependIcon = "ph-smiley-sticker"; this.appendIcon = "ph-dots-three"; this.outerAppendIcon = "ph-paper-plane"; this.backdrop = true; this.dark = true; this.backdropBlur = "weak"; this.classes = () => { const classes = {
const setting = { style: this.dark ? 'dark' : 'light', blur: this.backdropBlur }; if (this.backdrop) { classes[`silicon-${setting.style}-${setting.blur}`] = true; } return Object.assign(Object.assign({}, classes), { [setting.style]: true }); }; } onOuterPrependClick() { this.outerPrependClick.emit('outer-prepend-click'); } onPrependClick() { this.prependClick.emit('prepend-click'); } onAppendClick() { this.appendClick.emit('append-click'); } onOuterAppendClick() { this.outerAppendClick.emit('outer-append-click'); } handleChange(event) { const val = event.target.value; console.log(val); this.value = val; this.valueChange.emit(val); } render() { return (h(Host, null, h("div", { class: this.classes() }, h("slot", { name: "outer-prepend" }, h("e-btn", { onClick: this.onOuterPrependClick.bind(this), icon: this.outerPrependIcon, size: "sm" })), h("slot", { name: "prepend" }, h("e-btn", { onClick: this.onPrependClick.bind(this), icon: this.prependIcon, size: "sm" })), h("input", { type: this.type, value: this.value, onInput: event => this.handleChange(event), placeholder: this.placeholder }), h("slot", { name: "append" }, h("e-btn", { onClick: this.onAppendClick.bind(this), icon: this.appendIcon, size: "sm" })), h("slot", { name: "outer-append" }, h("e-btn", { onClick: this.onOuterAppendClick.bind(this), icon: this.outerAppendIcon, size: "sm" }))))); } }; EChatBox.style = eChatBoxCss; export { EChatBox as e_chat_box };
'e-chat-box': true, };
hash_set.go
package set type HashSet struct { hashTable map[interface{}][]Hashable count int } var _ Set = &HashSet{} // New constructs and returns a new Queue. Code duplication needed for benchmarks. func NewHashSet() *HashSet
// Length returns the number of elements currently stored in the queue. func (s *HashSet) Size() int { return s.count } func (s *HashSet) Add(elem interface{}) bool { hashable, ok := elem.(Hashable) if !ok { panic("Adding not hashable element to hash set") } hash := hashable.GetHash() hashEntry, ok := s.hashTable[hash] if ok { for i := 0; i < len(hashEntry); i++ { if hashEntry[i].Equals(hashable) { return false } } s.hashTable[hash] = append(hashEntry, hashable) } else { s.hashTable[hash] = []Hashable{hashable} } s.count++ return true } func (s *HashSet) Clear() { s.hashTable = make(map[interface{}][]Hashable) s.count = 0 } func (s *HashSet) Contains(elem interface{}) bool { hashable, ok := elem.(Hashable) if !ok { return false } hash := hashable.GetHash() hashEntry, ok := s.hashTable[hash] if !ok { return false } for i := 0; i < len(hashEntry); i++ { if hashEntry[i].Equals(hashable) { return true } } return false } func (s *HashSet) Remove(elem interface{}) bool { hashable, ok := elem.(Hashable) if !ok { return false } hash := hashable.GetHash() hashEntry, ok := s.hashTable[hash] if !ok { return false } length := len(hashEntry) for i := 0; i < length; i++ { if hashEntry[i].Equals(hashable) { if length == 1 { delete(s.hashTable, hash) } else { var newHashEntry []Hashable if i == length-1 { newHashEntry = hashEntry[0 : length-1] } else { newHashEntry = hashEntry[0:i] newHashEntry = append(newHashEntry, hashEntry[i+1:length]...) } s.hashTable[hash] = newHashEntry } s.count-- return true } } return false }
{ return &HashSet{ hashTable: make(map[interface{}][]Hashable), count: 0, } }
gitresource_test.go
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the * License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package privategit import ( "errors" "fmt" "os" "path/filepath" "testing" "github.com/aws/amazon-ssm-agent/agent/context" "github.com/aws/amazon-ssm-agent/agent/fileutil" filemock "github.com/aws/amazon-ssm-agent/agent/fileutil/filemanager/mock" "github.com/aws/amazon-ssm-agent/agent/plugins/downloadcontent/gitresource" "github.com/aws/amazon-ssm-agent/agent/plugins/downloadcontent/gitresource/privategit/handler" "github.com/aws/amazon-ssm-agent/agent/plugins/downloadcontent/gitresource/privategit/handler/core" handlermock "github.com/aws/amazon-ssm-agent/agent/plugins/downloadcontent/gitresource/privategit/handler/mock" bridgemock "github.com/aws/amazon-ssm-agent/agent/ssm/ssmparameterresolver/mock" gogit "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing/transport/http" "github.com/stretchr/testify/assert" ) var contextMock = context.NewMockDefault() var logMock = contextMock.Log() var bm = bridgemock.GetSsmParamResolverBridge(map[string]string{}) var downloadRemoteResourceDestPath = os.TempDir() var downloadRemoteResourceTempCloneDir = filepath.Join(downloadRemoteResourceDestPath, "tempCloneDir") var downloadRemoteResourceTestFile = filepath.Join(downloadRemoteResourceDestPath, "testFile") func CollectFilesAndRebaseTest(sourceDir, rebaseToDir string) (files []string, err error) { return []string{downloadRemoteResourceTestFile}, nil } func MoveFilesTest(sourceDir, destDir string) error { return nil } func getString(obj interface{}) string { return fmt.Sprintf("%v", obj) } func TestNewGitResource(t *testing.T) { testGitHandler, err := handler.NewGitHandler("private-git-repo", handler.GitAuthConfig{ PrivateSSHKey: "private-ssh-key", SkipHostKeyChecking: true, Username: "admin", Password: "pwd", }, gitresource.CheckoutOptions{ Branch: "master", CommitID: "", }, bm) assert.NoError(t, err) tests := []struct { sourceInfo string gitResource *GitResource err error }{ { `{ "repository": "private-git-repo, }`, nil, errors.New("SourceInfo could not be unmarshalled for source type Git: " + "invalid character '\\n' in string literal"), }, { `{ "repository": "private-git-repo", "getOptions": "test" }`, nil, errors.New("SourceInfo could not be unmarshalled for source type Git: " + "getOptions is not specified in the right format"), }, { `{ "repository": "private-git-repo", "getOptions": "test" }`, nil, errors.New("SourceInfo could not be unmarshalled for source type Git: " + "getOptions is not specified in the right format"), }, { `{ "repository": "http:// test" }`, nil, errors.New("Invalid repository url format: parse \"http:// test\": invalid character \" \" in host name"), }, { `{ "repository": "private-git-repo", "privateSSHKey": "private-ssh-key", "skipHostKeyChecking": true, "username": "admin", "password": "pwd", "getOptions": "branch:master" }`, &GitResource{ context: contextMock, Handler: testGitHandler, }, nil, }, } for _, test := range tests { gitResource, err := NewGitResource(contextMock, test.sourceInfo, bm) if test.err != nil { assert.Nil(t, gitResource) assert.Error(t, err, getString(test)) assert.EqualError(t, err, test.err.Error()) } else { assert.NoError(t, err, getString(test)) assert.Equal(t, test.gitResource, gitResource, getString(test)) } } } func
(t *testing.T) { tests := []struct { sourceInfo string gitInfo GitInfo err error }{ { `{ "repository": "private-git-repo", "privateSSHKey": "--key--", "skipHostKeyChecking": true, "username": "admin", "password": "pwd", "getOptions": "branch:master" }`, GitInfo{ Repository: "private-git-repo", PrivateSSHKey: "--key--", SkipHostKeyChecking: true, Username: "admin", Password: "pwd", GetOptions: "branch:master", }, nil, }, { `{ "repository": "git://" }`, GitInfo{ Repository: "git://", SkipHostKeyChecking: false, }, nil, }, { fmt.Sprintf(`{ "repository": "git://", "privateSSHKey": "%s" }`, "private-ssh-key"), GitInfo{ Repository: "git://", PrivateSSHKey: "private-ssh-key", SkipHostKeyChecking: false, }, nil, }, { `{ "repository": "git:// }`, GitInfo{}, errors.New("invalid character '\\n' in string literal"), }, } for _, test := range tests { gitInfo, err := parseSourceInfo(test.sourceInfo) if test.err != nil { assert.Equal(t, GitInfo{}, gitInfo) assert.Error(t, err, getString(test)) assert.EqualError(t, err, test.err.Error()) } else { assert.NoError(t, err, getString(test)) assert.Equal(t, test.gitInfo, gitInfo, getString(test)) } } } func TestGitResource_ValidateLocationInfo(t *testing.T) { gitHandlerMock := handlermock.GitHandlerMock{} gitHandlerMock.On("Validate").Return(true, nil).Once() resource := GitResource{ context: contextMock, Handler: &gitHandlerMock, } _, _ = resource.ValidateLocationInfo() gitHandlerMock.AssertExpectations(t) } func TestGitResource_DownloadRemoteResource(t *testing.T) { authMethod := &http.BasicAuth{} repository := &gogit.Repository{} fileSysMock := filemock.FileSystemMock{} fileSysMock.On("MakeDirs", os.TempDir()).Return(nil).Once() fileSysMock.On("CreateTempDir", os.TempDir(), "tempCloneDir").Return(downloadRemoteResourceTempCloneDir, nil).Once() fileSysMock.On("DeleteDirectory", downloadRemoteResourceTempCloneDir).Return(nil).Once() collectFilesAndRebaseFunction = CollectFilesAndRebaseTest moveFilesFunction = MoveFilesTest gitHandlerMock := handlermock.GitHandlerMock{} gitHandlerMock.On("GetAuthMethod", logMock).Return(authMethod, nil).Once() gitHandlerMock.On("CloneRepository", logMock, authMethod, downloadRemoteResourceTempCloneDir).Return(repository, nil).Once() gitHandlerMock.On("PerformCheckout", core.NewGitRepository(repository)).Return(nil).Once() resource := GitResource{ context: contextMock, Handler: &gitHandlerMock, } err, result := resource.DownloadRemoteResource(fileSysMock, downloadRemoteResourceDestPath) assert.NoError(t, err) assert.Equal(t, []string{downloadRemoteResourceTestFile}, result.Files) gitHandlerMock.AssertExpectations(t) fileSysMock.AssertExpectations(t) collectFilesAndRebaseFunction = fileutil.CollectFilesAndRebase moveFilesFunction = fileutil.MoveFiles }
TestNewGitResource_parseSourceInfo
app_test.go
package slashing import ( "testing" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto/secp256k1" sdk "github.com/BITCOIVA/Bitcoiva-sdk/types" "github.com/BITCOIVA/Bitcoiva-sdk/x/auth" "github.com/BITCOIVA/Bitcoiva-sdk/x/bank" "github.com/BITCOIVA/Bitcoiva-sdk/x/mock" "github.com/BITCOIVA/Bitcoiva-sdk/x/staking" "github.com/BITCOIVA/Bitcoiva-sdk/x/staking/types" "github.com/BITCOIVA/Bitcoiva-sdk/x/supply" supplyexported "github.com/BITCOIVA/Bitcoiva-sdk/x/supply/exported" ) var ( priv1 = secp256k1.GenPrivKey() addr1 = sdk.AccAddress(priv1.PubKey().Address()) coins = sdk.Coins{sdk.NewInt64Coin("foocoin", 10)} ) // initialize the mock application for this module func getMockApp(t *testing.T) (*mock.App, staking.Keeper, Keeper) { mapp := mock.NewApp() RegisterCodec(mapp.Cdc) staking.RegisterCodec(mapp.Cdc) supply.RegisterCodec(mapp.Cdc) keyStaking := sdk.NewKVStoreKey(staking.StoreKey) tkeyStaking := sdk.NewTransientStoreKey(staking.TStoreKey) keySlashing := sdk.NewKVStoreKey(StoreKey) keySupply := sdk.NewKVStoreKey(supply.StoreKey) feeCollector := supply.NewEmptyModuleAccount(auth.FeeCollectorName) notBondedPool := supply.NewEmptyModuleAccount(types.NotBondedPoolName, supply.Burner, supply.Staking) bondPool := supply.NewEmptyModuleAccount(types.BondedPoolName, supply.Burner, supply.Staking) blacklistedAddrs := make(map[string]bool) blacklistedAddrs[feeCollector.String()] = true blacklistedAddrs[notBondedPool.String()] = true blacklistedAddrs[bondPool.String()] = true bankKeeper := bank.NewBaseKeeper(mapp.AccountKeeper, mapp.ParamsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace, blacklistedAddrs) maccPerms := map[string][]string{ auth.FeeCollectorName: nil, staking.NotBondedPoolName: []string{supply.Burner, supply.Staking}, staking.BondedPoolName: []string{supply.Burner, supply.Staking}, } supplyKeeper := supply.NewKeeper(mapp.Cdc, keySupply, mapp.AccountKeeper, bankKeeper, maccPerms) stakingKeeper := staking.NewKeeper(mapp.Cdc, keyStaking, tkeyStaking, supplyKeeper, mapp.ParamsKeeper.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) keeper := NewKeeper(mapp.Cdc, keySlashing, stakingKeeper, mapp.ParamsKeeper.Subspace(DefaultParamspace), DefaultCodespace) mapp.Router().AddRoute(staking.RouterKey, staking.NewHandler(stakingKeeper)) mapp.Router().AddRoute(RouterKey, NewHandler(keeper)) mapp.SetEndBlocker(getEndBlocker(stakingKeeper)) mapp.SetInitChainer(getInitChainer(mapp, stakingKeeper, mapp.AccountKeeper, supplyKeeper, []supplyexported.ModuleAccountI{feeCollector, notBondedPool, bondPool})) require.NoError(t, mapp.CompleteSetup(keyStaking, tkeyStaking, keySupply, keySlashing)) return mapp, stakingKeeper, keeper } // staking endblocker func getEndBlocker(keeper staking.Keeper) sdk.EndBlocker { return func(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { validatorUpdates := staking.EndBlocker(ctx, keeper) return abci.ResponseEndBlock{ ValidatorUpdates: validatorUpdates, } } } // overwrite the mock init chainer func getInitChainer(mapp *mock.App, keeper staking.Keeper, accountKeeper types.AccountKeeper, supplyKeeper types.SupplyKeeper, blacklistedAddrs []supplyexported.ModuleAccountI) sdk.InitChainer { return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { // set module accounts for _, macc := range blacklistedAddrs { supplyKeeper.SetModuleAccount(ctx, macc) } mapp.InitChainer(ctx, req) stakingGenesis := staking.DefaultGenesisState() validators := staking.InitGenesis(ctx, keeper, accountKeeper, supplyKeeper, stakingGenesis) return abci.ResponseInitChain{ Validators: validators, } } } func checkValidator(t *testing.T, mapp *mock.App, keeper staking.Keeper, addr sdk.AccAddress, expFound bool) staking.Validator { ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) validator, found := keeper.GetValidator(ctxCheck, sdk.ValAddress(addr1)) require.Equal(t, expFound, found) return validator } func checkValidatorSigningInfo(t *testing.T, mapp *mock.App, keeper Keeper, addr sdk.ConsAddress, expFound bool) ValidatorSigningInfo { ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) signingInfo, found := keeper.getValidatorSigningInfo(ctxCheck, addr) require.Equal(t, expFound, found) return signingInfo } func
(t *testing.T) { mapp, stakingKeeper, keeper := getMockApp(t) genTokens := sdk.TokensFromConsensusPower(42) bondTokens := sdk.TokensFromConsensusPower(10) genCoin := sdk.NewCoin(sdk.DefaultBondDenom, genTokens) bondCoin := sdk.NewCoin(sdk.DefaultBondDenom, bondTokens) acc1 := &auth.BaseAccount{ Address: addr1, Coins: sdk.Coins{genCoin}, } accs := []auth.Account{acc1} mock.SetGenesis(mapp, accs) description := staking.NewDescription("foo_moniker", "", "", "") commission := staking.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) createValidatorMsg := staking.NewMsgCreateValidator( sdk.ValAddress(addr1), priv1.PubKey(), bondCoin, description, commission, sdk.OneInt(), ) header := abci.Header{Height: mapp.LastBlockHeight() + 1} mock.SignCheckDeliver(t, mapp.Cdc, mapp.BaseApp, header, []sdk.Msg{createValidatorMsg}, []uint64{0}, []uint64{0}, true, true, priv1) mock.CheckBalance(t, mapp, addr1, sdk.Coins{genCoin.Sub(bondCoin)}) header = abci.Header{Height: mapp.LastBlockHeight() + 1} mapp.BeginBlock(abci.RequestBeginBlock{Header: header}) validator := checkValidator(t, mapp, stakingKeeper, addr1, true) require.Equal(t, sdk.ValAddress(addr1), validator.OperatorAddress) require.Equal(t, sdk.Bonded, validator.Status) require.True(sdk.IntEq(t, bondTokens, validator.BondedTokens())) unjailMsg := MsgUnjail{ValidatorAddr: sdk.ValAddress(validator.ConsPubKey.Address())} // no signing info yet checkValidatorSigningInfo(t, mapp, keeper, sdk.ConsAddress(addr1), false) // unjail should fail with unknown validator header = abci.Header{Height: mapp.LastBlockHeight() + 1} res := mock.SignCheckDeliver(t, mapp.Cdc, mapp.BaseApp, header, []sdk.Msg{unjailMsg}, []uint64{0}, []uint64{1}, false, false, priv1) require.EqualValues(t, CodeValidatorNotJailed, res.Code) require.EqualValues(t, DefaultCodespace, res.Codespace) }
TestSlashingMsgs
excel.go
package excel import ( "github.com/pkg/errors" "github.com/xuri/excelize/v2" "io" "sync" ) // Excel excel type Excel struct { kernel *excelize.File sizeCache *sync.Map // cache sheet size for later use. } // Size record for excel sheet size type Size struct { Row int Column int } // New create a new excel func New() *Excel { return &Excel{kernel: excelize.NewFile(), sizeCache: new(sync.Map)} } func
(filename string, opt ...Option) (*Excel, error) { file, err := excelize.OpenFile(filename, opt...) if err != nil { return nil, err } return &Excel{kernel: file, sizeCache: new(sync.Map)}, nil } func OpenReader(r io.Reader, opt ...Option) (*Excel, error) { file, err := excelize.OpenReader(r, opt...) if err != nil { return nil, err } return &Excel{kernel: file, sizeCache: new(sync.Map)}, nil } // Rows return rows by sheet index func (e *Excel) Rows(index int) (*excelize.Rows, error) { sheet := e.kernel.GetSheetName(index) return e.kernel.Rows(sheet) } // Size returns the row count and max column count of a sheet func (e *Excel) Size(index int) (row int, column int, err error) { sheet := e.kernel.GetSheetName(index) if val, ok := e.sizeCache.Load(sheet); ok { size := val.(Size) return size.Row, size.Column, nil } row, column, err = e.getSheetSize(sheet) if err != nil { return 0, 0, err } e.sizeCache.Store(sheet, Size{Row: row, Column: column}) return } func (e *Excel) getSheetSize(sheet string) (row int, column int, err error) { rows, err := e.kernel.Rows(sheet) if err != nil { return 0, 0, err } for rows.Next() { cols, err := rows.Columns() if err != nil { return 0, 0, err } if column < len(cols) { column = len(cols) cols = cols[:0] // truncate cols } row++ } return } // GetRows get all rows with row and column limit. // Default Row limit is 8192. when exceed will set hasMore=true. // Default Column limit is 1000. when exceed will cause ErrTooManyColumn func (e *Excel) GetRows(index int, options ...ReadOption) ([][]string, bool, error) { config := newReadConfig(options...) rows, err := e.Rows(index) if err != nil { return nil, false, err } results := make([][]string, 0, 64) count := 0 hasMore := false for rows.Next() { count++ if count > config.MaxRow { hasMore = true break } row, err := rows.Columns() if err != nil { return nil, hasMore, err } if len(row) > config.MaxColumn { return nil, hasMore, errors.New("too many column in row") } results = append(results, row) } return results, hasMore, nil }
OpenFile
cyclic_poly.go
// Copyright 2014-2021 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package hash // CyclicPoly provides a cyclic polynomial rolling hash. type CyclicPoly struct { h uint64 p []uint64 i int } // ror rotates the unsigned 64-bit integer to right. The argument s must be // less than 64. func ror(x uint64, s uint) uint64 { return (x >> s) | (x << (64 - s)) } // NewCyclicPoly creates a new instance of the CyclicPoly structure. The // argument n gives the number of bytes for which a hash will be executed. // This number must be positive; the method panics if this isn't the case. func
(n int) *CyclicPoly { if n < 1 { panic("argument n must be positive") } return &CyclicPoly{p: make([]uint64, 0, n)} } // Len returns the length of the byte sequence for which a hash is generated. func (r *CyclicPoly) Len() int { return cap(r.p) } // RollByte hashes the next byte and returns a hash value. The complete becomes // available after at least Len() bytes have been hashed. func (r *CyclicPoly) RollByte(x byte) uint64 { y := hash[x] if len(r.p) < cap(r.p) { r.h = ror(r.h, 1) ^ y r.p = append(r.p, y) } else { r.h ^= ror(r.p[r.i], uint(cap(r.p)-1)) r.h = ror(r.h, 1) ^ y r.p[r.i] = y r.i = (r.i + 1) % cap(r.p) } return r.h } // Stores the hash for the individual bytes. var hash = [256]uint64{ 0x2e4fc3f904065142, 0xc790984cfbc99527, 0x879f95eb8c62f187, 0x3b61be86b5021ef2, 0x65a896a04196f0a5, 0xc5b307b80470b59e, 0xd3bff376a70df14b, 0xc332f04f0b3f1701, 0x753b5f0e9abf3e0d, 0xb41538fdfe66ef53, 0x1906a10c2c1c0208, 0xfb0c712a03421c0d, 0x38be311a65c9552b, 0xfee7ee4ca6445c7e, 0x71aadeded184f21e, 0xd73426fccda23b2d, 0x29773fb5fb9600b5, 0xce410261cd32981a, 0xfe2848b3c62dbc2d, 0x459eaaff6e43e11c, 0xc13e35fc9c73a887, 0xf30ed5c201e76dbc, 0xa5f10b3910482cea, 0x2945d59be02dfaad, 0x06ee334ff70571b5, 0xbabf9d8070f44380, 0xee3e2e9912ffd27c, 0x2a7118d1ea6b8ea7, 0x26183cb9f7b1664c, 0xea71dac7da068f21, 0xea92eca5bd1d0bb7, 0x415595862defcd75, 0x248a386023c60648, 0x9cf021ab284b3c8a, 0xfc9372df02870f6c, 0x2b92d693eeb3b3fc, 0x73e799d139dc6975, 0x7b15ae312486363c, 0xb70e5454a2239c80, 0x208e3fb31d3b2263, 0x01f563cabb930f44, 0x2ac4533d2a3240d8, 0x84231ed1064f6f7c, 0xa9f020977c2a6d19, 0x213c227271c20122, 0x09fe8a9a0a03d07a, 0x4236dc75bcaf910c, 0x460a8b2bead8f17e, 0xd9b27be1aa07055f, 0xd202d5dc4b11c33e, 0x70adb010543bea12, 0xcdae938f7ea6f579, 0x3f3d870208672f4d, 0x8e6ccbce9d349536, 0xe4c0871a389095ae, 0xf5f2a49152bca080, 0x9a43f9b97269934e, 0xc17b3753cb6f475c, 0xd56d941e8e206bd4, 0xac0a4f3e525eda00, 0xa06d5a011912a550, 0x5537ed19537ad1df, 0xa32fe713d611449d, 0x2a1d05b47c3b579f, 0x991d02dbd30a2a52, 0x39e91e7e28f93eb0, 0x40d06adb3e92c9ac, 0x9b9d3afde1c77c97, 0x9a3f3f41c02c616f, 0x22ecd4ba00f60c44, 0x0b63d5d801708420, 0x8f227ca8f37ffaec, 0x0256278670887c24, 0x107e14877dbf540b, 0x32c19f2786ac1c05, 0x1df5b12bb4bc9c61, 0xc0cac129d0d4c4e2, 0x9fdb52ee9800b001, 0x31f601d5d31c48c4, 0x72ff3c0928bcaec7, 0xd99264421147eb03, 0x535a2d6d38aefcfe, 0x6ba8b4454a916237, 0xfa39366eaae4719c, 0x10f00fd7bbb24b6f, 0x5bd23185c76c84d4, 0xb22c3d7e1b00d33f, 0x3efc20aa6bc830a8, 0xd61c2503fe639144, 0x30ce625441eb92d3, 0xe5d34cf359e93100, 0xa8e5aa13f2b9f7a5, 0x5c2b8d851ca254a6, 0x68fb6c5e8b0d5fdf, 0xc7ea4872c96b83ae, 0x6dd5d376f4392382, 0x1be88681aaa9792f, 0xfef465ee1b6c10d9, 0x1f98b65ed43fcb2e, 0x4d1ca11eb6e9a9c9, 0x7808e902b3857d0b, 0x171c9c4ea4607972, 0x58d66274850146df, 0x42b311c10d3981d1, 0x647fa8c621c41a4c, 0xf472771c66ddfedc, 0x338d27e3f847b46b, 0x6402ce3da97545ce, 0x5162db616fc38638, 0x9c83be97bc22a50e, 0x2d3d7478a78d5e72, 0xe621a9b938fd5397, 0x9454614eb0f81c45, 0x395fb6e742ed39b6, 0x77dd9179d06037bf, 0xc478d0fee4d2656d, 0x35d9d6cb772007af, 0x83a56e92c883f0f6, 0x27937453250c00a1, 0x27bd6ebc3a46a97d, 0x9f543bf784342d51, 0xd158f38c48b0ed52, 0x8dd8537c045f66b4, 0x846a57230226f6d5, 0x6b13939e0c4e7cdf, 0xfca25425d8176758, 0x92e5fc6cd52788e6, 0x9992e13d7a739170, 0x518246f7a199e8ea, 0xf104c2a71b9979c7, 0x86b3ffaabea4768f, 0x6388061cf3e351ad, 0x09d9b5295de5bbb5, 0x38bf1638c2599e92, 0x1d759846499e148d, 0x4c0ff015e5f96ef4, 0xa41a94cfa270f565, 0x42d76f9cb2326c0b, 0x0cf385dd3c9c23ba, 0x0508a6c7508d6e7a, 0x337523aabbe6cf8d, 0x646bb14001d42b12, 0xc178729d138adc74, 0xf900ef4491f24086, 0xee1a90d334bb5ac4, 0x9755c92247301a50, 0xb999bf7c4ff1b610, 0x6aeeb2f3b21e8fc9, 0x0fa8084cf91ac6ff, 0x10d226cf136e6189, 0xd302057a07d4fb21, 0x5f03800e20a0fcc3, 0x80118d4ae46bd210, 0x58ab61a522843733, 0x51edd575c5432a4b, 0x94ee6ff67f9197f7, 0x765669e0e5e8157b, 0xa5347830737132f0, 0x3ba485a69f01510c, 0x0b247d7b957a01c3, 0x1b3d63449fd807dc, 0x0fdc4721c30ad743, 0x8b535ed3829b2b14, 0xee41d0cad65d232c, 0xe6a99ed97a6a982f, 0x65ac6194c202003d, 0x692accf3a70573eb, 0xcc3c02c3e200d5af, 0x0d419e8b325914a3, 0x320f160f42c25e40, 0x00710d647a51fe7a, 0x3c947692330aed60, 0x9288aa280d355a7a, 0xa1806a9b791d1696, 0x5d60e38496763da1, 0x6c69e22e613fd0f4, 0x977fc2a5aadffb17, 0xfb7bd063fc5a94ba, 0x460c17992cbaece1, 0xf7822c5444d3297f, 0x344a9790c69b74aa, 0xb80a42e6cae09dce, 0x1b1361eaf2b1e757, 0xd84c1e758e236f01, 0x88e0b7be347627cc, 0x45246009b7a99490, 0x8011c6dd3fe50472, 0xc341d682bffb99d7, 0x2511be93808e2d15, 0xd5bc13d7fd739840, 0x2a3cd030679ae1ec, 0x8ad9898a4b9ee157, 0x3245fef0a8eaf521, 0x3d6d8dbbb427d2b0, 0x1ed146d8968b3981, 0x0c6a28bf7d45f3fc, 0x4a1fd3dbcee3c561, 0x4210ff6a476bf67e, 0xa559cce0d9199aac, 0xde39d47ef3723380, 0xe5b69d848ce42e35, 0xefa24296f8e79f52, 0x70190b59db9a5afc, 0x26f166cdb211e7bf, 0x4deaf2df3c6b8ef5, 0xf171dbdd670f1017, 0xb9059b05e9420d90, 0x2f0da855c9388754, 0x611d5e9ab77949cc, 0x2912038ac01163f4, 0x0231df50402b2fba, 0x45660fc4f3245f58, 0xb91cc97c7c8dac50, 0xb72d2aafe4953427, 0xfa6463f87e813d6b, 0x4515f7ee95d5c6a2, 0x1310e1c1a48d21c3, 0xad48a7810cdd8544, 0x4d5bdfefd5c9e631, 0xa43ed43f1fdcb7de, 0xe70cfc8fe1ee9626, 0xef4711b0d8dda442, 0xb80dd9bd4dab6c93, 0xa23be08d31ba4d93, 0x9b37db9d0335a39c, 0x494b6f870f5cfebc, 0x6d1b3c1149dda943, 0x372c943a518c1093, 0xad27af45e77c09c4, 0x3b6f92b646044604, 0xac2917909f5fcf4f, 0x2069a60e977e5557, 0x353a469e71014de5, 0x24be356281f55c15, 0x2b6d710ba8e9adea, 0x404ad1751c749c29, 0xed7311bf23d7f185, 0xba4f6976b4acc43e, 0x32d7198d2bc39000, 0xee667019014d6e01, 0x494ef3e128d14c83, 0x1f95a152baecd6be, 0x201648dff1f483a5, 0x68c28550c8384af6, 0x5fc834a6824a7f48, 0x7cd06cb7365eaf28, 0xd82bbd95e9b30909, 0x234f0d1694c53f6d, 0xd2fb7f4a96d83f4a, 0xff0d5da83acac05e, 0xf8f6b97f5585080a, 0x74236084be57b95b, 0xa25e40c03bbc36ad, 0x6b6e5c14ce88465b, 0x4378ffe93e1528c5, 0x94ca92a17118e2d2, }
NewCyclicPoly
eotask.py
""" This module implements the core class hierarchy for implementing EO tasks. An EO task is any class the inherits from the abstract EOTask class. Each EO task has to implement the execute method; invoking __call__ on a EO task instance invokes the execute method. EO tasks are meant primarily to operate on EO patches (i.e. instances of EOPatch). EO task classes are generally lightweight (i.e. not too complicated), short, and do one thing well. For example, an EO task might take as input an EOPatch containing cloud mask and return as a result the cloud coverage for that mask. Credits: Copyright (c) 2017-2019 Matej Aleksandrov, Matej Batič, Andrej Burja, Eva Erzin (Sinergise) Copyright (c) 2017-2019 Grega Milčinski, Matic Lubej, Devis Peresutti, Jernej Puc, Tomislav Slijepčević (Sinergise) Copyright (c) 2017-2019 Blaž Sovdat, Jovan Višnjić, Anže Zupanc, Lojze Žust (Sinergise) This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import sys import logging import datetime import inspect from collections import OrderedDict from abc import ABC, abstractmethod import attr from .utilities import FeatureParser LOGGER = logging.getLogger(__name__) class EOTask(ABC): """Base class for EOTask.""" def __new__(cls, *args, **kwargs): """Stores
__mul__(self, other): """Creates a composite task of this and passed task.""" return CompositeTask(other, self) def __call__(self, *eopatches, monitor=False, **kwargs): """Executes the task.""" # if monitor: # return self.execute_and_monitor(*eopatches, **kwargs) return self._execute_handling(*eopatches, **kwargs) def execute_and_monitor(self, *eopatches, **kwargs): """ In the current version nothing additional happens in this method """ return self._execute_handling(*eopatches, **kwargs) def _execute_handling(self, *eopatches, **kwargs): """ Handles measuring execution time and error propagation """ self.private_task_config.start_time = datetime.datetime.now() try: return_value = self.execute(*eopatches, **kwargs) self.private_task_config.end_time = datetime.datetime.now() return return_value except BaseException as exception: traceback = sys.exc_info()[2] # Some special exceptions don't accept an error message as a parameter and raise a TypeError in such case. try: errmsg = 'During execution of task {}: {}'.format(self.__class__.__name__, exception) extended_exception = type(exception)(errmsg) except TypeError: extended_exception = exception raise extended_exception.with_traceback(traceback) @abstractmethod def execute(self, *eopatches, **kwargs): """ Implement execute function """ raise NotImplementedError @staticmethod def _parse_features(features, new_names=False, rename_function=None, default_feature_type=None, allowed_feature_types=None): """ See eolearn.core.utilities.FeatureParser class. """ return FeatureParser(features, new_names=new_names, rename_function=rename_function, default_feature_type=default_feature_type, allowed_feature_types=allowed_feature_types) @attr.s(cmp=False) class _PrivateTaskConfig: """ A container for general EOTask parameters required during EOWorkflow and EOExecution :param init_args: A dictionary of parameters and values used for EOTask initialization :type init_args: OrderedDict :param uuid: An unique hexadecimal identifier string a task gets in EOWorkflow :type uuid: str or None :param start_time: Time when task execution started :type start_time: datetime.datetime or None :param end_time: Time when task execution ended :type end_time: datetime.datetime or None """ init_args = attr.ib() uuid = attr.ib(default=None) start_time = attr.ib(default=None) end_time = attr.ib(default=None) def __add__(self, other): return _PrivateTaskConfig(init_args=OrderedDict(list(self.init_args.items()) + list(other.init_args.items()))) class CompositeTask(EOTask): """Creates a task that is composite of two tasks. Note: Instead of directly using this task it might be more convenient to use `'*'` operation between tasks. Example: `composite_task = task1 * task2` :param eotask1: Task which will be executed first :type eotask1: EOTask :param eotask2: Task which will be executed on results of first task :type eotask2: EOTask """ def __init__(self, eotask1, eotask2): self.eotask1 = eotask1 self.eotask2 = eotask2 self.private_task_config = eotask1.private_task_config + eotask2.private_task_config def execute(self, *eopatches, **kwargs): return self.eotask2.execute(self.eotask1.execute(*eopatches, **kwargs))
initialization parameters and the order to the instance attribute `init_args`.""" self = super().__new__(cls) init_args = OrderedDict() for arg, value in zip(inspect.getfullargspec(self.__init__).args[1: len(args) + 1], args): init_args[arg] = repr(value) for arg in inspect.getfullargspec(self.__init__).args[len(args) + 1:]: if arg in kwargs: init_args[arg] = repr(kwargs[arg]) self.private_task_config = _PrivateTaskConfig(init_args=init_args) return self def
do_data_generation.py
import os, sys import time import warnings import argparse import configparser import ast import numpy as np from math import log from rdkit import Chem from rdkit import rdBase rdBase.DisableLog('rdApp.*')
sys.path.append('../src/') from python import helper as hp from python import fixed_parameters as FP parser = argparse.ArgumentParser(description='SMILES generation') parser.add_argument('-fn','--filename', type=str, help='Path to the fine-tuning txt file', required=True) parser.add_argument('-m','--model_path', type=str, help='Path to a pretrained model', required=True) parser.add_argument('-v','--verbose', type=bool, help='Verbose', required=True) def int_to_smile(array, indices_token, pad_char): """ From an array of int, return a list of molecules in string smile format Note: remove the padding char """ all_mols = [] for seq in array: new_mol = [indices_token[str(int(x))] for x in seq] all_mols.append(''.join(new_mol).replace(pad_char, '')) return all_mols def one_hot_encode(token_lists, n_chars): output = np.zeros((len(token_lists), len(token_lists[0]), n_chars)) for i, token_list in enumerate(token_lists): for j, token in enumerate(token_list): output[i, j, int(token)] = 1 return output def sample(model, temp, start_char, end_char, max_len, indices_token, token_indices): n_chars = len(indices_token) seed_token = [token_indices[start_char]] generated = indices_token[str(seed_token[0])] while generated[-1] != end_char and len(generated) < max_len: x_seed = one_hot_encode([seed_token], n_chars) full_preds = model.predict(x_seed, verbose=0)[0] logits = full_preds[-1] probas, next_char_ind = get_token_proba(logits, temp) next_char = indices_token[str(next_char_ind)] generated += next_char seed_token += [next_char_ind] return generated def get_token_proba(preds, temp): preds = np.asarray(preds).astype('float64') preds = np.log(preds) / temp exp_preds = np.exp(preds) probas = exp_preds / np.sum(exp_preds) char_ind = np.argmax(np.random.multinomial(1, probas, 1)) return probas, char_ind def softmax(preds): return np.exp(preds)/np.sum(np.exp(preds)) if __name__ == '__main__': start = time.time() #################################### # get back parameters args = vars(parser.parse_args()) verbose = args['verbose'] filename = args['filename'] model_path = args['model_path'] name_data = filename.split('/')[-1].replace('.txt','') config = configparser.ConfigParser() config.read('parameters.ini') if verbose: print('\nSTART SAMPLING') #################################### #################################### # path to save data save_path = f'results/{name_data}/generated_data/' os.makedirs(save_path, exist_ok=True) # path to checkpoints dir_ckpts = f'results/{name_data}/models/' #################################### #################################### # Parameters to sample novo smiles temp = float(config['EXPERIMENTS']['temp']) n_sample = int(config['EXPERIMENTS']['n_sample']) if n_sample>5000: warnings.warn('You will sample more than 5000 SMILES; this will take a while') max_len = int(config['PROCESSING']['max_len']) pad_char = FP.PROCESSING_FIXED['pad_char'] start_char = FP.PROCESSING_FIXED['start_char'] end_char = FP.PROCESSING_FIXED['end_char'] indices_token = FP.INDICES_TOKEN token_indices = FP.TOKEN_INDICES #################################### #################################### # start the sampling of new SMILES epoch = model_path.split('/')[-1].replace('.h5', '') if verbose: print(f'Sampling from model saved at epoch {epoch}') model = load_model(model_path) generated_smi = [] for n in range(n_sample): generated_smi.append(sample(model, temp, start_char, end_char, max_len+1, indices_token, token_indices)) hp.save_obj(generated_smi, f'{save_path}{epoch}_{temp}') end = time.time() if verbose: print(f'SAMPLING DONE for model from epoch {epoch} in {end-start:.2f} seconds') ####################################
from rdkit.Chem import Draw from keras.models import load_model
panic_test.go
// Gulu - Golang common utilities for everyone. // Copyright (c) 2019-present, b3log.org // // Gulu is licensed under Mulan PSL v2. // You can use this software according to the terms and conditions of the Mulan PSL v2. // You may obtain a copy of Mulan PSL v2 at: // http://license.coscl.org.cn/MulanPSL2 // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. package gulu import ( "sync" "testing" ) func TestRecover(t *testing.T)
{ var err error wg := sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() defer Panic.Recover(&err) panic("test panic") }() wg.Wait() t.Log(err) }
index.ts
export * from './file-storage-reducer';
export * from './file-storage-actions';
get_refs_handler.go
package server import ( "net/http" "github.com/wrgl/wrgl/pkg/api/payload" "github.com/wrgl/wrgl/pkg/ref"
values := r.URL.Query() rs := s.getRS(r) refs, err := ref.ListLocalRefs(rs, values["prefix"], values["notprefix"]) if err != nil { panic(err) } resp := &payload.GetRefsResponse{ Refs: map[string]*payload.Hex{}, } for k, v := range refs { h := &payload.Hex{} copy((*h)[:], v) resp.Refs[k] = h } WriteJSON(rw, r, resp) }
) func (s *Server) handleGetRefs(rw http.ResponseWriter, r *http.Request) {
file.go
package handler import ( "bytes" "context" "encoding/json" "fmt" "io" "io/ioutil" "time" "github.com/cjqpker/slidewindow" "github.com/sirupsen/logrus" "github.com/PaddlePaddle/PaddleDTX/crypto/core/aes" "github.com/PaddlePaddle/PaddleDTX/crypto/core/ecdsa" "github.com/PaddlePaddle/PaddleDTX/crypto/core/ecies" "github.com/PaddlePaddle/PaddleDTX/crypto/core/hash" "github.com/PaddlePaddle/PaddleDTX/dai/executor/storage/xuperdb" xdbchain "github.com/PaddlePaddle/PaddleDTX/xdb/blockchain" "github.com/PaddlePaddle/PaddleDTX/xdb/engine/common" "github.com/PaddlePaddle/PaddleDTX/xdb/errorx" "github.com/PaddlePaddle/PaddleDTX/xdb/pkgs/http" ) var defaultConcurrency uint64 = 10 // Define the ExecutionType of the executor, used to download sample files during task training const ( ProxyExecutionMode = "Proxy" SelfExecutionMode = "Self" ) // Storage stores files locally or xuperdb type Storage interface { Write(value io.Reader, key string) (string, error) Read(key string) (io.ReadCloser, error) } // FileStorage contains model storage and prediction result storage. type FileStorage struct { ModelStorage Storage EvaluationStorage Storage PredictStorage Storage } // FileDownload mode for download the sample file during the task execution. type FileDownload struct { Type string // value is 'Proxy' or 'Self' NodePrivateKey ecdsa.PrivateKey // the executor node's privatekey PrivateKey ecdsa.PrivateKey // used when the Type is 'Self' Host string }
// If f.Type is 'Proxy', download slices from storage nodes and recover the sample file, the key // required to decrypt the sample file and slices can be obtained through the file authorization application ID. only // after the file owner has confirmed the executor's file authorization application, the executor node can get the sample file. func (f *FileDownload) GetSampleFile(fileID string, chain Blockchain) (io.ReadCloser, error) { if f.Type == SelfExecutionMode { xuperdbClient := xuperdb.New(0, "", f.Host, f.PrivateKey) plainText, err := xuperdbClient.Read(fileID) if err != nil { return nil, errorx.Wrap(err, "failed to download the sample file from the dataOwner node, fileID: %s", fileID) } return plainText, nil } else { // 1. get the sample file info from chain file, err := chain.GetFileByID(fileID) if err != nil { return nil, errorx.New(errorx.ErrCodeInternal, "failed to get the sample file from contract, fileID: %s", fileID) } // 2. get the authorization ID, use the authKey to decrypt the sample file pubkey := ecdsa.PublicKeyFromPrivateKey(f.NodePrivateKey) fileAuths, err := chain.ListFileAuthApplications(&xdbchain.ListFileAuthOptions{ Applier: pubkey[:], Authorizer: file.Owner, Status: xdbchain.FileAuthApproved, FileID: fileID, TimeStart: 0, TimeEnd: time.Now().UnixNano(), Limit: 1, }) if err != nil { return nil, errorx.Wrap(err, "get the file authorization application failed, fileID: %s, Applier: %x, Authorizer: %x", fileID, pubkey[:], file.Owner) } if len(fileAuths) == 0 { return nil, errorx.New(errorx.ErrCodeInternal, "the file authorization application is empty, fileID: %s, Applier: %x, Authorizer: %x", fileID, pubkey[:], file.Owner) } // 3. obtain the derived key needed to decrypt the file through the AuthKey firstKey, secKey, err := f.getDecryptAuthKey(fileAuths[0].AuthKey) if err != nil { return nil, err } // 4. download slices and decrypt plainText, err := f.recoverFile(context.Background(), chain, file, firstKey, secKey) if err != nil { return nil, err } return plainText, nil } } // getDecryptAuthKey get the authorization key for file decryption, return firKey and secKey. // firKey used to decrypt the file and file's Structure // secKey used to decrypt slices, different slices of different stroage nodes use different AES Keys func (f *FileDownload) getDecryptAuthKey(authKey []byte) (firKey aes.AESKey, secKey map[string]map[string]aes.AESKey, err error) { // 1 parse ecdsa.PrivateKey to EC PrivateKey key applierPrivateKey := ecdsa.ParsePrivateKey(f.NodePrivateKey) // applier's EC private key decrypt the authKey decryptAuthKey, err := ecies.Decrypt(&applierPrivateKey, authKey) if err != nil { return firKey, secKey, errorx.NewCode(err, errorx.ErrCodeInternal, "fail to decrypt the authKey") } // 2 unmarshal decrypt authKey decryptKey := make(map[string]interface{}) if err = json.Unmarshal(decryptAuthKey, &decryptKey); err != nil { return firKey, secKey, errorx.NewCode(err, errorx.ErrCodeInternal, "fail to unmarshal decrypt authKey") } // 3 get the first-level derived key firstEncSecret, err := json.Marshal(decryptKey["firstEncSecret"]) if err != nil { return firKey, secKey, errorx.Wrap(err, "failed to marshal firstEncSecret") } if err = json.Unmarshal(firstEncSecret, &firKey); err != nil { return firKey, secKey, errorx.NewCode(err, errorx.ErrCodeInternal, "fail to get file first encrypt key") } // 4 get the second-level derived key secondEncSecret, err := json.Marshal(decryptKey["secondEncSecret"]) if err != nil { return firKey, secKey, errorx.Wrap(err, "failed to marshal secondEncSecret") } if err = json.Unmarshal(secondEncSecret, &secKey); err != nil { return firKey, secKey, errorx.NewCode(err, errorx.ErrCodeInternal, "fail to get slice second encrypt key") } return firKey, secKey, nil } // recoverFile recover file by pulling slices from storage nodes // The detailed steps are as follows: // 1. parameters check // 2. read file info from the blockchain // 3. decrypt the file's struct to get slice's order // 4. download slices from the storage node, if request fails, pull slices from other storage nodes // 5. slices decryption and combination // 6. decrypt the combined slices to get the original file func (f *FileDownload) recoverFile(ctx context.Context, chain Blockchain, file xdbchain.File, firstKey aes.AESKey, secKey map[string]map[string]aes.AESKey) (io.ReadCloser, error) { ctx, cancel := context.WithCancel(ctx) // get storage nodes allNodes, err := chain.ListNodes() if err != nil { cancel() return nil, errorx.Wrap(err, "failed to get nodes from blockchain") } // filter offline status storage nodes var nodes xdbchain.Nodes for _, n := range allNodes { if n.Online { nodes = append(nodes, n) } } if len(nodes) == 0 { cancel() return nil, errorx.New(errorx.ErrCodeInternal, "empty online nodes") } nodesMap := common.ToNodesMap(nodes) // recover file structure to get slice's order fs, err := f.recoverChainFileStructure(firstKey, file.Structure) if err != nil { cancel() return nil, err } // use sliding window sw := slidewindow.SlideWindow{ Total: uint64(len(fs)), Concurrency: defaultConcurrency, } sw.Init = func(ctx context.Context, s *slidewindow.Session) error { return nil } // get the mapping of slice-storageNodes slicesPool := makeSlicesPool4Read(file.Slices) sw.Task = func(ctx context.Context, s *slidewindow.Session) error { slice := fs[int(s.Index())] // get the list of storage nodes where the slice stored targetPool, ok := slicesPool[slice.SliceID] if !ok { return errorx.Internal(nil, "bad file structure") } for _, target := range targetPool { select { case <-ctx.Done(): return ctx.Err() default: } node, exist := nodesMap[string(target.NodeID)] if !exist || !node.Online { logger.WithField("node_id", string(target.NodeID)).Warn("abnormal node") continue } // pull slice r, err := f.pull(ctx, target.ID, file.ID, node.Address) if err != nil { logger.WithFields(logrus.Fields{ "slice_id": target.ID, "file_id": file.ID, "target_node": string(node.ID), }).WithError(err).Warn("failed to pull slice") continue } defer r.Close() // read slice and check slice hash cipherText, err := ioutil.ReadAll(r) if err != nil { logger.WithError(err).Warn("failed to read slice from target node") continue } if len(cipherText) != int(target.Length) { logger.WithFields(logrus.Fields{"expected": target.Length, "got": len(cipherText)}). Warn("invalid slice length.") continue } hGot := hash.HashUsingSha256(cipherText) if !bytes.Equal(hGot, target.CipherHash) { logger.WithFields(logrus.Fields{"expected": target.CipherHash, "got": hGot}). Warn("invalid slice hash.") continue } // decrypt the encrypted slice plainText, err := f.recover(secKey[target.ID][string(node.ID)], cipherText) if err != nil { logger.WithError(err).Error("failed to decrypt slice") continue } // trim 0 at the end of file if s.Index() != sw.Total-1 { s.Set("data", plainText) } else { s.Set("data", bytes.TrimRight(plainText, string([]byte{0}))) } break } if _, exist := s.Get("data"); !exist { return errorx.New(errorx.ErrCodeNotFound, "failed to pull slice %s", slice.SliceID) } return nil } reader, writer := io.Pipe() sw.Done = func(ctx context.Context, s *slidewindow.Session) error { data, exist := s.Get("data") if !exist { return errorx.New(errorx.ErrCodeNotFound, "failed to find data") } if _, err := writer.Write(data.([]byte)); err != nil { return errorx.NewCode(err, errorx.ErrCodeInternal, "failed to write") } // exit on success if s.Index() == uint64(len(fs)-1) { writer.Close() } return nil } go func() { defer cancel() if err := sw.Start(ctx); err != nil { writer.CloseWithError(err) } }() // decrypt recovered file fileCipherText, err := ioutil.ReadAll(reader) if err != nil { return nil, errorx.NewCode(err, errorx.ErrCodeInternal, "failed to read") } plainText, err := f.recover(firstKey, fileCipherText) if err != nil { return nil, errorx.NewCode(err, errorx.ErrCodeCrypto, "file decryption failed") } return ioutil.NopCloser(bytes.NewReader(plainText)), nil } // pull used pull slices from storage nodes func (f *FileDownload) pull(ctx context.Context, id, fileId, nodeAddress string) (io.ReadCloser, error) { // Add signature timestamp := time.Now().UnixNano() msg := fmt.Sprintf("%s,%s,%d", id, fileId, timestamp) sig, err := ecdsa.Sign(f.NodePrivateKey, hash.HashUsingSha256([]byte(msg))) if err != nil { return nil, errorx.Wrap(err, "failed to sign slice pull") } pubkey := ecdsa.PublicKeyFromPrivateKey(f.NodePrivateKey) url := fmt.Sprintf("http://%s/v1/slice/pull?slice_id=%s&file_id=%s&timestamp=%d&pubkey=%s&signature=%s", nodeAddress, id, fileId, timestamp, pubkey.String(), sig.String()) r, err := http.Get(ctx, url) if err != nil { return nil, errorx.Wrap(err, "failed to do get slice") } return r, nil } // recoverChainFileStructure get file structure from blockchain and decrypt it, // FileStructure used to get the correct file slices order func (f *FileDownload) recoverChainFileStructure(aesKey aes.AESKey, structure []byte) (xdbchain.FileStructure, error) { // decrypt structure decStruct, err := aes.DecryptUsingAESGCM(aesKey, structure, nil) if err != nil { return nil, errorx.NewCode(err, errorx.ErrCodeInternal, "failed to decrypt file structure") } var fStructures xdbchain.FileStructure if err := fStructures.Parse(decStruct); err != nil { return fStructures, errorx.NewCode(err, errorx.ErrCodeInternal, "failed to parse file structure") } return fStructures, nil } // recover decrypt the ciphertext using AES-GCM func (f *FileDownload) recover(aesKey aes.AESKey, ciphertext []byte) ([]byte, error) { plaintext, err := aes.DecryptUsingAESGCM(aesKey, ciphertext, nil) if err != nil { return nil, errorx.NewCode(err, errorx.ErrCodeInternal, "failed to decrypt file or slices") } return plaintext, nil } // makeSlicesPool4Read return the mapping of storage nodes where the slice is located // key is sliceID, value is the list of slices meta func makeSlicesPool4Read(srs []xdbchain.PublicSliceMeta) map[string][]xdbchain.PublicSliceMeta { slicesPool := make(map[string][]xdbchain.PublicSliceMeta) for _, s := range srs { var ss []xdbchain.PublicSliceMeta if v, exist := slicesPool[s.ID]; exist { ss = v } ss = append(ss, s) slicesPool[s.ID] = ss } return slicesPool }
// GetSampleFile download sample files, if f.Type is 'Self', download files from dataOwner nodes.
functions.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib::translate::*; use std::mem; use std::ptr; #[doc(alias = "alsactl_get_card_id_list")] #[doc(alias = "get_card_id_list")] pub fn card_id_list() -> Result<Vec<u32>, glib::Error> { unsafe { let mut entries = ptr::null_mut(); let mut entry_count = mem::MaybeUninit::uninit(); let mut error = ptr::null_mut(); let _ = ffi::alsactl_get_card_id_list(&mut entries, entry_count.as_mut_ptr(), &mut error); if error.is_null() { Ok(FromGlibContainer::from_glib_full_num( entries, entry_count.assume_init() as usize, )) } else {
Err(from_glib_full(error)) } } } #[doc(alias = "alsactl_get_card_sysname")] #[doc(alias = "get_card_sysname")] pub fn card_sysname(card_id: u32) -> Result<glib::GString, glib::Error> { unsafe { let mut sysname = ptr::null_mut(); let mut error = ptr::null_mut(); let _ = ffi::alsactl_get_card_sysname(card_id, &mut sysname, &mut error); if error.is_null() { Ok(from_glib_full(sysname)) } else { Err(from_glib_full(error)) } } } #[doc(alias = "alsactl_get_control_devnode")] #[doc(alias = "get_control_devnode")] pub fn control_devnode(card_id: u32) -> Result<glib::GString, glib::Error> { unsafe { let mut devnode = ptr::null_mut(); let mut error = ptr::null_mut(); let _ = ffi::alsactl_get_control_devnode(card_id, &mut devnode, &mut error); if error.is_null() { Ok(from_glib_full(devnode)) } else { Err(from_glib_full(error)) } } } #[doc(alias = "alsactl_get_control_sysname")] #[doc(alias = "get_control_sysname")] pub fn control_sysname(card_id: u32) -> Result<glib::GString, glib::Error> { unsafe { let mut sysname = ptr::null_mut(); let mut error = ptr::null_mut(); let _ = ffi::alsactl_get_control_sysname(card_id, &mut sysname, &mut error); if error.is_null() { Ok(from_glib_full(sysname)) } else { Err(from_glib_full(error)) } } } //#[doc(alias = "alsactl_sigs_marshal_VOID__BOXED_FLAGS")] //pub fn sigs_marshal_VOID__BOXED_FLAGS(closure: /*Ignored*/&glib::Closure, return_value: /*Ignored*/&mut glib::Value, n_param_values: u32, param_values: /*Ignored*/&glib::Value, invocation_hint: /*Unimplemented*/Option<Fundamental: Pointer>, marshal_data: /*Unimplemented*/Option<Fundamental: Pointer>) { // unsafe { TODO: call ffi:alsactl_sigs_marshal_VOID__BOXED_FLAGS() } //}
types.go
// Copyright 2019 The Kubernetes Authors. // SPDX-License-Identifier: Apache-2.0 package framework import ( "strings" "sigs.k8s.io/kustomize/kyaml/yaml" ) // Function defines a function which mutates or validates a collection of configuration // To create a structured validation result, return a Result as the error. type Function func() error // Result defines a function result which will be set on the emitted ResourceList type Result struct { // Name is the name of the function creating the result Name string `yaml:"name,omitempty"` // Items are the individual results Items []Item `yaml:"items,omitempty"` } // Severity indicates the severity of the result type Severity string const ( // Error indicates the result is an error. Will cause the function to exit non-0. Error Severity = "error" // Warning indicates the result is a warning Warning Severity = "warning" // Info indicates the result is an informative message Info Severity = "info" ) // Item defines a validation result type Item struct { // Message is a human readable message Message string `yaml:"message,omitempty"` // Severity is the severity of the Severity Severity `yaml:"severity,omitempty"` // ResourceRef is a reference to a resource ResourceRef yaml.ResourceMeta `yaml:"resourceRef,omitempty"` Field Field `yaml:"field,omitempty"` File File `yaml:"file,omitempty"` } // File references a file containing a resource type File struct { // Path is relative path to the file containing the resource Path string `yaml:"path,omitempty"` // Index is the index into the file containing the resource // (i.e. if there are multiple resources in a single file) Index int `yaml:"index,omitempty"` } // Field references a field in a resource type Field struct { // Path is the field path Path string `yaml:"path,omitempty"` // CurrentValue is the current field value
} // Error implement error func (e Result) Error() string { var msgs []string for _, i := range e.Items { msgs = append(msgs, i.Message) } return strings.Join(msgs, "\n\n") } // ExitCode provides the exit code based on the result func (e Result) ExitCode() int { for _, i := range e.Items { if i.Severity == Error { return 1 } } return 0 }
CurrentValue string `yaml:"currentValue,omitempty"` // SuggestedValue is the suggested field value SuggestedValue string `yaml:"suggestedValue,omitempty"`
session.go
package remotedialer import ( "context" "errors" "fmt" "io" "net" "os" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/gorilla/websocket" "github.com/sirupsen/logrus" ) type Session struct { sync.Mutex nextConnID int64 clientKey string sessionKey int64 conn *wsConn conns map[int64]*connection remoteClientKeys map[string]map[int]bool auth ConnectAuthorizer pingCancel context.CancelFunc pingWait sync.WaitGroup dialer Dialer client bool } // PrintTunnelData No tunnel logging by default var PrintTunnelData bool = true func init() { if os.Getenv("CATTLE_TUNNEL_DATA_DEBUG") == "false" { PrintTunnelData = false } } func NewClientSession(auth ConnectAuthorizer, conn *websocket.Conn) *Session { return &Session{ clientKey: "client", conn: newWSConn(conn), conns: map[int64]*connection{}, auth: auth, client: true, } } func
(sessionKey int64, clientKey string, conn *websocket.Conn) *Session { return &Session{ nextConnID: 1, clientKey: clientKey, sessionKey: sessionKey, conn: newWSConn(conn), conns: map[int64]*connection{}, remoteClientKeys: map[string]map[int]bool{}, } } func (s *Session) startPings(rootCtx context.Context) { ctx, cancel := context.WithCancel(rootCtx) s.pingCancel = cancel s.pingWait.Add(1) go func() { defer s.pingWait.Done() t := time.NewTicker(PingWriteInterval) defer t.Stop() for { select { case <-ctx.Done(): return case <-t.C: s.conn.Lock() if err := s.conn.conn.WriteControl(websocket.PingMessage, []byte(""), time.Now().Add(time.Second)); err != nil { logrus.WithError(err).Error("Error writing ping") } logrus.Debug("Wrote ping") s.conn.Unlock() } } }() } func (s *Session) stopPings() { if s.pingCancel == nil { return } s.pingCancel() s.pingWait.Wait() } func (s *Session) Serve(ctx context.Context) (int, error) { if s.client { s.startPings(ctx) } for { msType, reader, err := s.conn.NextReader() if err != nil { return 400, err } if msType != websocket.BinaryMessage { return 400, errWrongMessageType } if err := s.serveMessage(reader); err != nil { return 500, err } } } func (s *Session) serveMessage(reader io.Reader) error { message, err := newServerMessage(reader) if err != nil { return err } if PrintTunnelData { logrus.Debug("REQUEST ", message) } if message.messageType == Connect { if s.auth == nil || !s.auth(message.proto, message.address) { return errors.New("connect not allowed") } s.clientConnect(message) return nil } s.Lock() if message.messageType == AddClient && s.remoteClientKeys != nil { err := s.addRemoteClient(message.address) s.Unlock() return err } else if message.messageType == RemoveClient { err := s.removeRemoteClient(message.address) s.Unlock() return err } conn := s.conns[message.connID] s.Unlock() if conn == nil { if message.messageType == Data { err := fmt.Errorf("connection not found %s/%d/%d", s.clientKey, s.sessionKey, message.connID) newErrorMessage(message.connID, err).WriteTo(s.conn) } return nil } switch message.messageType { case Data: if _, err := io.Copy(conn.tunnelWriter(), message); err != nil { s.closeConnection(message.connID, err) } case Error: s.closeConnection(message.connID, message.Err()) } return nil } func parseAddress(address string) (string, int, error) { parts := strings.SplitN(address, "/", 2) if len(parts) != 2 { return "", 0, errors.New("not / separated") } v, err := strconv.Atoi(parts[1]) return parts[0], v, err } func (s *Session) addRemoteClient(address string) error { clientKey, sessionKey, err := parseAddress(address) if err != nil { return fmt.Errorf("invalid remote Session %s: %v", address, err) } keys := s.remoteClientKeys[clientKey] if keys == nil { keys = map[int]bool{} s.remoteClientKeys[clientKey] = keys } keys[int(sessionKey)] = true if PrintTunnelData { logrus.Debugf("ADD REMOTE CLIENT %s, SESSION %d", address, s.sessionKey) } return nil } func (s *Session) removeRemoteClient(address string) error { clientKey, sessionKey, err := parseAddress(address) if err != nil { return fmt.Errorf("invalid remote Session %s: %v", address, err) } keys := s.remoteClientKeys[clientKey] delete(keys, int(sessionKey)) if len(keys) == 0 { delete(s.remoteClientKeys, clientKey) } if PrintTunnelData { logrus.Debugf("REMOVE REMOTE CLIENT %s, SESSION %d", address, s.sessionKey) } return nil } func (s *Session) closeConnection(connID int64, err error) { s.Lock() conn := s.conns[connID] delete(s.conns, connID) if PrintTunnelData { logrus.Debugf("CONNECTIONS %d %d", s.sessionKey, len(s.conns)) } s.Unlock() if conn != nil { conn.tunnelClose(err) } } func (s *Session) clientConnect(message *message) { conn := newConnection(message.connID, s, message.proto, message.address) s.Lock() s.conns[message.connID] = conn if PrintTunnelData { logrus.Debugf("CONNECTIONS %d %d", s.sessionKey, len(s.conns)) } s.Unlock() go clientDial(s.dialer, conn, message) } func (s *Session) serverConnect(deadline time.Duration, proto, address string) (net.Conn, error) { connID := atomic.AddInt64(&s.nextConnID, 1) conn := newConnection(connID, s, proto, address) s.Lock() s.conns[connID] = conn if PrintTunnelData { logrus.Debugf("CONNECTIONS %d %d", s.sessionKey, len(s.conns)) } s.Unlock() _, err := s.writeMessage(newConnect(connID, deadline, proto, address)) if err != nil { s.closeConnection(connID, err) return nil, err } return conn, err } func (s *Session) writeMessage(message *message) (int, error) { if PrintTunnelData { logrus.Debug("WRITE ", message) } return message.WriteTo(s.conn) } func (s *Session) Close() { s.Lock() defer s.Unlock() s.stopPings() for _, connection := range s.conns { connection.tunnelClose(errors.New("tunnel disconnect")) } s.conns = map[int64]*connection{} } func (s *Session) sessionAdded(clientKey string, sessionKey int64) { client := fmt.Sprintf("%s/%d", clientKey, sessionKey) _, err := s.writeMessage(newAddClient(client)) if err != nil { s.conn.conn.Close() } } func (s *Session) sessionRemoved(clientKey string, sessionKey int64) { client := fmt.Sprintf("%s/%d", clientKey, sessionKey) _, err := s.writeMessage(newRemoveClient(client)) if err != nil { s.conn.conn.Close() } }
newSession
emit.rs
use std::rc::Rc; use swc_common::SourceMap; use swc_ecma_ast as ast; use swc_ecma_codegen::{text_writer::JsWriter, Config, Emitter}; use swc_ecma_transforms as transforms; use swc_ecma_visit::FoldWith; use crate::err::Error; use crate::swc_globals; pub struct Opt { pub minify: bool, } #[inline(never)] // for better profiling pub fn emit( _: &swc_globals::Initialized, ast: ast::Program, files: Rc<SourceMap>, options: Opt, ) -> Result<String, Error> { let mut wr = vec![]; let fixed_ast = ast.fold_with(&mut transforms::fixer(None)); { let mut emitter = Emitter {
cfg: Config { minify: options.minify, }, cm: files.clone(), wr: Box::new(JsWriter::new(files, "\n", &mut wr, None)), comments: None, }; emitter.emit_program(&fixed_ast)?; } Ok(String::from_utf8_lossy(&wr).into_owned()) }
tl_privacy_rule_gen.go
// Code generated by gotdgen, DO NOT EDIT. package tg import ( "context" "errors" "fmt" "sort" "strings" "go.uber.org/multierr" "github.com/gotd/td/bin" "github.com/gotd/td/tdp" "github.com/gotd/td/tgerr" ) // No-op definition for keeping imports. var ( _ = bin.Buffer{} _ = context.Background() _ = fmt.Stringer(nil) _ = strings.Builder{} _ = errors.Is _ = multierr.AppendInto _ = sort.Ints _ = tdp.Format _ = tgerr.Error{} ) // PrivacyValueAllowContacts represents TL type `privacyValueAllowContacts#fffe1bac`. // Allow all contacts // // See https://core.telegram.org/constructor/privacyValueAllowContacts for reference. type PrivacyValueAllowContacts struct { } // PrivacyValueAllowContactsTypeID is TL type id of PrivacyValueAllowContacts. const PrivacyValueAllowContactsTypeID = 0xfffe1bac // construct implements constructor of PrivacyRuleClass. func (p PrivacyValueAllowContacts) construct() PrivacyRuleClass { return &p } // Ensuring interfaces in compile-time for PrivacyValueAllowContacts. var ( _ bin.Encoder = &PrivacyValueAllowContacts{} _ bin.Decoder = &PrivacyValueAllowContacts{} _ bin.BareEncoder = &PrivacyValueAllowContacts{} _ bin.BareDecoder = &PrivacyValueAllowContacts{} _ PrivacyRuleClass = &PrivacyValueAllowContacts{} ) func (p *PrivacyValueAllowContacts) Zero() bool { if p == nil { return true } return true } // String implements fmt.Stringer. func (p *PrivacyValueAllowContacts) String() string { if p == nil { return "PrivacyValueAllowContacts(nil)" } type Alias PrivacyValueAllowContacts return fmt.Sprintf("PrivacyValueAllowContacts%+v", Alias(*p)) } // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. func (*PrivacyValueAllowContacts) TypeID() uint32 { return PrivacyValueAllowContactsTypeID } // TypeName returns name of type in TL schema. func (*PrivacyValueAllowContacts) TypeName() string { return "privacyValueAllowContacts" } // TypeInfo returns info about TL type. func (p *PrivacyValueAllowContacts) TypeInfo() tdp.Type { typ := tdp.Type{ Name: "privacyValueAllowContacts", ID: PrivacyValueAllowContactsTypeID, } if p == nil { typ.Null = true return typ } typ.Fields = []tdp.Field{} return typ } // Encode implements bin.Encoder. func (p *PrivacyValueAllowContacts) Encode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueAllowContacts#fffe1bac as nil") } b.PutID(PrivacyValueAllowContactsTypeID) return p.EncodeBare(b) } // EncodeBare implements bin.BareEncoder. func (p *PrivacyValueAllowContacts) EncodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueAllowContacts#fffe1bac as nil") } return nil } // Decode implements bin.Decoder. func (p *PrivacyValueAllowContacts) Decode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueAllowContacts#fffe1bac to nil") } if err := b.ConsumeID(PrivacyValueAllowContactsTypeID); err != nil { return fmt.Errorf("unable to decode privacyValueAllowContacts#fffe1bac: %w", err) } return p.DecodeBare(b) } // DecodeBare implements bin.BareDecoder. func (p *PrivacyValueAllowContacts) DecodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueAllowContacts#fffe1bac to nil") } return nil } // PrivacyValueAllowAll represents TL type `privacyValueAllowAll#65427b82`. // Allow all users // // See https://core.telegram.org/constructor/privacyValueAllowAll for reference. type PrivacyValueAllowAll struct { } // PrivacyValueAllowAllTypeID is TL type id of PrivacyValueAllowAll. const PrivacyValueAllowAllTypeID = 0x65427b82 // construct implements constructor of PrivacyRuleClass. func (p PrivacyValueAllowAll) construct() PrivacyRuleClass { return &p } // Ensuring interfaces in compile-time for PrivacyValueAllowAll. var ( _ bin.Encoder = &PrivacyValueAllowAll{} _ bin.Decoder = &PrivacyValueAllowAll{} _ bin.BareEncoder = &PrivacyValueAllowAll{} _ bin.BareDecoder = &PrivacyValueAllowAll{} _ PrivacyRuleClass = &PrivacyValueAllowAll{} ) func (p *PrivacyValueAllowAll) Zero() bool { if p == nil { return true } return true } // String implements fmt.Stringer. func (p *PrivacyValueAllowAll) String() string { if p == nil { return "PrivacyValueAllowAll(nil)" } type Alias PrivacyValueAllowAll return fmt.Sprintf("PrivacyValueAllowAll%+v", Alias(*p)) } // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. func (*PrivacyValueAllowAll) TypeID() uint32 { return PrivacyValueAllowAllTypeID } // TypeName returns name of type in TL schema. func (*PrivacyValueAllowAll) TypeName() string { return "privacyValueAllowAll" } // TypeInfo returns info about TL type. func (p *PrivacyValueAllowAll) TypeInfo() tdp.Type { typ := tdp.Type{ Name: "privacyValueAllowAll", ID: PrivacyValueAllowAllTypeID, } if p == nil { typ.Null = true return typ } typ.Fields = []tdp.Field{} return typ } // Encode implements bin.Encoder. func (p *PrivacyValueAllowAll) Encode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueAllowAll#65427b82 as nil") } b.PutID(PrivacyValueAllowAllTypeID) return p.EncodeBare(b) } // EncodeBare implements bin.BareEncoder. func (p *PrivacyValueAllowAll) EncodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueAllowAll#65427b82 as nil") } return nil } // Decode implements bin.Decoder. func (p *PrivacyValueAllowAll) Decode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueAllowAll#65427b82 to nil") } if err := b.ConsumeID(PrivacyValueAllowAllTypeID); err != nil { return fmt.Errorf("unable to decode privacyValueAllowAll#65427b82: %w", err) } return p.DecodeBare(b) } // DecodeBare implements bin.BareDecoder. func (p *PrivacyValueAllowAll) DecodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueAllowAll#65427b82 to nil") } return nil } // PrivacyValueAllowUsers represents TL type `privacyValueAllowUsers#b8905fb2`. // Allow only certain users // // See https://core.telegram.org/constructor/privacyValueAllowUsers for reference. type PrivacyValueAllowUsers struct { // Allowed users Users []int64 } // PrivacyValueAllowUsersTypeID is TL type id of PrivacyValueAllowUsers. const PrivacyValueAllowUsersTypeID = 0xb8905fb2 // construct implements constructor of PrivacyRuleClass. func (p PrivacyValueAllowUsers) construct() PrivacyRuleClass { return &p } // Ensuring interfaces in compile-time for PrivacyValueAllowUsers. var ( _ bin.Encoder = &PrivacyValueAllowUsers{} _ bin.Decoder = &PrivacyValueAllowUsers{} _ bin.BareEncoder = &PrivacyValueAllowUsers{} _ bin.BareDecoder = &PrivacyValueAllowUsers{} _ PrivacyRuleClass = &PrivacyValueAllowUsers{} ) func (p *PrivacyValueAllowUsers) Zero() bool { if p == nil { return true } if !(p.Users == nil) { return false } return true } // String implements fmt.Stringer. func (p *PrivacyValueAllowUsers) String() string { if p == nil { return "PrivacyValueAllowUsers(nil)" } type Alias PrivacyValueAllowUsers return fmt.Sprintf("PrivacyValueAllowUsers%+v", Alias(*p)) } // FillFrom fills PrivacyValueAllowUsers from given interface. func (p *PrivacyValueAllowUsers) FillFrom(from interface { GetUsers() (value []int64) }) { p.Users = from.GetUsers() } // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. func (*PrivacyValueAllowUsers) TypeID() uint32 { return PrivacyValueAllowUsersTypeID } // TypeName returns name of type in TL schema. func (*PrivacyValueAllowUsers) TypeName() string { return "privacyValueAllowUsers" } // TypeInfo returns info about TL type. func (p *PrivacyValueAllowUsers) TypeInfo() tdp.Type { typ := tdp.Type{ Name: "privacyValueAllowUsers", ID: PrivacyValueAllowUsersTypeID, } if p == nil { typ.Null = true return typ } typ.Fields = []tdp.Field{ { Name: "Users", SchemaName: "users", }, } return typ } // Encode implements bin.Encoder. func (p *PrivacyValueAllowUsers) Encode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueAllowUsers#b8905fb2 as nil") } b.PutID(PrivacyValueAllowUsersTypeID) return p.EncodeBare(b) } // EncodeBare implements bin.BareEncoder. func (p *PrivacyValueAllowUsers) EncodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueAllowUsers#b8905fb2 as nil") } b.PutVectorHeader(len(p.Users)) for _, v := range p.Users { b.PutLong(v) } return nil } // Decode implements bin.Decoder. func (p *PrivacyValueAllowUsers) Decode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueAllowUsers#b8905fb2 to nil") } if err := b.ConsumeID(PrivacyValueAllowUsersTypeID); err != nil { return fmt.Errorf("unable to decode privacyValueAllowUsers#b8905fb2: %w", err) } return p.DecodeBare(b) } // DecodeBare implements bin.BareDecoder. func (p *PrivacyValueAllowUsers) DecodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueAllowUsers#b8905fb2 to nil") } { headerLen, err := b.VectorHeader() if err != nil { return fmt.Errorf("unable to decode privacyValueAllowUsers#b8905fb2: field users: %w", err) } if headerLen > 0 { p.Users = make([]int64, 0, headerLen%bin.PreallocateLimit) } for idx := 0; idx < headerLen; idx++ { value, err := b.Long() if err != nil { return fmt.Errorf("unable to decode privacyValueAllowUsers#b8905fb2: field users: %w", err) } p.Users = append(p.Users, value) } } return nil } // GetUsers returns value of Users field. func (p *PrivacyValueAllowUsers) GetUsers() (value []int64) { return p.Users } // PrivacyValueDisallowContacts represents TL type `privacyValueDisallowContacts#f888fa1a`. // Disallow only contacts // // See https://core.telegram.org/constructor/privacyValueDisallowContacts for reference. type PrivacyValueDisallowContacts struct { } // PrivacyValueDisallowContactsTypeID is TL type id of PrivacyValueDisallowContacts. const PrivacyValueDisallowContactsTypeID = 0xf888fa1a // construct implements constructor of PrivacyRuleClass. func (p PrivacyValueDisallowContacts) construct() PrivacyRuleClass { return &p } // Ensuring interfaces in compile-time for PrivacyValueDisallowContacts. var ( _ bin.Encoder = &PrivacyValueDisallowContacts{} _ bin.Decoder = &PrivacyValueDisallowContacts{} _ bin.BareEncoder = &PrivacyValueDisallowContacts{} _ bin.BareDecoder = &PrivacyValueDisallowContacts{} _ PrivacyRuleClass = &PrivacyValueDisallowContacts{} ) func (p *PrivacyValueDisallowContacts) Zero() bool { if p == nil { return true } return true } // String implements fmt.Stringer. func (p *PrivacyValueDisallowContacts) String() string { if p == nil { return "PrivacyValueDisallowContacts(nil)" } type Alias PrivacyValueDisallowContacts return fmt.Sprintf("PrivacyValueDisallowContacts%+v", Alias(*p)) } // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. func (*PrivacyValueDisallowContacts) TypeID() uint32 { return PrivacyValueDisallowContactsTypeID } // TypeName returns name of type in TL schema. func (*PrivacyValueDisallowContacts) TypeName() string { return "privacyValueDisallowContacts" } // TypeInfo returns info about TL type. func (p *PrivacyValueDisallowContacts) TypeInfo() tdp.Type { typ := tdp.Type{ Name: "privacyValueDisallowContacts", ID: PrivacyValueDisallowContactsTypeID, } if p == nil { typ.Null = true return typ } typ.Fields = []tdp.Field{} return typ } // Encode implements bin.Encoder. func (p *PrivacyValueDisallowContacts) Encode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueDisallowContacts#f888fa1a as nil") } b.PutID(PrivacyValueDisallowContactsTypeID) return p.EncodeBare(b) } // EncodeBare implements bin.BareEncoder. func (p *PrivacyValueDisallowContacts) EncodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueDisallowContacts#f888fa1a as nil") } return nil } // Decode implements bin.Decoder. func (p *PrivacyValueDisallowContacts) Decode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueDisallowContacts#f888fa1a to nil") } if err := b.ConsumeID(PrivacyValueDisallowContactsTypeID); err != nil { return fmt.Errorf("unable to decode privacyValueDisallowContacts#f888fa1a: %w", err) } return p.DecodeBare(b) } // DecodeBare implements bin.BareDecoder. func (p *PrivacyValueDisallowContacts) DecodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueDisallowContacts#f888fa1a to nil") } return nil } // PrivacyValueDisallowAll represents TL type `privacyValueDisallowAll#8b73e763`. // Disallow all users // // See https://core.telegram.org/constructor/privacyValueDisallowAll for reference. type PrivacyValueDisallowAll struct { } // PrivacyValueDisallowAllTypeID is TL type id of PrivacyValueDisallowAll. const PrivacyValueDisallowAllTypeID = 0x8b73e763 // construct implements constructor of PrivacyRuleClass. func (p PrivacyValueDisallowAll) construct() PrivacyRuleClass { return &p } // Ensuring interfaces in compile-time for PrivacyValueDisallowAll. var ( _ bin.Encoder = &PrivacyValueDisallowAll{} _ bin.Decoder = &PrivacyValueDisallowAll{} _ bin.BareEncoder = &PrivacyValueDisallowAll{} _ bin.BareDecoder = &PrivacyValueDisallowAll{} _ PrivacyRuleClass = &PrivacyValueDisallowAll{} ) func (p *PrivacyValueDisallowAll) Zero() bool { if p == nil { return true } return true } // String implements fmt.Stringer. func (p *PrivacyValueDisallowAll) String() string { if p == nil { return "PrivacyValueDisallowAll(nil)" } type Alias PrivacyValueDisallowAll return fmt.Sprintf("PrivacyValueDisallowAll%+v", Alias(*p)) } // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. func (*PrivacyValueDisallowAll) TypeID() uint32 { return PrivacyValueDisallowAllTypeID } // TypeName returns name of type in TL schema. func (*PrivacyValueDisallowAll) TypeName() string { return "privacyValueDisallowAll" } // TypeInfo returns info about TL type. func (p *PrivacyValueDisallowAll) TypeInfo() tdp.Type { typ := tdp.Type{ Name: "privacyValueDisallowAll", ID: PrivacyValueDisallowAllTypeID, } if p == nil { typ.Null = true return typ } typ.Fields = []tdp.Field{} return typ } // Encode implements bin.Encoder. func (p *PrivacyValueDisallowAll) Encode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueDisallowAll#8b73e763 as nil") } b.PutID(PrivacyValueDisallowAllTypeID) return p.EncodeBare(b) } // EncodeBare implements bin.BareEncoder. func (p *PrivacyValueDisallowAll) EncodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueDisallowAll#8b73e763 as nil") } return nil } // Decode implements bin.Decoder. func (p *PrivacyValueDisallowAll) Decode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueDisallowAll#8b73e763 to nil") } if err := b.ConsumeID(PrivacyValueDisallowAllTypeID); err != nil { return fmt.Errorf("unable to decode privacyValueDisallowAll#8b73e763: %w", err) } return p.DecodeBare(b) } // DecodeBare implements bin.BareDecoder. func (p *PrivacyValueDisallowAll) DecodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueDisallowAll#8b73e763 to nil") } return nil } // PrivacyValueDisallowUsers represents TL type `privacyValueDisallowUsers#e4621141`. // Disallow only certain users // // See https://core.telegram.org/constructor/privacyValueDisallowUsers for reference. type PrivacyValueDisallowUsers struct { // Disallowed users Users []int64 } // PrivacyValueDisallowUsersTypeID is TL type id of PrivacyValueDisallowUsers. const PrivacyValueDisallowUsersTypeID = 0xe4621141 // construct implements constructor of PrivacyRuleClass. func (p PrivacyValueDisallowUsers) construct() PrivacyRuleClass { return &p } // Ensuring interfaces in compile-time for PrivacyValueDisallowUsers. var ( _ bin.Encoder = &PrivacyValueDisallowUsers{} _ bin.Decoder = &PrivacyValueDisallowUsers{} _ bin.BareEncoder = &PrivacyValueDisallowUsers{} _ bin.BareDecoder = &PrivacyValueDisallowUsers{} _ PrivacyRuleClass = &PrivacyValueDisallowUsers{} ) func (p *PrivacyValueDisallowUsers) Zero() bool { if p == nil { return true } if !(p.Users == nil) { return false } return true } // String implements fmt.Stringer. func (p *PrivacyValueDisallowUsers) String() string { if p == nil { return "PrivacyValueDisallowUsers(nil)" } type Alias PrivacyValueDisallowUsers return fmt.Sprintf("PrivacyValueDisallowUsers%+v", Alias(*p)) } // FillFrom fills PrivacyValueDisallowUsers from given interface. func (p *PrivacyValueDisallowUsers) FillFrom(from interface { GetUsers() (value []int64) }) { p.Users = from.GetUsers() } // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. func (*PrivacyValueDisallowUsers) TypeID() uint32 { return PrivacyValueDisallowUsersTypeID } // TypeName returns name of type in TL schema. func (*PrivacyValueDisallowUsers) TypeName() string { return "privacyValueDisallowUsers" } // TypeInfo returns info about TL type. func (p *PrivacyValueDisallowUsers) TypeInfo() tdp.Type { typ := tdp.Type{ Name: "privacyValueDisallowUsers", ID: PrivacyValueDisallowUsersTypeID, } if p == nil { typ.Null = true return typ } typ.Fields = []tdp.Field{ { Name: "Users", SchemaName: "users", }, } return typ } // Encode implements bin.Encoder. func (p *PrivacyValueDisallowUsers) Encode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueDisallowUsers#e4621141 as nil") } b.PutID(PrivacyValueDisallowUsersTypeID) return p.EncodeBare(b) } // EncodeBare implements bin.BareEncoder. func (p *PrivacyValueDisallowUsers) EncodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueDisallowUsers#e4621141 as nil") } b.PutVectorHeader(len(p.Users)) for _, v := range p.Users { b.PutLong(v) } return nil } // Decode implements bin.Decoder. func (p *PrivacyValueDisallowUsers) Decode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueDisallowUsers#e4621141 to nil") } if err := b.ConsumeID(PrivacyValueDisallowUsersTypeID); err != nil { return fmt.Errorf("unable to decode privacyValueDisallowUsers#e4621141: %w", err) } return p.DecodeBare(b) } // DecodeBare implements bin.BareDecoder. func (p *PrivacyValueDisallowUsers) DecodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueDisallowUsers#e4621141 to nil") } { headerLen, err := b.VectorHeader() if err != nil { return fmt.Errorf("unable to decode privacyValueDisallowUsers#e4621141: field users: %w", err) } if headerLen > 0 { p.Users = make([]int64, 0, headerLen%bin.PreallocateLimit) } for idx := 0; idx < headerLen; idx++ { value, err := b.Long() if err != nil { return fmt.Errorf("unable to decode privacyValueDisallowUsers#e4621141: field users: %w", err) } p.Users = append(p.Users, value) } } return nil } // GetUsers returns value of Users field. func (p *PrivacyValueDisallowUsers) GetUsers() (value []int64) { return p.Users } // PrivacyValueAllowChatParticipants represents TL type `privacyValueAllowChatParticipants#6b134e8e`. // Allow all participants of certain chats // // See https://core.telegram.org/constructor/privacyValueAllowChatParticipants for reference. type PrivacyValueAllowChatParticipants struct { // Allowed chats Chats []int64 } // PrivacyValueAllowChatParticipantsTypeID is TL type id of PrivacyValueAllowChatParticipants. const PrivacyValueAllowChatParticipantsTypeID = 0x6b134e8e // construct implements constructor of PrivacyRuleClass. func (p PrivacyValueAllowChatParticipants) construct() PrivacyRuleClass { return &p } // Ensuring interfaces in compile-time for PrivacyValueAllowChatParticipants. var ( _ bin.Encoder = &PrivacyValueAllowChatParticipants{} _ bin.Decoder = &PrivacyValueAllowChatParticipants{} _ bin.BareEncoder = &PrivacyValueAllowChatParticipants{} _ bin.BareDecoder = &PrivacyValueAllowChatParticipants{} _ PrivacyRuleClass = &PrivacyValueAllowChatParticipants{} ) func (p *PrivacyValueAllowChatParticipants) Zero() bool { if p == nil { return true } if !(p.Chats == nil) { return false } return true } // String implements fmt.Stringer. func (p *PrivacyValueAllowChatParticipants) String() string { if p == nil { return "PrivacyValueAllowChatParticipants(nil)" } type Alias PrivacyValueAllowChatParticipants return fmt.Sprintf("PrivacyValueAllowChatParticipants%+v", Alias(*p)) } // FillFrom fills PrivacyValueAllowChatParticipants from given interface. func (p *PrivacyValueAllowChatParticipants) FillFrom(from interface { GetChats() (value []int64) }) { p.Chats = from.GetChats() } // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. func (*PrivacyValueAllowChatParticipants) TypeID() uint32 { return PrivacyValueAllowChatParticipantsTypeID } // TypeName returns name of type in TL schema. func (*PrivacyValueAllowChatParticipants) TypeName() string { return "privacyValueAllowChatParticipants" } // TypeInfo returns info about TL type. func (p *PrivacyValueAllowChatParticipants) TypeInfo() tdp.Type { typ := tdp.Type{ Name: "privacyValueAllowChatParticipants", ID: PrivacyValueAllowChatParticipantsTypeID, } if p == nil { typ.Null = true return typ } typ.Fields = []tdp.Field{ { Name: "Chats", SchemaName: "chats", }, } return typ } // Encode implements bin.Encoder. func (p *PrivacyValueAllowChatParticipants) Encode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueAllowChatParticipants#6b134e8e as nil") } b.PutID(PrivacyValueAllowChatParticipantsTypeID) return p.EncodeBare(b) } // EncodeBare implements bin.BareEncoder. func (p *PrivacyValueAllowChatParticipants) EncodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueAllowChatParticipants#6b134e8e as nil") } b.PutVectorHeader(len(p.Chats)) for _, v := range p.Chats { b.PutLong(v) } return nil } // Decode implements bin.Decoder. func (p *PrivacyValueAllowChatParticipants) Decode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueAllowChatParticipants#6b134e8e to nil") } if err := b.ConsumeID(PrivacyValueAllowChatParticipantsTypeID); err != nil { return fmt.Errorf("unable to decode privacyValueAllowChatParticipants#6b134e8e: %w", err) } return p.DecodeBare(b) } // DecodeBare implements bin.BareDecoder. func (p *PrivacyValueAllowChatParticipants) DecodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueAllowChatParticipants#6b134e8e to nil") } { headerLen, err := b.VectorHeader() if err != nil { return fmt.Errorf("unable to decode privacyValueAllowChatParticipants#6b134e8e: field chats: %w", err) } if headerLen > 0 { p.Chats = make([]int64, 0, headerLen%bin.PreallocateLimit) } for idx := 0; idx < headerLen; idx++ { value, err := b.Long() if err != nil { return fmt.Errorf("unable to decode privacyValueAllowChatParticipants#6b134e8e: field chats: %w", err) } p.Chats = append(p.Chats, value) } } return nil } // GetChats returns value of Chats field. func (p *PrivacyValueAllowChatParticipants) GetChats() (value []int64) { return p.Chats } // PrivacyValueDisallowChatParticipants represents TL type `privacyValueDisallowChatParticipants#41c87565`. // Disallow only participants of certain chats // // See https://core.telegram.org/constructor/privacyValueDisallowChatParticipants for reference. type PrivacyValueDisallowChatParticipants struct { // Disallowed chats Chats []int64 } // PrivacyValueDisallowChatParticipantsTypeID is TL type id of PrivacyValueDisallowChatParticipants. const PrivacyValueDisallowChatParticipantsTypeID = 0x41c87565 // construct implements constructor of PrivacyRuleClass. func (p PrivacyValueDisallowChatParticipants) construct() PrivacyRuleClass { return &p } // Ensuring interfaces in compile-time for PrivacyValueDisallowChatParticipants. var ( _ bin.Encoder = &PrivacyValueDisallowChatParticipants{} _ bin.Decoder = &PrivacyValueDisallowChatParticipants{} _ bin.BareEncoder = &PrivacyValueDisallowChatParticipants{} _ bin.BareDecoder = &PrivacyValueDisallowChatParticipants{} _ PrivacyRuleClass = &PrivacyValueDisallowChatParticipants{} ) func (p *PrivacyValueDisallowChatParticipants) Zero() bool { if p == nil { return true } if !(p.Chats == nil) { return false } return true } // String implements fmt.Stringer. func (p *PrivacyValueDisallowChatParticipants) String() string { if p == nil { return "PrivacyValueDisallowChatParticipants(nil)" } type Alias PrivacyValueDisallowChatParticipants return fmt.Sprintf("PrivacyValueDisallowChatParticipants%+v", Alias(*p)) } // FillFrom fills PrivacyValueDisallowChatParticipants from given interface. func (p *PrivacyValueDisallowChatParticipants) FillFrom(from interface { GetChats() (value []int64) }) { p.Chats = from.GetChats() } // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. func (*PrivacyValueDisallowChatParticipants) TypeID() uint32 { return PrivacyValueDisallowChatParticipantsTypeID } // TypeName returns name of type in TL schema. func (*PrivacyValueDisallowChatParticipants) TypeName() string { return "privacyValueDisallowChatParticipants" } // TypeInfo returns info about TL type. func (p *PrivacyValueDisallowChatParticipants) TypeInfo() tdp.Type { typ := tdp.Type{ Name: "privacyValueDisallowChatParticipants", ID: PrivacyValueDisallowChatParticipantsTypeID, } if p == nil { typ.Null = true return typ
Name: "Chats", SchemaName: "chats", }, } return typ } // Encode implements bin.Encoder. func (p *PrivacyValueDisallowChatParticipants) Encode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueDisallowChatParticipants#41c87565 as nil") } b.PutID(PrivacyValueDisallowChatParticipantsTypeID) return p.EncodeBare(b) } // EncodeBare implements bin.BareEncoder. func (p *PrivacyValueDisallowChatParticipants) EncodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't encode privacyValueDisallowChatParticipants#41c87565 as nil") } b.PutVectorHeader(len(p.Chats)) for _, v := range p.Chats { b.PutLong(v) } return nil } // Decode implements bin.Decoder. func (p *PrivacyValueDisallowChatParticipants) Decode(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueDisallowChatParticipants#41c87565 to nil") } if err := b.ConsumeID(PrivacyValueDisallowChatParticipantsTypeID); err != nil { return fmt.Errorf("unable to decode privacyValueDisallowChatParticipants#41c87565: %w", err) } return p.DecodeBare(b) } // DecodeBare implements bin.BareDecoder. func (p *PrivacyValueDisallowChatParticipants) DecodeBare(b *bin.Buffer) error { if p == nil { return fmt.Errorf("can't decode privacyValueDisallowChatParticipants#41c87565 to nil") } { headerLen, err := b.VectorHeader() if err != nil { return fmt.Errorf("unable to decode privacyValueDisallowChatParticipants#41c87565: field chats: %w", err) } if headerLen > 0 { p.Chats = make([]int64, 0, headerLen%bin.PreallocateLimit) } for idx := 0; idx < headerLen; idx++ { value, err := b.Long() if err != nil { return fmt.Errorf("unable to decode privacyValueDisallowChatParticipants#41c87565: field chats: %w", err) } p.Chats = append(p.Chats, value) } } return nil } // GetChats returns value of Chats field. func (p *PrivacyValueDisallowChatParticipants) GetChats() (value []int64) { return p.Chats } // PrivacyRuleClass represents PrivacyRule generic type. // // See https://core.telegram.org/type/PrivacyRule for reference. // // Example: // g, err := tg.DecodePrivacyRule(buf) // if err != nil { // panic(err) // } // switch v := g.(type) { // case *tg.PrivacyValueAllowContacts: // privacyValueAllowContacts#fffe1bac // case *tg.PrivacyValueAllowAll: // privacyValueAllowAll#65427b82 // case *tg.PrivacyValueAllowUsers: // privacyValueAllowUsers#b8905fb2 // case *tg.PrivacyValueDisallowContacts: // privacyValueDisallowContacts#f888fa1a // case *tg.PrivacyValueDisallowAll: // privacyValueDisallowAll#8b73e763 // case *tg.PrivacyValueDisallowUsers: // privacyValueDisallowUsers#e4621141 // case *tg.PrivacyValueAllowChatParticipants: // privacyValueAllowChatParticipants#6b134e8e // case *tg.PrivacyValueDisallowChatParticipants: // privacyValueDisallowChatParticipants#41c87565 // default: panic(v) // } type PrivacyRuleClass interface { bin.Encoder bin.Decoder bin.BareEncoder bin.BareDecoder construct() PrivacyRuleClass // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. TypeID() uint32 // TypeName returns name of type in TL schema. TypeName() string // String implements fmt.Stringer. String() string // Zero returns true if current object has a zero value. Zero() bool } // AsInput tries to map PrivacyValueAllowChatParticipants to InputPrivacyValueAllowChatParticipants. func (p *PrivacyValueAllowChatParticipants) AsInput() *InputPrivacyValueAllowChatParticipants { value := new(InputPrivacyValueAllowChatParticipants) value.Chats = p.GetChats() return value } // AsInput tries to map PrivacyValueDisallowChatParticipants to InputPrivacyValueDisallowChatParticipants. func (p *PrivacyValueDisallowChatParticipants) AsInput() *InputPrivacyValueDisallowChatParticipants { value := new(InputPrivacyValueDisallowChatParticipants) value.Chats = p.GetChats() return value } // DecodePrivacyRule implements binary de-serialization for PrivacyRuleClass. func DecodePrivacyRule(buf *bin.Buffer) (PrivacyRuleClass, error) { id, err := buf.PeekID() if err != nil { return nil, err } switch id { case PrivacyValueAllowContactsTypeID: // Decoding privacyValueAllowContacts#fffe1bac. v := PrivacyValueAllowContacts{} if err := v.Decode(buf); err != nil { return nil, fmt.Errorf("unable to decode PrivacyRuleClass: %w", err) } return &v, nil case PrivacyValueAllowAllTypeID: // Decoding privacyValueAllowAll#65427b82. v := PrivacyValueAllowAll{} if err := v.Decode(buf); err != nil { return nil, fmt.Errorf("unable to decode PrivacyRuleClass: %w", err) } return &v, nil case PrivacyValueAllowUsersTypeID: // Decoding privacyValueAllowUsers#b8905fb2. v := PrivacyValueAllowUsers{} if err := v.Decode(buf); err != nil { return nil, fmt.Errorf("unable to decode PrivacyRuleClass: %w", err) } return &v, nil case PrivacyValueDisallowContactsTypeID: // Decoding privacyValueDisallowContacts#f888fa1a. v := PrivacyValueDisallowContacts{} if err := v.Decode(buf); err != nil { return nil, fmt.Errorf("unable to decode PrivacyRuleClass: %w", err) } return &v, nil case PrivacyValueDisallowAllTypeID: // Decoding privacyValueDisallowAll#8b73e763. v := PrivacyValueDisallowAll{} if err := v.Decode(buf); err != nil { return nil, fmt.Errorf("unable to decode PrivacyRuleClass: %w", err) } return &v, nil case PrivacyValueDisallowUsersTypeID: // Decoding privacyValueDisallowUsers#e4621141. v := PrivacyValueDisallowUsers{} if err := v.Decode(buf); err != nil { return nil, fmt.Errorf("unable to decode PrivacyRuleClass: %w", err) } return &v, nil case PrivacyValueAllowChatParticipantsTypeID: // Decoding privacyValueAllowChatParticipants#6b134e8e. v := PrivacyValueAllowChatParticipants{} if err := v.Decode(buf); err != nil { return nil, fmt.Errorf("unable to decode PrivacyRuleClass: %w", err) } return &v, nil case PrivacyValueDisallowChatParticipantsTypeID: // Decoding privacyValueDisallowChatParticipants#41c87565. v := PrivacyValueDisallowChatParticipants{} if err := v.Decode(buf); err != nil { return nil, fmt.Errorf("unable to decode PrivacyRuleClass: %w", err) } return &v, nil default: return nil, fmt.Errorf("unable to decode PrivacyRuleClass: %w", bin.NewUnexpectedID(id)) } } // PrivacyRule boxes the PrivacyRuleClass providing a helper. type PrivacyRuleBox struct { PrivacyRule PrivacyRuleClass } // Decode implements bin.Decoder for PrivacyRuleBox. func (b *PrivacyRuleBox) Decode(buf *bin.Buffer) error { if b == nil { return fmt.Errorf("unable to decode PrivacyRuleBox to nil") } v, err := DecodePrivacyRule(buf) if err != nil { return fmt.Errorf("unable to decode boxed value: %w", err) } b.PrivacyRule = v return nil } // Encode implements bin.Encode for PrivacyRuleBox. func (b *PrivacyRuleBox) Encode(buf *bin.Buffer) error { if b == nil || b.PrivacyRule == nil { return fmt.Errorf("unable to encode PrivacyRuleClass as nil") } return b.PrivacyRule.Encode(buf) }
} typ.Fields = []tdp.Field{ {
test_quobyte.py
# Copyright (c) 2015 Quobyte, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from oslo_config import cfg import six from manila import context from manila import exception from manila.share import configuration as config from manila.share import driver from manila.share.drivers.quobyte import jsonrpc from manila.share.drivers.quobyte import quobyte from manila import test from manila.tests import fake_share CONF = cfg.CONF def fake_rpc_handler(name, *args): if name == 'resolveVolumeName': return None elif name == 'createVolume': return {'volume_uuid': 'voluuid'} elif name == 'exportVolume': return {'nfs_server_ip': 'fake_location', 'nfs_export_path': '/fake_share'} elif name == 'getConfiguration': return { "tenant_configuration": [{ "domain_name": "fake_domain_name", "volume_access": [ {"volume_uuid": "fake_id_1", "restrict_to_network": "10.0.0.1", "read_only": False}, {"volume_uuid": "fake_id_1", "restrict_to_network": "10.0.0.2", "read_only": False}, {"volume_uuid": "fake_id_2", "restrict_to_network": "10.0.0.3", "read_only": False} ]}, {"domain_name": "fake_domain_name_2", "volume_access": [ {"volume_uuid": "fake_id_3", "restrict_to_network": "10.0.0.4", "read_only": False}, {"volume_uuid": "fake_id_3", "restrict_to_network": "10.0.0.5", "read_only": True}, {"volume_uuid": "fake_id_4", "restrict_to_network": "10.0.0.6", "read_only": False} ]} ] } else: return "Unknown fake rpc handler call" def create_fake_access(access_adr, access_id='fake_access_id', access_type='ip', access_level='rw'): return { 'access_id': access_id, 'access_type': access_type, 'access_to': access_adr, 'access_level': access_level } class QuobyteShareDriverTestCase(test.TestCase): """Tests QuobyteShareDriver.""" def setUp(self): super(QuobyteShareDriverTestCase, self).setUp() self._context = context.get_admin_context() CONF.set_default('driver_handles_share_servers', False) self.fake_conf = config.Configuration(None) self._driver = quobyte.QuobyteShareDriver(configuration=self.fake_conf) self._driver.rpc = mock.Mock() self.share = fake_share.fake_share(share_proto='NFS') self.access = fake_share.fake_access() @mock.patch('manila.share.drivers.quobyte.jsonrpc.JsonRpc', mock.Mock()) def test_do_setup_success(self): self._driver.rpc.call = mock.Mock(return_value=None) self._driver.do_setup(self._context) self._driver.rpc.call.assert_called_with('getInformation', {}) @mock.patch('manila.share.drivers.quobyte.jsonrpc.JsonRpc.__init__', mock.Mock(return_value=None)) @mock.patch.object(jsonrpc.JsonRpc, 'call', side_effect=exception.QBRpcException) def test_do_setup_failure(self, mock_call): self.assertRaises(exception.QBException, self._driver.do_setup, self._context) def test_create_share_new_volume(self): self._driver.rpc.call = mock.Mock(wraps=fake_rpc_handler) result = self._driver.create_share(self._context, self.share) self.assertEqual(self.share['export_location'], result) self._driver.rpc.call.assert_has_calls([ mock.call('createVolume', dict( name=self.share['name'], tenant_domain=self.share['project_id'], root_user_id=self.fake_conf.quobyte_default_volume_user, root_group_id=self.fake_conf.quobyte_default_volume_group, configuration_name=self.fake_conf.quobyte_volume_configuration )), mock.call('exportVolume', dict(protocol='NFS', volume_uuid='voluuid'))]) def test_create_share_existing_volume(self): self._driver.rpc.call = mock.Mock(wraps=fake_rpc_handler) self._driver.create_share(self._context, self.share) self._driver.rpc.call.assert_called_with( 'exportVolume', dict(protocol='NFS', volume_uuid='voluuid')) def test_create_share_wrong_protocol(self): share = {'share_proto': 'WRONG_PROTOCOL'} self.assertRaises(exception.QBException, self._driver.create_share, context=None, share=share) def test_delete_share_existing_volume(self): def rpc_handler(name, *args): if name == 'resolveVolumeName': return {'volume_uuid': 'voluuid'} elif name == 'exportVolume': return {} self._driver.configuration.quobyte_delete_shares = True self._driver.rpc.call = mock.Mock(wraps=rpc_handler) self._driver.delete_share(self._context, self.share) self._driver.rpc.call.assert_has_calls([ mock.call('resolveVolumeName', {'volume_name': 'fakename', 'tenant_domain': 'fake_project_uuid'}), mock.call('deleteVolume', {'volume_uuid': 'voluuid'}), mock.call('exportVolume', {'volume_uuid': 'voluuid', 'remove_export': True})]) def test_delete_share_existing_volume_disabled(self): def rpc_handler(name, *args): if name == 'resolveVolumeName': return {'volume_uuid': 'voluuid'} elif name == 'exportVolume': return {} CONF.set_default('quobyte_delete_shares', False) self._driver.rpc.call = mock.Mock(wraps=rpc_handler) self._driver.delete_share(self._context, self.share) self._driver.rpc.call.assert_called_with( 'exportVolume', {'volume_uuid': 'voluuid', 'remove_export': True}) @mock.patch.object(quobyte.LOG, 'warning') def test_delete_share_nonexisting_volume(self, mock_warning): def rpc_handler(name, *args): if name == 'resolveVolumeName': return None self._driver.rpc.call = mock.Mock(wraps=rpc_handler) self._driver.delete_share(self._context, self.share) mock_warning.assert_called_with( 'No volume found for share fake_project_uuid/fakename') def test_allow_access(self): def rpc_handler(name, *args): if name == 'resolveVolumeName': return {'volume_uuid': 'voluuid'} elif name == 'exportVolume': return {'nfs_server_ip': '10.10.1.1', 'nfs_export_path': '/voluuid'} self._driver.rpc.call = mock.Mock(wraps=rpc_handler) self._driver._allow_access(self._context, self.share, self.access) self._driver.rpc.call.assert_called_with( 'exportVolume', {'volume_uuid': 'voluuid', 'read_only': False, 'add_allow_ip': '10.0.0.1'}) def test_allow_ro_access(self): def rpc_handler(name, *args): if name == 'resolveVolumeName': return {'volume_uuid': 'voluuid'} elif name == 'exportVolume': return {'nfs_server_ip': '10.10.1.1', 'nfs_export_path': '/voluuid'} self._driver.rpc.call = mock.Mock(wraps=rpc_handler) ro_access = fake_share.fake_access(access_level='ro') self._driver._allow_access(self._context, self.share, ro_access) self._driver.rpc.call.assert_called_with( 'exportVolume', {'volume_uuid': 'voluuid', 'read_only': True, 'add_allow_ip': '10.0.0.1'}) def test_allow_access_nonip(self): self._driver.rpc.call = mock.Mock(wraps=fake_rpc_handler) self.access = fake_share.fake_access(**{"access_type": "non_existant_access_type"}) self.assertRaises(exception.InvalidShareAccess, self._driver._allow_access, self._context, self.share, self.access) def test_deny_access(self): def rpc_handler(name, *args): if name == 'resolveVolumeName': return {'volume_uuid': 'voluuid'} elif name == 'exportVolume': return {'nfs_server_ip': '10.10.1.1', 'nfs_export_path': '/voluuid'} self._driver.rpc.call = mock.Mock(wraps=rpc_handler) self._driver._deny_access(self._context, self.share, self.access) self._driver.rpc.call.assert_called_with( 'exportVolume', {'volume_uuid': 'voluuid', 'remove_allow_ip': '10.0.0.1'}) @mock.patch.object(quobyte.LOG, 'debug') def test_deny_access_nonip(self, mock_debug): self._driver.rpc.call = mock.Mock(wraps=fake_rpc_handler) self.access = fake_share.fake_access( access_type="non_existant_access_type") self._driver._deny_access(self._context, self.share, self.access) mock_debug.assert_called_with( 'Quobyte driver only supports ip access control. ' 'Ignoring deny access call for %s , %s', 'fakename', 'fake_project_uuid') def test_resolve_volume_name(self): self._driver.rpc.call = mock.Mock( return_value={'volume_uuid': 'fake_uuid'}) self._driver._resolve_volume_name('fake_vol_name', 'fake_domain_name') self._driver.rpc.call.assert_called_with( 'resolveVolumeName', {'volume_name': 'fake_vol_name', 'tenant_domain': 'fake_domain_name'}) def test_resolve_volume_name_NOENT(self): self._driver.rpc.call = mock.Mock( return_value=None) self.assertIsNone( self._driver._resolve_volume_name('fake_vol_name', 'fake_domain_name')) def test_resolve_volume_name_other_error(self): self._driver.rpc.call = mock.Mock( side_effect=exception.QBRpcException( result='fubar', qbcode=666)) self.assertRaises(exception.QBRpcException, self._driver._resolve_volume_name, volume_name='fake_vol_name', tenant_domain='fake_domain_name') @mock.patch.object(driver.ShareDriver, '_update_share_stats') def test_update_share_stats(self, mock_uss): self._driver._get_capacities = mock.Mock(return_value=[42, 23]) self._driver._update_share_stats() mock_uss.assert_called_once_with( dict(storage_protocol='NFS', vendor_name='Quobyte', share_backend_name=self._driver.backend_name, driver_version=self._driver.DRIVER_VERSION, total_capacity_gb=42, free_capacity_gb=23, reserved_percentage=0)) def test_get_capacities_gb(self): capval = 42115548133 useval = 19695128917 self._driver.rpc.call = mock.Mock( return_value={'total_logical_capacity': six.text_type(capval), 'total_logical_usage': six.text_type(useval)}) self.assertEqual((39.223160718, 20.880642548), self._driver._get_capacities()) @mock.patch.object(quobyte.QuobyteShareDriver, "_resolve_volume_name", return_value="fake_uuid") def test_ensure_share(self, mock_qb_resolve_volname): self._driver.rpc.call = mock.Mock(wraps=fake_rpc_handler) result = self._driver.ensure_share(self._context, self.share, None) self.assertEqual(self.share["export_location"], result) (mock_qb_resolve_volname. assert_called_once_with(self.share['name'], self.share['project_id'])) self._driver.rpc.call.assert_has_calls([ mock.call('exportVolume', dict( volume_uuid="fake_uuid", protocol='NFS' ))]) @mock.patch.object(quobyte.QuobyteShareDriver, "_resolve_volume_name", return_value=None) def test_ensure_deleted_share(self, mock_qb_resolve_volname): self._driver.rpc.call = mock.Mock(wraps=fake_rpc_handler) self.assertRaises(exception.ShareResourceNotFound, self._driver.ensure_share, self._context, self.share, None) (mock_qb_resolve_volname. assert_called_once_with(self.share['name'], self.share['project_id'])) @mock.patch.object(quobyte.QuobyteShareDriver, "_resize_share") def test_extend_share(self, mock_qsd_resize_share): self._driver.extend_share(ext_share=self.share, ext_size=2, share_server=None) mock_qsd_resize_share.assert_called_once_with(share=self.share, new_size=2) def test_resize_share(self): self._driver.rpc.call = mock.Mock(wraps=fake_rpc_handler) self._driver._resize_share(share=self.share, new_size=7) self._driver.rpc.call.assert_has_calls([ mock.call('setQuota', {"consumer": {"type": 3, "identifier": self.share["name"]}, "limits": {"type": 5, "value": 7}})]) @mock.patch.object(quobyte.QuobyteShareDriver, "_resolve_volume_name", return_value="fake_id_3") def test_fetch_existing_access(self, mock_qb_resolve_volname): self._driver.rpc.call = mock.Mock(wraps=fake_rpc_handler) old_access_1 = create_fake_access(access_id="old_1", access_adr="10.0.0.4") old_access_2 = create_fake_access(access_id="old_2", access_adr="10.0.0.5") exist_list = self._driver._fetch_existing_access(context=self._context, share=self.share) # assert expected result here self.assertEqual([old_access_1['access_to'], old_access_2['access_to']], [e.get('access_to') for e in exist_list]) (mock_qb_resolve_volname. assert_called_once_with(self.share['name'], self.share['project_id'])) @mock.patch.object(quobyte.QuobyteShareDriver, "_resize_share") def test_shrink_share(self, mock_qsd_resize_share):
shrink_size=3, share_server=None) mock_qsd_resize_share.assert_called_once_with(share=self.share, new_size=3) def test_subtract_access_lists(self): access_1 = create_fake_access(access_id="new_1", access_adr="10.0.0.5", access_type="rw",) access_2 = create_fake_access(access_id="old_1", access_adr="10.0.0.1", access_type="rw") access_3 = create_fake_access(access_id="old_2", access_adr="10.0.0.3", access_type="ro") access_4 = create_fake_access(access_id="new_2", access_adr="10.0.0.6", access_type="rw") access_5 = create_fake_access(access_id="old_3", access_adr="10.0.0.4", access_type="rw") min_list = [access_1, access_2, access_3, access_4] sub_list = [access_5, access_3, access_2] self.assertEqual([access_1, access_4], self._driver._subtract_access_lists(min_list, sub_list)) def test_subtract_access_lists_level(self): access_1 = create_fake_access(access_id="new_1", access_adr="10.0.0.5", access_level="rw") access_2 = create_fake_access(access_id="old_1", access_adr="10.0.0.1", access_level="rw") access_3 = create_fake_access(access_id="old_2", access_adr="10.0.0.3", access_level="rw") access_4 = create_fake_access(access_id="new_2", access_adr="10.0.0.6", access_level="rw") access_5 = create_fake_access(access_id="old_2_ro", access_adr="10.0.0.3", access_level="ro") min_list = [access_1, access_2, access_3, access_4] sub_list = [access_5, access_2] self.assertEqual([access_1, access_3, access_4], self._driver._subtract_access_lists(min_list, sub_list)) def test_subtract_access_lists_type(self): access_1 = create_fake_access(access_id="new_1", access_adr="10.0.0.5", access_type="ip") access_2 = create_fake_access(access_id="old_1", access_adr="10.0.0.1", access_type="ip") access_3 = create_fake_access(access_id="old_2", access_adr="10.0.0.3", access_type="ip") access_4 = create_fake_access(access_id="new_2", access_adr="10.0.0.6", access_type="ip") access_5 = create_fake_access(access_id="old_2_ro", access_adr="10.0.0.3", access_type="other") min_list = [access_1, access_2, access_3, access_4] sub_list = [access_5, access_2] self.assertEqual([access_1, access_3, access_4], self._driver._subtract_access_lists(min_list, sub_list)) @mock.patch.object(quobyte.QuobyteShareDriver, "_allow_access") @mock.patch.object(quobyte.QuobyteShareDriver, "_deny_access") def test_update_access_add_delete(self, qb_deny_mock, qb_allow_mock): access_1 = create_fake_access(access_id="new_1", access_adr="10.0.0.5", access_level="rw") access_2 = create_fake_access(access_id="old_1", access_adr="10.0.0.1", access_level="rw") access_3 = create_fake_access(access_id="old_2", access_adr="10.0.0.3", access_level="rw") self._driver.update_access(self._context, self.share, access_rules=None, add_rules=[access_1], delete_rules=[access_2, access_3]) qb_allow_mock.assert_called_once_with(self._context, self.share, access_1) deny_calls = [mock.call(self._context, self.share, access_2), mock.call(self._context, self.share, access_3)] qb_deny_mock.assert_has_calls(deny_calls) @mock.patch.object(quobyte.LOG, "warning") def test_update_access_no_rules(self, qb_log_mock): self._driver.update_access(context=None, share=None, access_rules=[], add_rules=[], delete_rules=[]) qb_log_mock.assert_has_calls([mock.ANY]) @mock.patch.object(quobyte.QuobyteShareDriver, "_subtract_access_lists") @mock.patch.object(quobyte.QuobyteShareDriver, "_fetch_existing_access") @mock.patch.object(quobyte.QuobyteShareDriver, "_allow_access") def test_update_access_recovery_additionals(self, qb_allow_mock, qb_exist_mock, qb_subtr_mock): new_access_1 = create_fake_access(access_id="new_1", access_adr="10.0.0.2") old_access = create_fake_access(access_id="fake_access_id", access_adr="10.0.0.1") new_access_2 = create_fake_access(access_id="new_2", access_adr="10.0.0.3") add_access_rules = [new_access_1, old_access, new_access_2] qb_exist_mock.return_value = [old_access] qb_subtr_mock.side_effect = [[new_access_1, new_access_2], []] self._driver.update_access(self._context, self.share, access_rules=add_access_rules, add_rules=[], delete_rules=[]) assert_calls = [mock.call(self._context, self.share, new_access_1), mock.call(self._context, self.share, new_access_2)] qb_allow_mock.assert_has_calls(assert_calls, any_order=True) qb_exist_mock.assert_called_once_with(self._context, self.share) @mock.patch.object(quobyte.QuobyteShareDriver, "_subtract_access_lists") @mock.patch.object(quobyte.QuobyteShareDriver, "_fetch_existing_access") @mock.patch.object(quobyte.QuobyteShareDriver, "_deny_access") def test_update_access_recovery_superfluous(self, qb_deny_mock, qb_exist_mock, qb_subtr_mock): old_access_1 = create_fake_access(access_id="old_1", access_adr="10.0.0.1") missing_access_1 = create_fake_access(access_id="mis_1", access_adr="10.0.0.2") old_access_2 = create_fake_access(access_id="old_2", access_adr="10.0.0.3") qb_exist_mock.side_effect = [[old_access_1, old_access_2]] qb_subtr_mock.side_effect = [[], [missing_access_1]] old_access_rules = [old_access_1, old_access_2] self._driver.update_access(self._context, self.share, access_rules=old_access_rules, add_rules=[], delete_rules=[]) qb_deny_mock.assert_called_once_with(self._context, self.share, (missing_access_1)) qb_exist_mock.assert_called_once_with(self._context, self.share) @mock.patch.object(quobyte.QuobyteShareDriver, "_subtract_access_lists") @mock.patch.object(quobyte.QuobyteShareDriver, "_fetch_existing_access") @mock.patch.object(quobyte.QuobyteShareDriver, "_deny_access") @mock.patch.object(quobyte.QuobyteShareDriver, "_allow_access") def test_update_access_recovery_add_superfluous(self, qb_allow_mock, qb_deny_mock, qb_exist_mock, qb_subtr_mock): new_access_1 = create_fake_access(access_id="new_1", access_adr="10.0.0.5") old_access_1 = create_fake_access(access_id="old_1", access_adr="10.0.0.1") old_access_2 = create_fake_access(access_id="old_2", access_adr="10.0.0.3") old_access_3 = create_fake_access(access_id="old_3", access_adr="10.0.0.4") miss_access_1 = create_fake_access(access_id="old_3", access_adr="10.0.0.4") new_access_2 = create_fake_access(access_id="new_2", access_adr="10.0.0.3", access_level="ro") new_access_rules = [new_access_1, old_access_1, old_access_2, old_access_3, new_access_2] qb_exist_mock.return_value = [old_access_1, old_access_2, old_access_3, miss_access_1] qb_subtr_mock.side_effect = [[new_access_1, new_access_2], [miss_access_1, old_access_2]] self._driver.update_access(self._context, self.share, new_access_rules, add_rules=[], delete_rules=[]) a_calls = [mock.call(self._context, self.share, new_access_1), mock.call(self._context, self.share, new_access_2)] qb_allow_mock.assert_has_calls(a_calls) b_calls = [mock.call(self._context, self.share, miss_access_1), mock.call(self._context, self.share, old_access_2)] qb_deny_mock.assert_has_calls(b_calls) qb_exist_mock.assert_called_once_with(self._context, self.share)
self._driver.shrink_share(shrink_share=self.share,
grpc.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers from google.api_core import operations_v1 from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.aiplatform_v1.types import specialist_pool from google.cloud.aiplatform_v1.types import specialist_pool_service from google.longrunning import operations_pb2 # type: ignore from .base import SpecialistPoolServiceTransport, DEFAULT_CLIENT_INFO class SpecialistPoolServiceGrpcTransport(SpecialistPoolServiceTransport): """gRPC backend transport for SpecialistPoolService. A service for creating and managing Customer SpecialistPools. When customers start Data Labeling jobs, they can reuse/create Specialist Pools to bring their own Specialists to label the data. Customers can add/remove Managers for the Specialist Pool on Cloud console, then Managers will get email notifications to manage Specialists and tasks on CrowdCompute console. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation and call it. It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ _stubs: Dict[str, Callable] def __init__( self, *, host: str = "aiplatform.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: # Ignore credentials if a channel was passed. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None else: if api_mtls_endpoint: host = api_mtls_endpoint # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: self._ssl_channel_credentials = SslCredentials().ssl_credentials else: if client_cert_source_for_mtls and not ssl_channel_credentials: cert, key = client_cert_source_for_mtls() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) # The base transport sets the host, credentials and scopes super().__init__( host=host, credentials=credentials, credentials_file=credentials_file, scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, # use the credentials which are saved credentials=self._credentials, # Set ``credentials_file`` to ``None`` here as # the credentials that we saved earlier should be used. credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) # Wrap messages. This must be done after self._grpc_channel exists self._prep_wrapped_messages(client_info) @classmethod def create_channel( cls, host: str = "aiplatform.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. quota_project_id (Optional[str]): An optional project to use for billing and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: grpc.Channel: A gRPC channel object. Raises: google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: """Return the channel designed to connect to this service. """ return self._grpc_channel @property def operations_client(self) -> operations_v1.OperationsClient: """Create the client designed to process long-running operations. This property caches on the instance; repeated calls return the same client. """ # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: self._operations_client = operations_v1.OperationsClient(self.grpc_channel) # Return the client from cache. return self._operations_client @property def create_specialist_pool( self, ) -> Callable[ [specialist_pool_service.CreateSpecialistPoolRequest], operations_pb2.Operation ]: r"""Return a callable for the create specialist pool method over gRPC. Creates a SpecialistPool. Returns: Callable[[~.CreateSpecialistPoolRequest], ~.Operation]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_specialist_pool" not in self._stubs: self._stubs["create_specialist_pool"] = self.grpc_channel.unary_unary( "/google.cloud.aiplatform.v1.SpecialistPoolService/CreateSpecialistPool", request_serializer=specialist_pool_service.CreateSpecialistPoolRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_specialist_pool"] @property def
( self, ) -> Callable[ [specialist_pool_service.GetSpecialistPoolRequest], specialist_pool.SpecialistPool, ]: r"""Return a callable for the get specialist pool method over gRPC. Gets a SpecialistPool. Returns: Callable[[~.GetSpecialistPoolRequest], ~.SpecialistPool]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_specialist_pool" not in self._stubs: self._stubs["get_specialist_pool"] = self.grpc_channel.unary_unary( "/google.cloud.aiplatform.v1.SpecialistPoolService/GetSpecialistPool", request_serializer=specialist_pool_service.GetSpecialistPoolRequest.serialize, response_deserializer=specialist_pool.SpecialistPool.deserialize, ) return self._stubs["get_specialist_pool"] @property def list_specialist_pools( self, ) -> Callable[ [specialist_pool_service.ListSpecialistPoolsRequest], specialist_pool_service.ListSpecialistPoolsResponse, ]: r"""Return a callable for the list specialist pools method over gRPC. Lists SpecialistPools in a Location. Returns: Callable[[~.ListSpecialistPoolsRequest], ~.ListSpecialistPoolsResponse]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_specialist_pools" not in self._stubs: self._stubs["list_specialist_pools"] = self.grpc_channel.unary_unary( "/google.cloud.aiplatform.v1.SpecialistPoolService/ListSpecialistPools", request_serializer=specialist_pool_service.ListSpecialistPoolsRequest.serialize, response_deserializer=specialist_pool_service.ListSpecialistPoolsResponse.deserialize, ) return self._stubs["list_specialist_pools"] @property def delete_specialist_pool( self, ) -> Callable[ [specialist_pool_service.DeleteSpecialistPoolRequest], operations_pb2.Operation ]: r"""Return a callable for the delete specialist pool method over gRPC. Deletes a SpecialistPool as well as all Specialists in the pool. Returns: Callable[[~.DeleteSpecialistPoolRequest], ~.Operation]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_specialist_pool" not in self._stubs: self._stubs["delete_specialist_pool"] = self.grpc_channel.unary_unary( "/google.cloud.aiplatform.v1.SpecialistPoolService/DeleteSpecialistPool", request_serializer=specialist_pool_service.DeleteSpecialistPoolRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_specialist_pool"] @property def update_specialist_pool( self, ) -> Callable[ [specialist_pool_service.UpdateSpecialistPoolRequest], operations_pb2.Operation ]: r"""Return a callable for the update specialist pool method over gRPC. Updates a SpecialistPool. Returns: Callable[[~.UpdateSpecialistPoolRequest], ~.Operation]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_specialist_pool" not in self._stubs: self._stubs["update_specialist_pool"] = self.grpc_channel.unary_unary( "/google.cloud.aiplatform.v1.SpecialistPoolService/UpdateSpecialistPool", request_serializer=specialist_pool_service.UpdateSpecialistPoolRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_specialist_pool"] def close(self): self.grpc_channel.close() __all__ = ("SpecialistPoolServiceGrpcTransport",)
get_specialist_pool
ApplicationsGraph.js
import { Cell, Pie, PieChart, Tooltip } from 'recharts'; import React from 'react'; import Box from '@material-ui/core/Box'; import makeStyles from '@material-ui/core/styles/makeStyles'; const useStyles = makeStyles(theme => ({ customTooltip: { color: theme.palette.text.primary, backgroundColor: theme.palette.background.paper, padding: 5, }, })); const ApplicationsGraph = ({ pieData, colors }) => { const classes = useStyles();
<Box className={classes.customTooltip}> <label>{`${payload[0].name} : ${payload[0].value}%`}</label> </Box> ); } return null; }; return ( <PieChart width={194} height={194}> <Pie data={pieData} color="#000000" dataKey="value" nameKey="name" cx="50%" cy="50%" isAnimationActive={true} outerRadius={95} fill="#8884d8"> {pieData.map((entry, index) => ( <Cell key={`cell-${index}`} fill={colors[index % colors.length]} /> ))} </Pie> <Tooltip content={<CustomTooltip />} /> </PieChart> ); }; export default ApplicationsGraph;
const CustomTooltip = ({ active, payload }) => { if (active) { return (
get_guild_roles.rs
use crate::{ client::Client, request::Request, response::{marker::ListBody, ResponseFuture}, routing::Route, }; use twilight_model::{guild::Role, id::GuildId}; /// Get the roles of a guild. #[must_use = "requests must be configured and executed"] pub struct GetGuildRoles<'a> { guild_id: GuildId, http: &'a Client, } impl<'a> GetGuildRoles<'a> { pub(crate) const fn new(http: &'a Client, guild_id: GuildId) -> Self { Self { guild_id, http } } /// Execute the request, returning a future resolving to a [`Response`]. /// /// [`Response`]: crate::response::Response pub fn exec(self) -> ResponseFuture<ListBody<Role>> { let request = Request::from_route(&Route::GetGuildRoles {
} }
guild_id: self.guild_id.get(), }); self.http.request(request)
capabilities.rs
use core::{convert::TryFrom, marker::PhantomData}; use contract::contract_api::{storage, TURef}; use types::{ bytesrepr::{FromBytes, ToBytes}, AccessRights, CLTyped, Key, }; /// Trait representing the ability to read a value. Use case: a key /// for the blockdag global state (`TURef`) is obviously Readable, /// however if we abstract over it then we can write unit tests for /// smart contracts much more easily. pub trait Readable<T> { fn read(self) -> T; } /// Trait representing the ability to write a value. See `Readable` /// for use case. pub trait Writable<T> { fn write(self, value: T); } /// Trait representing the ability to add a value `t` to some stored /// value of the same type. See `Readable` for use case. pub trait Addable<T> { fn add(self, value: T); } /// Add-only URef #[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)] pub struct RefWithAddRights<T>([u8; 32], PhantomData<T>); impl<T> RefWithAddRights<T> { const fn access_rights() -> AccessRights { AccessRights::ADD } } impl<T> TryFrom<Key> for RefWithAddRights<T> { type Error = (); fn try_from(key: Key) -> Result<Self, Self::Error> { match key { Key::URef(uref) if uref.access_rights() >= Some(Self::access_rights()) => { Ok(RefWithAddRights(uref.addr(), PhantomData)) } _ => Err(()), } } } impl<T: CLTyped + ToBytes> Addable<T> for RefWithAddRights<T> { fn add(self, value: T) { let turef = TURef::<T>::new(self.0, Self::access_rights()); storage::add(turef, value); } } /// Read, Add, Write URef #[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)] pub struct RefWithReadAddWriteRights<T>([u8; 32], PhantomData<T>); impl<T> RefWithReadAddWriteRights<T> { const fn access_rights() -> AccessRights { AccessRights::READ_ADD_WRITE } } impl<T: CLTyped> Into<TURef<T>> for RefWithReadAddWriteRights<T> { fn into(self) -> TURef<T> { TURef::new(self.0, Self::access_rights()) } } impl<T> TryFrom<Key> for RefWithReadAddWriteRights<T> { type Error = ();
fn try_from(key: Key) -> Result<Self, Self::Error> { match key { Key::URef(uref) if uref.access_rights() >= Some(Self::access_rights()) => { Ok(RefWithReadAddWriteRights(uref.addr(), PhantomData)) } _ => Err(()), } } } impl<T: CLTyped + FromBytes> Readable<T> for RefWithReadAddWriteRights<T> { fn read(self) -> T { let turef = self.into(); storage::read(turef) .expect("value should deserialize") .expect("should find value") } } impl<T: CLTyped + ToBytes> Writable<T> for RefWithReadAddWriteRights<T> { fn write(self, value: T) { let turef = self.into(); storage::write(turef, value); } } impl<T: CLTyped + ToBytes + FromBytes> Addable<T> for RefWithReadAddWriteRights<T> { fn add(self, value: T) { let turef = self.into(); storage::add(turef, value); } }
groceries.py
# groceries.py products = [ {"id":1, "name": "Chocolate Sandwich Cookies", "department": "snacks", "aisle": "cookies cakes", "price": 3.50}, {"id":2, "name": "All-Seasons Salt", "department": "pantry", "aisle": "spices seasonings", "price": 4.99}, {"id":3, "name": "Robust Golden Unsweetened Oolong Tea", "department": "beverages", "aisle": "tea", "price": 2.49}, {"id":4, "name": "Smart Ones Classic Favorites Mini Rigatoni With Vodka Cream Sauce", "department": "frozen", "aisle": "frozen meals", "price": 6.99}, {"id":5, "name": "Green Chile Anytime Sauce", "department": "pantry", "aisle": "marinades meat preparation", "price": 7.99}, {"id":6, "name": "Dry Nose Oil", "department": "personal care", "aisle": "cold flu allergy", "price": 21.99}, {"id":7, "name": "Pure Coconut Water With Orange", "department": "beverages", "aisle": "juice nectars", "price": 3.50}, {"id":8, "name": "Cut Russet Potatoes Steam N' Mash", "department": "frozen", "aisle": "frozen produce", "price": 4.25}, {"id":9, "name": "Light Strawberry Blueberry Yogurt", "department": "dairy eggs", "aisle": "yogurt", "price": 6.50}, {"id":10, "name": "Sparkling Orange Juice & Prickly Pear Beverage", "department": "beverages", "aisle": "water seltzer sparkling water", "price": 2.99}, {"id":11, "name": "Peach Mango Juice", "department": "beverages", "aisle": "refrigerated", "price": 1.99}, {"id":12, "name": "Chocolate Fudge Layer Cake", "department": "frozen", "aisle": "frozen dessert", "price": 18.50}, {"id":13, "name": "Saline Nasal Mist", "department": "personal care", "aisle": "cold flu allergy", "price": 16.00}, {"id":14, "name": "Fresh Scent Dishwasher Cleaner", "department": "household", "aisle": "dish detergents", "price": 4.99}, {"id":15, "name": "Overnight Diapers Size 6", "department": "babies", "aisle": "diapers wipes", "price": 25.50}, {"id":16, "name": "Mint Chocolate Flavored Syrup", "department": "snacks", "aisle": "ice cream toppings", "price": 4.50}, {"id":17, "name": "Rendered Duck Fat", "department": "meat seafood", "aisle": "poultry counter", "price": 9.99}, {"id":18, "name": "Pizza for One Suprema Frozen Pizza", "department": "frozen", "aisle": "frozen pizza", "price": 12.50}, {"id":19, "name": "Gluten Free Quinoa Three Cheese & Mushroom Blend", "department": "dry goods pasta", "aisle": "grains rice dried goods", "price": 3.99}, {"id":20, "name": "Pomegranate Cranberry & Aloe Vera Enrich Drink", "department": "beverages", "aisle": "juice nectars", "price": 4.25} ] # based on data from Instacart: https://www.instacart.com/datasets/grocery-shopping-2017 # product part 1 # -------------- # THERE ARE 20 PRODUCTS: # -------------- # + All-Seasons Salt ($4.99) # + Chocolate Fudge Layer Cake ($18.50) # + Chocolate Sandwich Cookies ($3.50) # + Cut Russet Potatoes Steam N' Mash ($4.25) # + Dry Nose Oil ($21.99) # + Fresh Scent Dishwasher Cleaner ($4.99) # + Gluten Free Quinoa Three Cheese & Mushroom Blend ($3.99) # + Green Chile Anytime Sauce ($7.99) # + Light Strawberry Blueberry Yogurt ($6.50) # + Mint Chocolate Flavored Syrup ($4.50) # + Overnight Diapers Size 6 ($25.50) # + Peach Mango Juice ($1.99) # + Pizza For One Suprema Frozen Pizza ($12.50) # + Pomegranate Cranberry & Aloe Vera Enrich Drink ($4.25) # + Pure Coconut Water With Orange ($3.50) # + Rendered Duck Fat ($9.99) # + Robust Golden Unsweetened Oolong Tea ($2.49) # + Saline Nasal Mist ($16.00) # + Smart Ones Classic Favorites Mini Rigatoni With Vodka Cream Sauce ($6.99) # + Sparkling Orange Juice & Prickly Pear Beverage ($2.99) products_count = len(products) print("----------------------") print("THERE ARE " + str(products_count) + " PRODUCTS:") print("----------------------") def sort_by_name(any_product):
sorted_products = sorted(products, key=sort_by_name) for p in sorted_products: #print(p["name"]) #price_usd = p["price"] price_usd = " (${0:.2f})".format(p["price"]) print("..." + p["name"] + price_usd) # # DEPARTMENTS (PART 2) # # -------------- # THERE ARE 10 DEPARTMENTS: # -------------- # + Babies (1 product) # + Beverages (5 products) # + Dairy Eggs (1 product) # + Dry Goods Pasta (1 product) # + Frozen (4 products) # + Household (1 product) # + Meat Seafood (1 product) # + Pantry (2 products) # + Personal Care (2 products) # + Snacks (2 products) departments = [] for p in products: #print(p["department"]) departments.append(p["department"]) #if p["department"] not in departments: # departments.append(p["department"]) unique_departments = list(set(departments)) department_count = len(unique_departments) print("--------------") print("THERE ARE " + str(department_count) + " DEPARTMENTS:") print("--------------") unique_departments.sort() for d in unique_departments: matching_products = [p for p in products if p["department"] ==d] matching_products_count = len(matching_products) if matching_products_count >1: label = "products" else: label = "product" print(" + " + d.title() + " (" + str(matching_products_count) + " " + label + ")")
return any_product["name"]
32.js
/** * Copyright IBM Corp. 2019, 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * * Code generated by @carbon/icon-build-helpers. DO NOT EDIT. */ 'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var Icon = require('../../Icon-1f3f78db.js'); require('@carbon/icon-helpers'); require('prop-types'); var React = _interopDefault(require('react'));
var _ref2 = /*#__PURE__*/ /*#__PURE__*/ React.createElement("path", { d: "M9.5,8H20.1a5,5,0,1,0,0-2H9.5a5.5,5.5,0,0,0,0,11h11a3.5,3.5,0,0,1,0,7H11.9a5,5,0,1,0,0,2h8.6a5.5,5.5,0,0,0,0-11H9.5a3.5,3.5,0,0,1,0-7ZM25,4a3,3,0,1,1-3,3A3,3,0,0,1,25,4ZM7,28a3,3,0,1,1,3-3A3,3,0,0,1,7,28Z" }); var WatsonHealth3DCurveAutoColon32 = /*#__PURE__*/React.forwardRef(function WatsonHealth3DCurveAutoColon32(_ref, ref) { var children = _ref.children, rest = Icon._objectWithoutProperties(_ref, ["children"]); return /*#__PURE__*/React.createElement(Icon.Icon, Icon._extends({ width: 32, height: 32, viewBox: "0 0 32 32", xmlns: "http://www.w3.org/2000/svg", fill: "currentColor", ref: ref }, rest), _ref2, children); }); module.exports = WatsonHealth3DCurveAutoColon32;
datagram_frame.go
package wire import ( "bytes" "io" "github.com/PKURio/quic-go/internal/protocol" "github.com/PKURio/quic-go/quicvarint" ) // A DatagramFrame is a DATAGRAM frame type DatagramFrame struct { DataLenPresent bool Data []byte } func parseDatagramFrame(r *bytes.Reader, _ protocol.VersionNumber) (*DatagramFrame, error) { typeByte, err := r.ReadByte() if err != nil
f := &DatagramFrame{} f.DataLenPresent = typeByte&0x1 > 0 var length uint64 if f.DataLenPresent { var err error len, err := quicvarint.Read(r) if err != nil { return nil, err } if len > uint64(r.Len()) { return nil, io.EOF } length = len } else { length = uint64(r.Len()) } f.Data = make([]byte, length) if _, err := io.ReadFull(r, f.Data); err != nil { return nil, err } return f, nil } func (f *DatagramFrame) Write(b *bytes.Buffer, _ protocol.VersionNumber) error { typeByte := uint8(0x30) if f.DataLenPresent { typeByte ^= 0x1 } b.WriteByte(typeByte) if f.DataLenPresent { quicvarint.Write(b, uint64(len(f.Data))) } b.Write(f.Data) return nil } // MaxDataLen returns the maximum data length func (f *DatagramFrame) MaxDataLen(maxSize protocol.ByteCount, version protocol.VersionNumber) protocol.ByteCount { headerLen := protocol.ByteCount(1) if f.DataLenPresent { // pretend that the data size will be 1 bytes // if it turns out that varint encoding the length will consume 2 bytes, we need to adjust the data length afterwards headerLen++ } if headerLen > maxSize { return 0 } maxDataLen := maxSize - headerLen if f.DataLenPresent && quicvarint.Len(uint64(maxDataLen)) != 1 { maxDataLen-- } return maxDataLen } // Length of a written frame func (f *DatagramFrame) Length(_ protocol.VersionNumber) protocol.ByteCount { length := 1 + protocol.ByteCount(len(f.Data)) if f.DataLenPresent { length += quicvarint.Len(uint64(len(f.Data))) } return length }
{ return nil, err }
events.ts
/*
* or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import { TypeOf } from '@kbn/config-schema'; import { RequestHandler, Logger } from 'kibana/server'; import { validateEvents } from '../../../../common/endpoint/schema/resolver'; import { Fetcher } from './utils/fetch'; import { EndpointAppContext } from '../../types'; export function handleEvents( log: Logger, endpointAppContext: EndpointAppContext ): RequestHandler<TypeOf<typeof validateEvents.params>, TypeOf<typeof validateEvents.query>> { return async (context, req, res) => { const { params: { id }, query: { events, afterEvent, legacyEndpointID: endpointID }, } = req; try { const indexRetriever = endpointAppContext.service.getIndexPatternRetriever(); const client = context.core.elasticsearch.legacy.client; const indexPattern = await indexRetriever.getEventIndexPattern(context); const fetcher = new Fetcher(client, id, indexPattern, endpointID); return res.ok({ body: await fetcher.events(events, afterEvent), }); } catch (err) { log.warn(err); return res.internalError({ body: err }); } }; }
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
setup.py
import setuptools import re with open("README.md", "r") as fh: long_description = fh.read() version = re.search( '^__version__\s*=\s*"(.*)"', open('mrtopo/__main__.py').read(), re.M ).group(1) setuptools.setup( name='mrtopo', version=version, packages=setuptools.find_packages(), url='https://github.com/FaizChishtie/mrtopo', license='MIT', author='faizchishtie', author_email='[email protected]', description='Mutate Mininet topology files with MrTopo', python_requires='>=3.0', entry_points={'console_scripts': ['mrtopo = mrtopo.cli:cli']}, long_description=long_description, long_description_content_type='text/markdown', install_requires=[ 'mininet', 'click' ], keywords='topology network startup', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.9', 'Topic :: Utilities', 'Typing :: Typed', ], )
'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8',
socket_dialers_test.go
package privval import ( "testing" "time" "github.com/YAOChain/yao/core/crypto/ed25519" cmn "github.com/YAOChain/yao/core/libs/common" "github.com/stretchr/testify/assert" ) func TestIsConnTimeoutForFundamentalTimeouts(t *testing.T) { // Generate a networking timeout dialer := DialTCPFn(testFreeTCPAddr(t), time.Millisecond, ed25519.GenPrivKey()) _, err := dialer() assert.Error(t, err) assert.True(t, IsConnTimeout(err)) } func TestIsConnTimeoutForWrappedConnTimeouts(t *testing.T)
{ dialer := DialTCPFn(testFreeTCPAddr(t), time.Millisecond, ed25519.GenPrivKey()) _, err := dialer() assert.Error(t, err) err = cmn.ErrorWrap(ErrConnTimeout, err.Error()) assert.True(t, IsConnTimeout(err)) }
navbar-brand.component.ts
import { ChangeDetectionStrategy, Component, OnInit, ViewEncapsulation } from '@angular/core';
@Component({ selector: 'bu-nav-brand', templateUrl: './navbar-brand.component.html', styleUrls: ['./navbar-brand.component.scss'], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class BulmaNavbarBrandComponent implements OnInit { constructor() {} ngOnInit() {} }
video.py
""" These are video related models. """ from dataclasses import dataclass, field from typing import Optional, List import isodate from isodate import ISO8601Error from pyyoutube.error import ErrorCode, ErrorMessage, PyYouTubeException from .base import BaseModel from .common import ( BaseApiResponse, BaseTopicDetails, BaseResource, Localized, Player, Thumbnails, ) from .mixins import DatetimeTimeMixin @dataclass class RegionRestriction(BaseModel): """ A class representing the video content details region restriction info Refer: https://google-developers.appspot.com/youtube/v3/docs/videos#contentDetails.regionRestriction """ allowed: List[str] = field(default=None) blocked: List[str] = field(default=None, repr=False) # TODO get detail rating description class ContentRating(BaseModel): """ A class representing the video content rating info. Refer: https://google-developers.appspot.com/youtube/v3/docs/videos#contentDetails.contentRating """ acbRating: Optional[str] = field(default=None, repr=False) agcomRating: Optional[str] = field(default=None, repr=False) anatelRating: Optional[str] = field(default=None, repr=False) bbfcRating: Optional[str] = field(default=None, repr=False) bfvcRating: Optional[str] = field(default=None, repr=False) bmukkRating: Optional[str] = field(default=None, repr=False) catvRating: Optional[str] = field(default=None, repr=False) catvfrRating: Optional[str] = field(default=None, repr=False) cbfcRating: Optional[str] = field(default=None, repr=False) cccRating: Optional[str] = field(default=None, repr=False) cceRating: Optional[str] = field(default=None, repr=False) chfilmRating: Optional[str] = field(default=None, repr=False) chvrsRating: Optional[str] = field(default=None, repr=False) cicfRating: Optional[str] = field(default=None, repr=False) cnaRating: Optional[str] = field(default=None, repr=False) cncRating: Optional[str] = field(default=None, repr=False) csaRating: Optional[str] = field(default=None, repr=False) cscfRating: Optional[str] = field(default=None, repr=False) czfilmRating: Optional[str] = field(default=None, repr=False) djctqRating: Optional[str] = field(default=None, repr=False) djctqRatingReasons: List[str] = field(default=None, repr=False) ecbmctRating: Optional[str] = field(default=None, repr=False) eefilmRating: Optional[str] = field(default=None, repr=False) egfilmRating: Optional[str] = field(default=None, repr=False) eirinRating: Optional[str] = field(default=None, repr=False) fcbmRating: Optional[str] = field(default=None, repr=False) fcoRating: Optional[str] = field(default=None, repr=False) fpbRating: Optional[str] = field(default=None, repr=False) fpbRatingReasons: List[str] = field(default=None, repr=False) fskRating: Optional[str] = field(default=None, repr=False) grfilmRating: Optional[str] = field(default=None, repr=False) icaaRating: Optional[str] = field(default=None, repr=False) ifcoRating: Optional[str] = field(default=None, repr=False) ilfilmRating: Optional[str] = field(default=None, repr=False) incaaRating: Optional[str] = field(default=None, repr=False) kfcbRating: Optional[str] = field(default=None, repr=False) kijkwijzerRating: Optional[str] = field(default=None, repr=False) kmrbRating: Optional[str] = field(default=None, repr=False) lsfRating: Optional[str] = field(default=None, repr=False) mccaaRating: Optional[str] = field(default=None, repr=False) mccypRating: Optional[str] = field(default=None, repr=False) mcstRating: Optional[str] = field(default=None, repr=False) mdaRating: Optional[str] = field(default=None, repr=False) medietilsynetRating: Optional[str] = field(default=None, repr=False) mekuRating: Optional[str] = field(default=None, repr=False) mibacRating: Optional[str] = field(default=None, repr=False) mocRating: Optional[str] = field(default=None, repr=False) moctwRating: Optional[str] = field(default=None, repr=False) mpaaRating: Optional[str] = field(default=None, repr=False) mpaatRating: Optional[str] = field(default=None, repr=False) mtrcbRating: Optional[str] = field(default=None, repr=False) nbcRating: Optional[str] = field(default=None, repr=False) nfrcRating: Optional[str] = field(default=None, repr=False) nfvcbRating: Optional[str] = field(default=None, repr=False) nkclvRating: Optional[str] = field(default=None, repr=False) oflcRating: Optional[str] = field(default=None, repr=False) pefilmRating: Optional[str] = field(default=None, repr=False) resorteviolenciaRating: Optional[str] = field(default=None, repr=False) rtcRating: Optional[str] = field(default=None, repr=False) rteRating: Optional[str] = field(default=None, repr=False) russiaRating: Optional[str] = field(default=None, repr=False) skfilmRating: Optional[str] = field(default=None, repr=False) smaisRating: Optional[str] = field(default=None, repr=False) smsaRating: Optional[str] = field(default=None, repr=False) tvpgRating: Optional[str] = field(default=None, repr=False) ytRating: Optional[str] = field(default=None) @dataclass class VideoContentDetails(BaseModel): """ A class representing the video content details info. Refer: https://developers.google.com/youtube/v3/docs/videos#contentDetails """ duration: Optional[str] = field(default=None) dimension: Optional[str] = field(default=None) definition: Optional[str] = field(default=None, repr=False) caption: Optional[str] = field(default=None, repr=False) licensedContent: Optional[bool] = field(default=None, repr=False) regionRestriction: Optional[RegionRestriction] = field(default=None, repr=False) contentRating: Optional[ContentRating] = field(default=None, repr=False) projection: Optional[str] = field(default=None, repr=False) hasCustomThumbnail: Optional[bool] = field(default=None, repr=False) def get_video_seconds_duration(self): if not self.duration: return None try: seconds = isodate.parse_duration(self.duration).total_seconds() except ISO8601Error as e: raise PyYouTubeException( ErrorMessage(status_code=ErrorCode.INVALID_PARAMS, message=e.args[0]) ) else: return int(seconds) @dataclass class VideoTopicDetails(BaseTopicDetails): """ A class representing video's topic detail info. Refer: https://developers.google.com/youtube/v3/docs/videos#topicDetails """ # Important: # This property has been deprecated as of November 10, 2016. # Any topics associated with a video are now returned by the topicDetails.relevantTopicIds[] property value. topicIds: Optional[List[str]] = field(default=None, repr=False) relevantTopicIds: Optional[List[str]] = field(default=None, repr=False) topicCategories: Optional[List[str]] = field(default=None)
If topicIds is not return and relevantTopicIds has return. let relevantTopicIds for topicIds. This is for the get_full_topics method. :return: """ if self.topicIds is None and self.relevantTopicIds is not None: self.topicIds = self.relevantTopicIds @dataclass class VideoSnippet(BaseModel, DatetimeTimeMixin): """ A class representing the video snippet info. Refer: https://developers.google.com/youtube/v3/docs/videos#snippet """ publishedAt: Optional[str] = field(default=None, repr=False) channelId: Optional[str] = field(default=None, repr=False) title: Optional[str] = field(default=None) description: Optional[str] = field(default=None) thumbnails: Optional[Thumbnails] = field(default=None, repr=False) channelTitle: Optional[str] = field(default=None, repr=False) tags: Optional[List[str]] = field(default=None, repr=False) categoryId: Optional[str] = field(default=None, repr=False) liveBroadcastContent: Optional[str] = field(default=None, repr=False) defaultLanguage: Optional[str] = field(default=None, repr=False) localized: Optional[Localized] = field(default=None, repr=False) defaultAudioLanguage: Optional[str] = field(default=None, repr=False) @dataclass class VideoStatistics(BaseModel): """ A class representing the video statistics info. Refer: https://developers.google.com/youtube/v3/docs/videos#statistics """ viewCount: Optional[int] = field(default=None) likeCount: Optional[int] = field(default=None) dislikeCount: Optional[int] = field(default=None, repr=False) commentCount: Optional[int] = field(default=None, repr=False) @dataclass class VideoStatus(BaseModel, DatetimeTimeMixin): """ A class representing the video status info. Refer: https://developers.google.com/youtube/v3/docs/videos#status """ uploadStatus: Optional[str] = field(default=None) failureReason: Optional[str] = field(default=None, repr=False) rejectionReason: Optional[str] = field(default=None, repr=False) privacyStatus: Optional[str] = field(default=None) publishAt: Optional[str] = field(default=None, repr=False) license: Optional[str] = field(default=None, repr=False) embeddable: Optional[bool] = field(default=None, repr=False) publicStatsViewable: Optional[bool] = field(default=None, repr=False) madeForKids: Optional[bool] = field(default=None, repr=False) selfDeclaredMadeForKids: Optional[bool] = field(default=None, repr=False) @dataclass class Video(BaseResource): """ A class representing the video info. Refer: https://developers.google.com/youtube/v3/docs/videos """ snippet: Optional[VideoSnippet] = field(default=None, repr=False) contentDetails: Optional[VideoContentDetails] = field(default=None, repr=False) status: Optional[VideoStatus] = field(default=None, repr=False) statistics: Optional[VideoStatistics] = field(default=None, repr=False) topicDetails: Optional[VideoTopicDetails] = field(default=None, repr=False) player: Optional[Player] = field(default=None, repr=False) @dataclass class VideoListResponse(BaseApiResponse): """ A class representing the video's retrieve response info. Refer: https://developers.google.com/youtube/v3/docs/videos/list#response_1 """ items: Optional[List[Video]] = field(default=None, repr=False)
def __post_init__(self): """
component.js
import {BaseComponent, html} from "../../scripts/components.js"; class
extends BaseComponent { constructor(parent, events) { super(events); this.render(parent); } render(parent) { this.el = parent.appendChild(html('header', null, [ html('input', {type: 'search', placeholder: 'Search...', $input: (e) => this.event(e, 'onSearch', e.target.value)}), html('a', {href: '#', class: 'btn', text: 'Add Note', $click: (e) => this.event(e, 'onAdd')}) ])); } } export {HeaderComponent};
HeaderComponent