text:
'use strict';

import gulp        from 'gulp';
import runSequence from 'run-sequence';

gulp.task('prod', ['clean'], function(cb = function() {}) {

  global.isProd = true;

  runSequence(['styles', 'images', 'fonts', 'views', 'browserify'], 'gzip', cb);

});


text:
.list-container__row {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
  padding: 0;
  border-bottom: solid 1px black;
}
/*.list-container__row:hover {
  background-color: rgba(100, 100, 100, 0.2);
}*/

redpajama_set_name: RedPajamaGithub


text:
package org.isisaddons.app.kitchensink.dom.hierarchy.child;

import java.util.Collection;
import com.google.common.base.Predicate;

public final class PredicateUtil {
    private PredicateUtil(){}
    public static <T> Predicate<T> containedIn(final Collection<T> children) {
        return new Predicate<T>() {
            @Override
            public boolean apply(T input) {
                return children.contains(input);
            }
        };
    }
}


text:
package main

import (
  "context"
  "crypto/x509"
  "encoding/base64"
  "flag"
  "io/ioutil"
  "k8s.io/client-go/rest"
  "path/filepath"
  "sync"
  "time"

  "fmt"
  "github.com/hashicorp/vault/api"

  //"io/ioutil"
  log "github.com/sirupsen/logrus"
  "os"

  corev1 "k8s.io/api/core/v1"
  metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  "k8s.io/client-go/kubernetes"
  "k8s.io/client-go/tools/clientcmd"

  //"time"
)

func mustGetenv(k string) string {
  v := os.Getenv(k)
  if v == "" {
    panic(fmt.Sprintf("%s undefined", k))
  }
  return v
}

// loadCert loads a single pem-encoded certificate into the given pool.
func loadCert(pool *x509.CertPool, pem []byte) error {
  if ok := pool.AppendCertsFromPEM(pem); !ok {
    return fmt.Errorf("failed to parse PEM")
  }
  return nil
}

func rootCAs(vaultCaPem string) (*x509.CertPool, error) {
  //switch {
  //case vaultCaPem != "":
  pool := x509.NewCertPool()
  if err := loadCert(pool, []byte(vaultCaPem)); err != nil {
    return nil, err
  }
  return pool, nil
  //case vaultCaCert != "":
  //  pool := x509.NewCertPool()
  //  if err := loadCertFile(pool, vaultCaCert); err != nil {
  //    return nil, err
  //  }
  //  return pool, nil
  //case vaultCaPath != "":
  //  pool := x509.NewCertPool()
  //  if err := loadCertFolder(pool, vaultCaPath); err != nil {
  //    return nil, err
  //  }
  //  return pool, nil
  //default:
  //  pool, err := x509.SystemCertPool()
  //  if err != nil {
  //    return nil, errors.Wrap(err, "failed to load system certs")
  //  }
  //  return pool, err
  //}
}

// svcAcctJWT looks up the stored JWT secret token for a given service account
func svcAcctJWT(ctx context.Context, name, namespace string) (string, error) {
  log.Info("common:svcAcctJWT")

  var (
    err error

    secret     = &corev1.Secret{}
    svcAccount = &corev1.ServiceAccount{}
  )

  log.Info("common:svcAcctJWT:secret", "name", name, "namespace", namespace)

  config, err := clientcmd.BuildConfigFromFlags("", "")
  if err != nil {
    panic(err)
  }
  clientset, err := kubernetes.NewForConfig(config)
  if err != nil {
    panic(err)
  }

  // get service account
  sa, err := clientset.CoreV1().ServiceAccounts(namespace).Get(name, metav1.GetOptions{})
  if err != nil {
    log.Error(err, "get ServiceAccount")
    return "", fmt.Errorf("%s serviceAccount not found in %s namespace", name, namespace)
  }

  if len(sa.Secrets) == 0 {
    return "", fmt.Errorf("%s serviceAccount token not found", name)
  }

  log.Info("common:svcAcctJWT:secret:value", "name", name, "namespace", namespace)

  ref := svcAccount.Secrets[0]

  // get service account token secret
  secret, err = clientset.CoreV1().Secrets(namespace).Get(ref.Name, metav1.GetOptions{})
  if err != nil {
    return "", fmt.Errorf("%s serviceAccount token not found: %s", name, err)
  }

  b := string(secret.Data["token"])
  //b, err := base64.StdEncoding.DecodeString(string(secret.Data["token"]))
  //if err != nil {
  //	return "", err
  //}

  return string(b), nil
}

//// getApplicationsSecrets looks up the stored JWT secret token for a given service account
//func getApplicationsSecrets(ctx context.Context, name string, namespace string) (*map[string]string, error) {
//  log.Info("common:getApplicationsSecrets")
//
//  var (
//    appSecretInfo = map[string]string{}
//  )
//
//  log.Info("common:getApplicationsSecrets:secret:", "name-", name, "-namespace-", namespace)
//
//  config, err := rest.InClusterConfig()
//  if err != nil {
//    panic(err.Error())
//  }
//
//  clientset, err := kubernetes.NewForConfig(config)
//  if err != nil {
//    panic(err)
//  }
//
//  // get service account
//  secret, err := clientset.CoreV1().Secrets(namespace).Get(name, metav1.GetOptions{})
//  if err != nil {
//    return &appSecretInfo, fmt.Errorf("%s serviceAccount token not found: %s", name, err)
//  }
//
//  for k, v := range secret.StringData {
//    appSecretInfo[k] = v
//  }
//
//  resAsJSON, _ := json.Marshal(appSecretInfo)
//  log.Println("common:getApplicationsSecrets:JSON:", string(resAsJSON))
//  return &appSecretInfo, nil
//}

//func authenticate(role string, jwt string, vaultCaPem string, vaultAddr string, vaultK8SMountPath string) (string, string, error) {
//  // Setup the TLS (especially required for custom CAs)
//
//
//  log.WithFields(log.Fields{
//    "role": role,
//    "vaultAddr": vaultAddr,
//    "vaultK8SMountPath": vaultK8SMountPath,
//  }).Info("authenticate:start")
//
//
//
//  rootCAs, err := rootCAs(vaultCaPem)
//  if err != nil {
//    return "", "", err
//  }
//
//  tlsClientConfig := &tls.Config{
//    MinVersion: tls.VersionTLS12,
//    RootCAs:    rootCAs,
//  }
//
//  //if vaultSkipVerify {
//  //  tlsClientConfig.InsecureSkipVerify = true
//  //}
//
//  //if vaultServerName != "" {
//  //  tlsClientConfig.ServerName = vaultServerName
//  //}
//
//  transport := &http.Transport{
//    TLSClientConfig: tlsClientConfig,
//  }
//
//  if err := http2.ConfigureTransport(transport); err != nil {
//    return "", "", errors.New("failed to configure http2")
//  }
//
//  client := &http.Client{
//    Transport: transport,
//  }
//
//  transport.Proxy = http.ProxyFromEnvironment
//
//  addr := vaultAddr + "/v1/auth/" + vaultK8SMountPath + "/login"
//  body := fmt.Sprintf(`{"role": "%s", "jwt": "%s"}`, role, jwt)
//
//  req, err := http.NewRequest(http.MethodPost, addr, strings.NewReader(body))
//  req.Header.Set("Content-Type", "application/json")
//  if err != nil {
//    return "", "", errors.Wrap(err, "failed to create request")
//  }
//
//  resp, err := client.Do(req)
//  if err != nil {
//    return "", "", errors.Wrap(err, "failed to login")
//  }
//  defer resp.Body.Close()
//
//  if resp.StatusCode != 200 {
//    var b bytes.Buffer
//    io.Copy(&b, resp.Body)
//    return "", "", fmt.Errorf("failed to get successful response: %#v, %s",
//      resp, b.String())
//  }
//
//  var s struct {
//    Auth struct {
//      ClientToken    string `json:"client_token"`
//      ClientAccessor string `json:"accessor"`
//    } `json:"auth"`
//  }
//
//  if err := json.NewDecoder(resp.Body).Decode(&s); err != nil {
//    return "", "", errors.Wrap(err, "failed to read body")
//  }
//
//  return s.Auth.ClientToken, s.Auth.ClientAccessor, nil
//}

func getGCPKey(c *api.Client, keyRolesetPath string) (string, error) {
  res, err := c.Logical().Read(keyRolesetPath)
  if err != nil {
    return "", err
  }

  b, err := base64.StdEncoding.DecodeString(res.Data["private_key_data"].(string))
  if err != nil {
    return "", err
  }
  return string(b), nil
}

func updateGCPKey(credentialPath string, key string) (error) {
  log.WithFields(log.Fields{
    "path": credentialPath,
    "dir":  filepath.Dir(credentialPath),
  })
  err := os.MkdirAll(filepath.Dir(credentialPath), os.ModePerm)
  if err != nil {
    return err
  }
  err = ioutil.WriteFile(credentialPath, []byte(key), 0644)
  if err != nil {
    return err
  }
  return nil
}

const (
  version = "0.1"
)

func checkForWork(k8sConfig *rest.Config) {
  log.Printf("vault-init-gcp v%s starting watcher", version)

  log.Printf("Starting check")
  getSecrets()
  log.Printf("Ending checkg")
}

var ticker *time.Ticker
var config *rest.Config

func watch(k8sConfig *rest.Config) {
  quit := make(chan struct{})
  for {
    select {
    case <-ticker.C:
      fmt.Println("check")
      checkForWork(k8sConfig)
    case <-quit:
      ticker.Stop()
      return
    }
  }
}

type Server struct {
  serveWG       sync.WaitGroup
  SecretsConfig struct {
    vaultAddr         string
    vaultCAPath       string
    gcpRolesetKeyPath string
    k8sTokenPath      string
    k8sPath           string
    k8sRole           string
    credentialPath    string
    k8sNamespace      string
  }
}

var server Server

func Start(k8sConfig *rest.Config) {
  config = k8sConfig

  go watch(k8sConfig)

}

//var TODO_FIND_KUBECONFIG = "/Users/joseret/g/pso/anthos/anthos-pso-app-crd-cm/.private/t2-stg/t2-stg-03-kc"
func monitor() {
  server.serveWG.Add(1)
  config, err := rest.InClusterConfig()
  //config, err := clientcmd.BuildConfigFromFlags("",TODO_FIND_KUBECONFIG)
  if err != nil {
    log.Fatalf("Cluster Config Error - %v", err)
  }
  Start(config)
  server.serveWG.Wait()

}

func getSecrets() {

  log.Infoln("read jwt-ns", server.SecretsConfig.k8sNamespace)

  k8sJWT, err := ioutil.ReadFile(server.SecretsConfig.k8sTokenPath)
  if err != nil {
    panic(err)
  }

  log.Infoln("client")
  client, err := api.NewClient(&api.Config{
    Address: server.SecretsConfig.vaultAddr,
  })
  if err != nil {
    panic(err)
  }

  //Auth with K8s vault
  vaultK8sInfo := map[string]interface{}{"jwt": string(k8sJWT), "role": server.SecretsConfig.k8sRole}
  secret, err := client.Logical().Write(fmt.Sprintf("auth/%s/login",
    server.SecretsConfig.k8sPath), vaultK8sInfo)
  if err != nil {
    panic(err)
  }

  client.SetToken(string(secret.Auth.ClientToken))

  log.Infoln("getGCPKey")

  data, err := getGCPKey(client, server.SecretsConfig.gcpRolesetKeyPath)
  if err != nil {
    panic(err)
  }

  err = updateGCPKey(server.SecretsConfig.credentialPath, data)
  if err != nil {
    panic(err)
  }
}

func main() {
  initMode := flag.String("mode", "GCP-KSA", "a string")
  ttlCheckInterval := flag.String("duration", "5m", "ttl checks")
  flag.Parse()

  server.SecretsConfig.vaultAddr = mustGetenv("VAULT_ADDR")
  server.SecretsConfig.vaultCAPath = mustGetenv("VAULT_CAPATH")
  server.SecretsConfig.gcpRolesetKeyPath = mustGetenv("INIT_GCP_KEYPATH")
  server.SecretsConfig.k8sTokenPath = mustGetenv("INIT_K8S_TOKEN_KEYPATH")
  server.SecretsConfig.k8sPath = mustGetenv("INIT_K8S_KEYPATH")
  server.SecretsConfig.k8sRole = mustGetenv("INIT_K8S_ROLE")
  server.SecretsConfig.credentialPath = mustGetenv("GOOGLE_APPLICATION_CREDENTIALS")
  server.SecretsConfig.k8sNamespace = mustGetenv("MY_POD_NAMESPACE")

  log.WithFields(log.Fields{
    "initMode": *initMode,
  }).Info("main:start")

  log.WithFields(log.Fields{
    "vaultAddr":   server.SecretsConfig.vaultAddr,
    "vaultCAPath": server.SecretsConfig.vaultCAPath,
  }).Info("main:Parms")

  if *initMode == "GCP-RECYCLE" {
    dur, _ := time.ParseDuration(*ttlCheckInterval)
    ticker = time.NewTicker(dur)
    monitor()
    os.Exit(0)

  }

  getSecrets()

}


text:
if [ -z "$1" ]; then
  exit 1
fi
aws iam list-ssh-public-keys --user-name "$1" --query "SSHPublicKeys[?Status == 'Active'].[SSHPublicKeyId]" --output text | while read KeyId; do
  aws iam get-ssh-public-key --user-name "$1" --ssh-public-key-id "$KeyId" --encoding SSH --query "SSHPublicKey.SSHPublicKeyBody" --output text
done


text:
package controllers

import org.specs2.execute.AsResult
import org.specs2.execute.Result
import org.specs2.mutable.Specification

import controllers.SessionForm.EMAIL
import controllers.SessionForm.PASSWORD
import controllers.SessionForm.URI
import controllers.common.FlashName.Error
import controllers.common.FlashName.Logout
import controllers.common.FlashName.Success
import controllers.common.FlashName.Unauthorized
import controllers.common.FlashName.Uri
import models.Member
import play.api.db._
import play.api.test._
import play.api.test.Helpers._

class SessionControllerSpec extends Specification {

  abstract class TestApp extends WithApplication {
    override def around[T: AsResult](t: => T): Result = super.around {
      DB.withTransaction { implicit c =>
        for {
          i <- 1 to 10
          email = "name" + i + "@domain" + i
          nickname = "ニックネーム" + i
          id <- Member.create(Member(email, nickname, None))
        } Member.updatePw(id, "password")
      }
      t
    }
  }

  "SessionController#index" should {

    "ログイン画面が表示される。" in new TestApp {
      route(FakeRequest(GET, "/login")) must beSome.which { res =>
        status(res) must equalTo(OK)
        contentType(res) must beSome.which(_ == "text/html")
        val content = contentAsString(res)
        content must contain("""メールアドレス""")
        content must contain("""パスワード""")
        content must not contain ("ログアウトしました。")
        content must not contain ("ログインし直してください。")
        content must not contain ("""<input type="hidden" name="uri" value="/profile" />""")
      }
    }

    "ログアウトから転送されて、ログイン画面が表示される。" in new TestApp {
      route(FakeRequest(GET, "/login").withFlash(Success -> Logout)) must beSome.which { res =>
        status(res) must equalTo(OK)
        contentType(res) must beSome.which(_ == "text/html")
        val content = contentAsString(res)
        content must contain("""メールアドレス""")
        content must contain("""パスワード""")
        content must contain("ログアウトしました。")
        content must not contain ("ログインし直してください。")
        content must not contain ("""<input type="hidden" name="uri" value="/profile" />""")
      }
    }

    "セッション切れから転送されて、ログイン画面が表示される。" in new TestApp {
      route(FakeRequest(GET, "/login").withFlash(Error -> Unauthorized)) must beSome.which { res =>
        status(res) must equalTo(OK)
        contentType(res) must beSome.which(_ == "text/html")
        val content = contentAsString(res)
        content must contain("""メールアドレス""")
        content must contain("""パスワード""")
        content must not contain ("ログアウトしました。")
        content must contain("ログインし直してください。")
        content must not contain ("""<input type="hidden" name="uri" value="/profile" />""")
      }
    }

    "ログイン後転送先の指定ありで、ログイン画面が表示される。" in new TestApp {
      route(FakeRequest(GET, "/login").withFlash(Uri -> "/profile")) must beSome.which { res =>
        status(res) must equalTo(OK)
        contentType(res) must beSome.which(_ == "text/html")
        val content = contentAsString(res)
        content must contain("""メールアドレス""")
        content must contain("""パスワード""")
        content must not contain ("ログアウトしました。")
        content must not contain ("ログインし直してください。")
        content must contain("""<input type="hidden" name="uri" value="/profile" />""")
      }
    }
  }

  "SessionController#login" should {

    "ログインできる。ホームに転送される。" in new TestApp {
      route(FakeRequest(POST, "/login").withFormUrlEncodedBody(
        EMAIL -> "name1@domain1", PASSWORD -> "password")) must beSome.which { res =>
        status(res) must equalTo(SEE_OTHER)
        header(LOCATION, res) must beSome.which(_ == "/")
        contentType(res) must beNone
        contentAsString(res) must beEmpty
      }
    }

    "ログインできる。指定されたログイン後転送先に転送される。" in new TestApp {
      route(FakeRequest(POST, "/login").withFormUrlEncodedBody(
        EMAIL -> "name1@domain1", PASSWORD -> "password", URI -> "/profile")) must beSome.which { res =>
        status(res) must equalTo(SEE_OTHER)
        header(LOCATION, res) must beSome.which(_ == "/profile")
        contentType(res) must beNone
        contentAsString(res) must beEmpty
      }
    }

    "メールアドレス入力不正 (必須違反) でNG。" in new TestApp {
      route(FakeRequest(POST, "/login").withFormUrlEncodedBody(
        EMAIL -> "", PASSWORD -> "password")) must beSome.which { res =>
        status(res) must equalTo(OK)
        header(LOCATION, res) must beNone
        contentType(res) must beSome.which(_ == "text/html")
        val content = contentAsString(res)
        content must contain("値が不適切です。入力し直してください。")
        content must not contain ("メールアドレスまたはパスワードが異なっています。")
        content must contain("""メールアドレス""")
        content must contain("""パスワード""")
      }
    }

    "パスワード入力不正 (必須違反) でNG。" in new TestApp {
      route(FakeRequest(POST, "/login").withFormUrlEncodedBody(
        EMAIL -> "name1@domain1", PASSWORD -> "")) must beSome.which { res =>
        status(res) must equalTo(OK)
        header(LOCATION, res) must beNone
        contentType(res) must beSome.which(_ == "text/html")
        val content = contentAsString(res)
        content must contain("値が不適切です。入力し直してください。")
        content must not contain ("メールアドレスまたはパスワードが異なっています。")
        content must contain("""メールアドレス""")
        content must contain("""パスワード""")
      }
    }

    "メールアドレス/パスワード不適合でNG。" in new TestApp {
      route(FakeRequest(POST, "/login").withFormUrlEncodedBody(
        EMAIL -> "name1@domain1", PASSWORD -> "NOMATCH")) must beSome.which { res =>
        status(res) must equalTo(OK)
        header(LOCATION, res) must beNone
        contentType(res) must beSome.which(_ == "text/html")
        val content = contentAsString(res)
        content must not contain ("値が不適切です。入力し直してください。")
        content must contain("メールアドレスまたはパスワードが異なっています。")
        content must contain("""メールアドレス""")
        content must contain("""パスワード""")
      }
    }
  }

  "SessionController#logout" should {
    "ログアウトする。" in new TestApp {
      route(FakeRequest(GET, "/logout")) must beSome.which { res =>
        status(res) must equalTo(SEE_OTHER)
        header(LOCATION, res) must beSome.which(_ == "/login")
        contentType(res) must beEmpty
        flash(res).get(Success) must beSome.which(_ == Logout)
      }
    }
  }
}


text:
using System;
using System.Collections.Generic;

namespace Humanizer.Localisation.NumberToWords
{
    internal class NorwegianBokmalNumberToWordsConverter : GenderedNumberToWordsConverter
    {
        private static readonly string[] UnitsMap = { "null", "en", "to", "tre", "fire", "fem", "seks", "sju", "åtte", "ni", "ti", "elleve", "tolv", "tretten", "fjorten", "femten", "seksten", "sytten", "atten", "nitten" };
        private static readonly string[] TensMap = { "null", "ti", "tjue", "tretti", "førti", "femti", "seksti", "sytti", "åtti", "nitti" };

        private static readonly Dictionary<int, string> OrdinalExceptions = new Dictionary<int, string>
        {
            {0, "nullte"},
            {1, "første"},
            {2, "andre"},
            {3, "tredje"},
            {4, "fjerde"},
            {5, "femte"},
            {6, "sjette"},
            {11, "ellevte"},
            {12, "tolvte"}
        };

        public override string Convert(int number, GrammaticalGender gender)
        {
            return Convert(number, false, gender);
        }

        public override string ConvertToOrdinal(int number, GrammaticalGender gender)
        {
            return Convert(number, true, gender);
        }

        private string Convert(int number, bool isOrdinal, GrammaticalGender gender)
        {
            if (number == 0)
                return GetUnitValue(0, isOrdinal);

            if (number < 0)
                return string.Format("minus {0}", Convert(-number, isOrdinal, gender));

            if (number == 1)
            {
                switch (gender)
                {
                    case GrammaticalGender.Feminine:
                        return "ei";
                    case GrammaticalGender.Neuter:
                        return "et";
                }
            }

            var parts = new List<string>();

            var millionOrMore = false;

            const int billion = 1000000000;
            if ((number / billion) > 0)
            {
                millionOrMore = true;
                var isExactOrdinal = isOrdinal && number % billion == 0;
                parts.Add(Part("{0} milliard" + (isExactOrdinal ? "" : "er"), (isExactOrdinal ? "" : "en ") + "milliard", number / billion, !isExactOrdinal));
                number %= billion;
            }

            const int million = 1000000;
            if ((number / million) > 0)
            {
                millionOrMore = true;
                var isExactOrdinal = isOrdinal && number % million == 0;
                parts.Add(Part("{0} million" + (isExactOrdinal ? "" : "er"), (isExactOrdinal ? "" : "en ") + "million", number / million, !isExactOrdinal));
                number %= million;
            }

            var thousand = false;
            if ((number / 1000) > 0)
            {
                thousand = true;
                parts.Add(Part("{0}tusen", number % 1000 < 100 ? "tusen" : "ettusen", number / 1000));
                number %= 1000;
            }

            var hundred = false;
            if ((number / 100) > 0)
            {
                hundred = true;
                parts.Add(Part("{0}hundre", thousand || millionOrMore ? "ethundre" : "hundre", number / 100));
                number %= 100;
            }

            if (number > 0)
            {
                if (parts.Count != 0)
                    if (millionOrMore && !hundred && !thousand)
                        parts.Add("og ");
                    else
                        parts.Add("og");

                if (number < 20)
                    parts.Add(GetUnitValue(number, isOrdinal));
                else
                {
                    var lastPart = TensMap[number / 10];
                    if ((number % 10) > 0)
                        lastPart += string.Format("{0}", GetUnitValue(number % 10, isOrdinal));
                    else if (isOrdinal)
                        lastPart = lastPart.TrimEnd('e') + "ende";

                    parts.Add(lastPart);
                }
            }
            else if (isOrdinal)
                parts[parts.Count - 1] += (number == 0 ? "" : "en") + (millionOrMore ? "te" : "de");

            var toWords = string.Join("", parts.ToArray()).Trim();

            return toWords;
        }

        private static string GetUnitValue(int number, bool isOrdinal)
        {
            if (isOrdinal)
            {
                string exceptionString;
                if (ExceptionNumbersToWords(number, out exceptionString))
                    return exceptionString;
                else if (number < 13)
                    return UnitsMap[number].TrimEnd('e') + "ende";
                else
                    return UnitsMap[number] + "de";
            }
            else
                return UnitsMap[number];
        }

        private static bool ExceptionNumbersToWords(int number, out string words)
        {
            return OrdinalExceptions.TryGetValue(number, out words);
        }

        private string Part(string pluralFormat, string singular, int number, bool postfixSpace = false)
        {
            var postfix = postfixSpace ? " " : "";
            if (number == 1)
                return singular + postfix;
            return string.Format(pluralFormat, Convert(number)) + postfix;
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.connector.thrift.util;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import io.airlift.log.Logger;
import io.airlift.stats.CounterStat;
import io.airlift.stats.DistributionStat;
import io.airlift.stats.TimeDistribution;
import io.airlift.units.Duration;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;

import javax.annotation.Nullable;

import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.function.Predicate;

import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;

public class RetryDriver
{
    private static final Logger log = Logger.get(RetryDriver.class);
    private static final int DEFAULT_RETRY_ATTEMPTS = 10;
    private static final Duration DEFAULT_SLEEP_TIME = Duration.valueOf("1s");
    private static final Duration DEFAULT_MAX_RETRY_TIME = Duration.valueOf("30s");
    private static final double DEFAULT_SCALE_FACTOR = 2.0;

    private final int maxAttempts;
    private final Duration minSleepTime;
    private final Duration maxSleepTime;
    private final double scaleFactor;
    private final Duration maxRetryTime;
    private final Optional<Runnable> retryRunnable;
    private final Predicate<Exception> stopRetrying;
    private final Function<Exception, Exception> classifier;
    private final ListeningScheduledExecutorService retryExecutorService;

    private RetryDriver(
            int maxAttempts,
            Duration minSleepTime,
            Duration maxSleepTime,
            double scaleFactor,
            Duration maxRetryTime,
            Optional<Runnable> retryRunnable,
            Predicate<Exception> stopRetrying,
            Function<Exception, Exception> classifier,
            ListeningScheduledExecutorService retryExecutorService)
    {
        this.maxAttempts = maxAttempts;
        this.minSleepTime = minSleepTime;
        this.maxSleepTime = maxSleepTime;
        this.scaleFactor = scaleFactor;
        this.maxRetryTime = maxRetryTime;
        this.retryRunnable = retryRunnable;
        this.stopRetrying = stopRetrying;
        this.classifier = classifier;
        this.retryExecutorService = retryExecutorService;
    }

    private RetryDriver(ListeningScheduledExecutorService executor)
    {
        this(DEFAULT_RETRY_ATTEMPTS,
                DEFAULT_SLEEP_TIME,
                DEFAULT_SLEEP_TIME,
                DEFAULT_SCALE_FACTOR,
                DEFAULT_MAX_RETRY_TIME,
                Optional.empty(),
                e -> false,
                Function.identity(),
                executor);
    }

    public static RetryDriver retry(ListeningScheduledExecutorService executor)
    {
        return new RetryDriver(executor);
    }

    public final RetryDriver maxAttempts(int maxAttempts)
    {
        return new RetryDriver(maxAttempts, minSleepTime, maxSleepTime, scaleFactor, maxRetryTime, retryRunnable, stopRetrying, classifier, retryExecutorService);
    }

    public final RetryDriver exponentialBackoff(Duration minSleepTime, Duration maxSleepTime, Duration maxRetryTime, double scaleFactor)
    {
        return new RetryDriver(maxAttempts, minSleepTime, maxSleepTime, scaleFactor, maxRetryTime, retryRunnable, stopRetrying, classifier, retryExecutorService);
    }

    public final RetryDriver onRetry(Runnable retryRunnable)
    {
        return new RetryDriver(maxAttempts, minSleepTime, maxSleepTime, scaleFactor, maxRetryTime, Optional.ofNullable(retryRunnable), stopRetrying, classifier, retryExecutorService);
    }

    public RetryDriver stopRetryingWhen(Predicate<Exception> stopRetrying)
    {
        return new RetryDriver(maxAttempts, minSleepTime, maxSleepTime, scaleFactor, maxRetryTime, retryRunnable, stopRetrying, classifier, retryExecutorService);
    }

    public RetryDriver withClassifier(Function<Exception, Exception> classifier)
    {
        return new RetryDriver(maxAttempts, minSleepTime, maxSleepTime, scaleFactor, maxRetryTime, retryRunnable, stopRetrying, classifier, retryExecutorService);
    }

    /**
     * This is only for sync calls. For Callable that returns Future object, use runAsync instead.
     */
    public <V> V run(String callableName, RetryStats stats, Callable<V> callable)
    {
        requireNonNull(callableName, "callableName is null");
        requireNonNull(callable, "callable is null");
        RetryStatus retryStatus = new RetryStatus();

        while (true) {
            retryStatus.nextAttempt();
            try {
                V result = callable.call();
                stats.addSuccess();
                stats.addAttemptsBeforeSuccess(retryStatus.getAttempts());
                stats.addSuccessLatency(retryStatus.getDuration());
                return result;
            }
            catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                recordFailure(retryStatus, stats);
                throw propagate(ie);
            }
            catch (Exception e) {
                if (retryStatus.shouldStopRetry(e)) {
                    recordFailure(retryStatus, stats);
                    throw propagate(e);
                }

                log.warn(e, "Failed on executing %s with attempt %d, will retry.", callableName, retryStatus.getAttempts());
                try {
                    MILLISECONDS.sleep(retryStatus.getRetryDelayInMs());
                }
                catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    recordFailure(retryStatus, stats);
                    throw propagate(ie);
                }
            }
        }
    }

    public <V> ListenableFuture<V> runAsync(String callableName, RetryStats stats, Callable<ListenableFuture<V>> callable)
    {
        requireNonNull(callableName, "callableName is null");
        requireNonNull(callable, "callable is null");
        return runAsyncInternal(callableName, stats, callable, new RetryStatus());
    }

    private <V> ListenableFuture<V> runAsyncInternal(String callableName, RetryStats stats, Callable<ListenableFuture<V>> callable, RetryStatus retryStatus)
    {
        retryStatus.nextAttempt();
        ListenableFuture<V> resultFuture;
        try {
            resultFuture = callable.call();
            Futures.addCallback(resultFuture, new FutureCallback<V>()
            {
                @Override
                public void onSuccess(@Nullable V result)
                {
                    stats.addSuccess();
                    stats.addAttemptsBeforeSuccess(retryStatus.getAttempts());
                    stats.addSuccessLatency(retryStatus.getDuration());
                }

                @Override
                public void onFailure(Throwable t) {}
            });
        }
        catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            recordFailure(retryStatus, stats);
            throw propagate(ie);
        }
        catch (Exception e) {
            resultFuture = immediateFailedFuture(e);
        }

        return Futures.catchingAsync(resultFuture, Exception.class, e -> {
            if (e instanceof InterruptedException) {
                Thread.currentThread().interrupt();
                recordFailure(retryStatus, stats);
                throw propagate(e);
            }
            else if (retryStatus.shouldStopRetry(e)) {
                recordFailure(retryStatus, stats);
                throw propagate(e);
            }
            log.warn(e, "Failed on executing %s with attempt %d, will perform async retry.", callableName, retryStatus.getAttempts());
            return Futures.dereference(retryExecutorService.schedule(() -> runAsyncInternal(callableName, stats, callable, retryStatus), retryStatus.getRetryDelayInMs(), MILLISECONDS));
        });
    }

    private RuntimeException propagate(Exception e)
    {
        Exception classified = classifier.apply(e);
        throwIfUnchecked(classified);
        throw new RuntimeException(classified);
    }

    private void recordFailure(RetryStatus retryStatus, RetryStats stats)
    {
        stats.addFinalFailure();
        stats.addAttemptsBeforeFailure(retryStatus.getAttempts());
        stats.addFailureLatency(retryStatus.getDuration());
    }

    private final class RetryStatus
    {
        private final long startTime;
        private final AtomicInteger attempts;

        RetryStatus()
        {
            this.startTime = System.nanoTime();
            this.attempts = new AtomicInteger(0);
        }

        long getRetryDelayInMs()
        {
            int delayInMs = (int) Math.min(minSleepTime.toMillis() * Math.pow(scaleFactor, attempts.get() - 1), maxSleepTime.toMillis());
            int jitter = ThreadLocalRandom.current().nextInt(Math.max(1, (int) (delayInMs * 0.1)));
            return delayInMs + jitter;
        }

        Duration getDuration()
        {
            return Duration.nanosSince(startTime);
        }

        boolean shouldStopRetry(Exception e)
        {
            return stopRetrying.test(e) || attempts.get() >= maxAttempts || Duration.nanosSince(startTime).compareTo(maxRetryTime) >= 0;
        }

        int getAttempts()
        {
            return attempts.get();
        }

        void nextAttempt()
        {
            if (attempts.incrementAndGet() > 1) {
                retryRunnable.ifPresent(Runnable::run);
            }
        }
    }

    public static final class RetryStats
    {
        private final CounterStat success = new CounterStat();
        private final CounterStat finalFailure = new CounterStat();
        private final DistributionStat attemptsBeforeFailure = new DistributionStat();
        private final TimeDistribution failureLatency = new TimeDistribution(MICROSECONDS);
        private final DistributionStat attemptsBeforeSuccess = new DistributionStat();
        private final TimeDistribution successLatency = new TimeDistribution(MICROSECONDS);

        @Managed
        @Nested
        public CounterStat getSuccess()
        {
            return success;
        }

        @Managed
        @Nested
        public DistributionStat getAttemptsBeforeSuccess()
        {
            return attemptsBeforeSuccess;
        }

        @Managed
        @Nested
        public TimeDistribution getSuccessLatency()
        {
            return successLatency;
        }

        @Managed
        @Nested
        public CounterStat getFinalFailure()
        {
            return finalFailure;
        }

        @Managed
        @Nested
        public DistributionStat getAttemptsBeforeFailure()
        {
            return attemptsBeforeFailure;
        }

        @Managed
        @Nested
        public TimeDistribution getFailureLatency()

        {
            return failureLatency;
        }

        public void addSuccess()
        {
            success.update(1);
        }

        public void addAttemptsBeforeSuccess(int count)
        {
            attemptsBeforeSuccess.add(count);
        }

        public void addSuccessLatency(Duration duration)
        {
            successLatency.add(duration.roundTo(NANOSECONDS));
        }

        public void addFinalFailure()
        {
            finalFailure.update(1);
        }

        public void addAttemptsBeforeFailure(int count)
        {
            attemptsBeforeFailure.add(count);
        }

        public void addFailureLatency(Duration duration)
        {
            failureLatency.add(duration.roundTo(NANOSECONDS));
        }
    }
}


text:
PDSA: Probabilistic Data Structures and Algorithms in Python
************************************************************

.. image:: https://img.shields.io/travis/gakhov/pdsa/master.svg?style=flat-square
    :target: https://travis-ci.org/gakhov/pdsa
    :alt: Travis Build Status

.. image:: https://img.shields.io/github/release/gakhov/pdsa/all.svg?style=flat-square
    :target: https://github.com/gakhov/pdsa/releases
    :alt: Current Release Version

.. image:: https://img.shields.io/pypi/v/pdsa.svg?style=flat-square
    :target: https://pypi.python.org/pypi/pdsa
    :alt: pypi Version

.. image:: https://readthedocs.org/projects/pdsa/badge/?version=latest&style=flat-square
    :target: http://pdsa.readthedocs.io/en/latest/
    :alt: Documentation Version

.. image:: https://img.shields.io/pypi/pyversions/pdsa.svg?style=flat-square
    :target: https://github.com/gakhov/pdsa
    :alt: Python versions

.. contents ::

The Book
----------

Everybody interested in learning more about probabilistic data structures and
algorithms could be referred to our recently published book:

`Probabilistic Data Structures and Algorithms for Big Data Applications <https://pdsa.gakhov.com>`_ by Andrii Gakhov

2019, ISBN: 978-3748190486 (paperback) ASIN: B07MYKTY8W (e-book)

Introduction
------------

Probabilistic data structures is a common name of data structures
based on different hashing techniques.

Unlike regular (or deterministic) data structures, they always provide
approximated answers, but usually with reliable ways to estimate
the error probability.

The potential losses or errors are fully compensated by extremely
low memory requirements, constant query time and scaling.

GitHub repository: `<https://github.com/gakhov/pdsa>`_

Dependencies
---------------------

* Python 3.5+ (http://python.org/download/)
* Cython 0.28+ (http://cython.org/#download)

Documentation
--------------

The latest documentation can be found at `<http://pdsa.readthedocs.io/en/latest/>`_

**Membership problem**

- `Bloom Filter <http://pdsa.readthedocs.io/en/latest/membership/bloom_filter.html>`_
- `Counting Bloom Filter <http://pdsa.readthedocs.io/en/latest/membership/counting_bloom_filter.html>`_

**Cardinality problem**

- `Linear counter <http://pdsa.readthedocs.io/en/latest/cardinality/linear_counter.html>`_
- `Probabilistic counter (Flajolet–Martin algorithm) <http://pdsa.readthedocs.io/en/latest/cardinality/probabilistic_counter.html>`_
- `HyperLogLog <http://pdsa.readthedocs.io/en/latest/cardinality/hyperloglog.html>`_

**Frequency problem**

- `Count Sketch <http://pdsa.readthedocs.io/en/latest/frequency/count_sketch.html>`_
- `Count-Min Sketch <http://pdsa.readthedocs.io/en/latest/frequency/count_min_sketch.html>`_

**Rank problem**

- `Random Sampling <http://pdsa.readthedocs.io/en/latest/rank/random_sampling.html>`_
- `q-digest <http://pdsa.readthedocs.io/en/latest/rank/qdigest.html>`_

License
-------

MIT License

Source code
-----------

* https://github.com/gakhov/pdsa/

Authors
-------

* Maintainer: `Andrii Gakhov <andrii.gakhov@gmail.com>`

Install with pip
--------------------

Installation requires a working build environment.

Using pip, PDSA releases are currently only available as source packages.

.. code:: bash

    $ pip3 install -U pdsa

When using pip it is generally recommended to install packages in a ``virtualenv``
to avoid modifying system state:

.. code:: bash

    $ virtualenv .env -p python3 --no-site-packages
    $ source .env/bin/activate
    $ pip3 install -U cython
    $ pip3 install -U pdsa

Compile from source
---------------------

The other way to install PDSA is to clone its
`GitHub repository <https://github.com/gakhov/pdsa>`_ and build it from
source.

.. code:: bash

    $ git clone https://github.com/gakhov/pdsa.git
    $ cd pdsa

    $ make install

    $ bin/pip3 install -r requirements-dev.txt
    $ make test


text:
<?php
/**
 * Created by PhpStorm.
 * User: pavka
 * Date: 4/24/15
 * Time: 11:12 AM
 */

namespace Energine\shop\gears;

use Energine\share\gears\Builder;
use Energine\share\gears\FieldDescription;
use Energine\share\gears\SimpleBuilder;

class EmptySimpleFormBuilder extends SimpleBuilder {
    protected function run() {
        parent::run();

        if(!$this->dataDescription->isEmpty())
            $this->getResult()->removeAttribute('empty');
    }
    /**
     * @copydoc Builder::createField
     */
    protected function createField($fieldName, FieldDescription $fieldInfo, $fieldValue = false, $fieldProperties = false) {
        foreach(
            [
                'nullable',
                'pattern',
                'message',
                'tabName',
                'sort',
                'customField',
                //'deleteFileTitle',
                /*'msgOpenField',
                'msgCloseField',*/
                'default'
            ] as $propertyName
        ) {
            $fieldInfo->removeProperty($propertyName);
        }

        return Builder::createField($fieldName, $fieldInfo, $fieldValue, $fieldProperties);
    }
}


text:
var game = new Phaser.Game(500, 340, Phaser.AUTO, 'gameDiv');

game.global = {
	score: 0
};

game.state.add('boot', bootState);
game.state.add('load', loadState);
game.state.add('menu', menuState);
game.state.add('play', playState);

game.state.start('boot');


text:
<!DOCTYPE html>

<form>
<textarea>Passed</textarea>
</form>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.deidentifier.arx.test.AbstractTestUtilityMetrics.ARXUtilityMetricsTestCase</title>
<meta name="date" content="2019-11-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.deidentifier.arx.test.AbstractTestUtilityMetrics.ARXUtilityMetricsTestCase

Packages that use AbstractTestUtilityMetrics.ARXUtilityMetricsTestCase

Package
Description

org.deidentifier.arx.test

Uses of AbstractTestUtilityMetrics.ARXUtilityMetricsTestCase in org.deidentifier.arx.test

Methods in org.deidentifier.arx.test with parameters of type AbstractTestUtilityMetrics.ARXUtilityMetricsTestCase

Modifier and Type
Method and Description

static Data
AbstractTestUtilityMetrics.getDataObject(AbstractTestUtilityMetrics.ARXUtilityMetricsTestCase testCase)

Returns the data object for the test case.

Constructors in org.deidentifier.arx.test with parameters of type AbstractTestUtilityMetrics.ARXUtilityMetricsTestCase

Constructor and Description

AbstractTestUtilityEstimation(AbstractTestUtilityMetrics.ARXUtilityMetricsTestCase testcase)

Creates a new instance.

AbstractTestUtilityMetrics(AbstractTestUtilityMetrics.ARXUtilityMetricsTestCase testCase)

Creates a new instance.

TestUtilityEstimation(AbstractTestUtilityMetrics.ARXUtilityMetricsTestCase testCase)

Creates a new instance.

TestUtilityMetrics(AbstractTestUtilityMetrics.ARXUtilityMetricsTestCase testCase)

Creates a new instance

TestUtilityMetrics2(AbstractTestUtilityMetrics.ARXUtilityMetricsTestCase testCase)

Creates a new instance.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
import { Component, OnInit } from '@angular/core';
import { StatsService } from '../stats.service';

@Component({
  selector: 'app-mute-button',
  templateUrl: './mute-button.component.html',
  styleUrls: ['./mute-button.component.scss']
})
export class MuteButtonComponent implements OnInit {

  constructor(public _stats: StatsService) { }

  ngOnInit() {
    this._stats.muted = localStorage.getItem('muted') === 'true';
  }

  toggleMuted() {
    this._stats.muted = !this._stats.muted;
    localStorage.setItem('muted', this._stats.muted.toString());
  }

}


text:
using System;
using Newtonsoft.Json.Serialization;

namespace Core.Serialization.Json
{
  public class GuidBinder : DefaultSerializationBinder
  {

    public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
    {
      var assembly = serializedType.Assembly;
      //var guid = assembly.GetGuid();
      var id = serializedType.GUID;
      typeName = id.ToString();
      assemblyName = string.Empty;
      //base.BindToName(serializedType, out assemblyName, out typeName);
    }
    public override Type BindToType(string assemblyName, string typeName)
    {

      Guid id = Guid.Parse(typeName);
      var type = ReflectionService.Instance.GetById(id);
      //var result = base.BindToType(assemblyName, typeName);
      return type;
    }
  }
}


text:
package marubinotto.util.procedure;

/**
 * marubinotto.util.procedure.Procedure
 */
public interface Procedure {

    public Object execute(Object input) throws Exception;
}


text:
===========
Mojito: FAQ
===========

This page answers some of the most common questions we get about Mojito. For
troubleshooting issues, see
`Mojito: Troubleshooting <../reference/mojito_troubleshooting.html>`_.

Questions
=========

General
-------

* :ref:`What languages can I use to develop mojits? <moj_langs>`
* :ref:`Can I work on Mojito applications offline? <moj_offline>`
* :ref:`Does Mojito work in a Windows environment? <moj_windows>`
* :ref:`Do I have to restart Mojito to see updates that I've made to my application? <moj_nodemon>`
* :ref:`Is the Mojito Y instance persistent across requests? <moj_req_persistent>`
* :ref:`Does Mojito support lazy loading? <moj_lazyloading>`
* :ref:`Does Mojito have API methods for handling caching? If not, what's the best way for Mojito
  applications to handle caching? <moj_caching>`
* :ref:`Can Mojito make runtime decisions to run client-side or server-side code? <moj_run_client_server>`
* :ref:`Can Mojito be started with Node.js instead of using "mojito start"? <moj_node_start>`
* :ref:`How can I improve the performance of my Mojito application? <moj_optimize_performance>`

Configuration
-------------

* :ref:`How do I configure Mojito to deploy my application to the client? <moj_deploy>`
* :ref:`How do I configure mojits to run on the client? <moj_client>`
* :ref:`How do I configure the Mojito server to listen to specific port? <moj_config_port>`
* :ref:`What is the difference between 'definition.json' and 'defaults.json'? <moj_definition_defaults>`

Data
----

* :ref:`How do I get content for my mojits? <moj_content>`
* :ref:`How is data shared among mojits? <moj_share_data>`
* :ref:`How does a parent mojit send data to the template? <moj_parent_mojit_data>`
* :ref:`In Mojito applications, how are parameters passed from the controller to binders? <moj_params_controller_binder>`
* :ref:`How can data be passed from a parent mojit to its child mojits? <moj_pass_data_parent_to_child>`

Binders
-------

* :ref:`What are binders and what do they do? <moj_binders>`

CSS/JavaScript Assets
---------------------

* :ref:`How do I add assets templates? <moj_assets>`
* :ref:`How are assets dynamically added to views? <moj_dyn_assets>`

HTTP Headers/Responses
----------------------

* :ref:`Can Mojito applications access the 'request' or 'response' instances of the Node.js classes
  'http.ServerRequest' and 'http.ServerResponse'? <moj_req_res_instances>`
* :ref:`Is it possible to access HTTP headers from a Mojito application? <moj_access_headers>`
* :ref:`How does a Mojito application set the expiration of a cookie in the HTTP response? <moj_cookie_exp>`

Mojits
------

* :ref:`What is a mojit? <mojit_exp>`
* :ref:`Can mojits have child mojits? <moj_children>`
* :ref:`How do mojits share objects? <moj_objects>`
* :ref:`Can mojit instances be dynamically defined and then run? <moj_dynamic_creation>`
* :ref:`Is there a way to make all of the resources, such as assets, addons, binders, models, of one mojit available to other mojits? <moj_resources>`
* :ref:`Why does Mojito replace hyphens in the names of my mojits with underscores? <moj_names_hyphens>`
* :ref:`Can I extend or re-use mojits? <moj_reuse>`

Views
-----

* :ref:`Does Mojito support view partials? <moj_partials>`
* :ref:`Do I have to create separate mojits for different devices? <moj_devices>`
* :ref:`How do I refresh the view on the client? <moj_refresh_view>`
* :ref:`Can I use a different templating system other than Handlebars? <moj_different_templating>`
* :ref:`Can the mojit controller specify which template should be rendered? <moj_controller_specify_view>`

Logging/Testing
---------------

* :ref:`How do I change the logging levels for my Mojito application? <moj_log_level>`
* :ref:`Is there a way to exclude specific modules from logging on the client? <moj_mod_log_exclusion>`
* :ref:`Can logging be configured to be different for the client and server? <moj_client_server_logging>`

Addons/Libraries/Middleware
---------------------------

* :ref:`Does the Mojito framework offer API methods or addons? <moj_api_addons>`
* :ref:`Can I repurpose or extend existing YUI modules? <moj_yui>`

Answers
=======

General
-------

.. _moj_langs:
.. topic::  **What languages can I use to develop mojits?**

    JavaScript is the programming language of Cocktails. All modules are written in
    JavaScript, and JavaScript only. Modules that require server-side execution do so
    through a server-side JavaScript execution engine.

------------

.. _moj_offline:
.. topic:: **Can I work on Mojito applications offline?**

    The tools used in developing mojit modules (mojits) work offline, without requiring
    access to networked resources. When networked (cloud) resources are required due to the
    modules own nature, e.g., retrieving data from a back-end service, Cocktails provides
    facilities to mock these resources and simulate their behavior with dummy (local)
    implementations.

------------

.. _moj_windows:
.. topic:: **Does Mojito work in a Windows environment?**

    Unfortunately, Mojito is only supported on Unix-based systems. We hope to support
    Mojito on Windows in the future, so please check the
    `Mojito Releases Notes <`https://github.com/yahoo/mojito/wiki>`_ on GitHub for the
    latest updates.

.. _moj_nodemon:
.. topic:: **Do I have to restart Mojito to see updates that I've made to my application?**

    No, you can use the development environment with certain configurations or use
    an external module such as ``nodemon`` or ``supervisor`` to start Mojito, which will
    automatically update any changes that you've made to your application.

    **I. Using the Development Environment**

    #. In your ``application.json``, add the configuration object with the
       ``settings`` property given the array ``[ "environment:development" ]`` with the
       configurations for ``staticHandling``, ``viewEngine``, and ``yui`` shown
       below.

       .. code-block:: javascript

          [
            {
              "settings": [ "master" ],
              "appPort": "8666",
              "specs": {
                "frame": {
                  "type": "HTMLFrameMojit",
                  "config": {
                    "deploy": true,
                    "child": {
                      "type": "foo"
                    }
                  }
                }
              }
            },
            {
              "settings": [ "environment:development" ],
              "staticHandling": {
                "forceUpdate": true
              },
              "viewEngine": {
                "cacheTemplates": false
              },
              "yui": {
                "config": {
                  "combine": false
                }
              }
            }
          ]

       .. note:: Your application has to deploy code to the client, so
                ``deploy`` must be set to ``true``.

    #. Start your application with the context ``environment:development``:

       ``$ mojito start --context environment:development``
    #. Open your application in a browser.
    #. Modify code in your binders or templates.
    #. Refresh your browser to see the updates in your application.

    **Caveats**

    Although binder code and templates will be updated after you refresh your browser,
    resources, such as a model or controller, with a ``server`` or ``common`` affinity
    are executed in the Node.js environment, and therefore, will not get refreshed.
    You will need to restart your application to see changes. Also, meta data for modules,
    such as adding a module dependency to the ``requires`` array will not be reflected
    until you restart the application.

    **II. Using External Modules**

    You will need ``npm`` to install ``nodemon`` or ``supervisor``. To use ``nodemon``,
    you will need a script to start the server.

    Follow the steps below to use ``nodemon``:

    1. Install ``nodemon``:  ``$ sudo npm install nodemon -g``

    2. In your Mojito application directory, create the file ``devel.js`` with the
       following:

       .. code-block:: javascript

          require('./server.js').listen(8666, null, function() {
            console.log('----STARTED----');
            console.log('Nodemon will not honor the app port from the settings');
            console.log('The application is running under http://localhost:8666/');
          });

    3. From your application directory, start Mojito with ``nodemon``:

       ``$ nodemon devel.js``

    To use `supervisor <https://github.com/isaacs/node-supervisor>`_, follow these steps:

    #. Globally install ``supervisor``.

       ``$ sudo npm install supervisor -g``
    #. From a Mojito application directory, start Mojito with ``supervisor``:

       ``$ supervisor -x path/to/mojito/bin/mojito start``
    #. View your application in a browser.
    #. In a separate terminal window, make changes to the source code of the application.
    #. Refresh the page to view the modified application.

    .. note:: ``supervisor`` will only update files with extensions ``node`` or ``js`` by
              default. To have ``supervisor`` watch files with other extensions, use the
              option ``-e`` or ``--extensions``: ``$ supervisor -e js,json,html -x path/to/mojito start``

------------

.. _moj_req_persistent:
.. topic:: **Is the Mojito Y instance persistent across requests?**

    Yes, each mojit will have a Y instance that is persistent (by default) for every
    successive request. Computing YUI dependencies for every request negatively affects
    performance. You can change this behavior through the settings or you can deal with it
    at the mojit level, recreating the object.

------------

.. _moj_lazyloading:
.. topic:: **Does Mojito support lazy loading?**

    Yes, the Mojito framework comes with the frame mojit ``LazyLoadMojit`` specifically
    for lazy loading. The ``LazyLoadMojit`` allows you to defer the loading of a mojit
    instance by first dispatching the ``LazyLoadMojit`` as a proxy to the client. From the
    client, ``LazyLoadMojit`` can then request Mojito to load the proxied mojit. This
    allows your Mojito application to load the page quickly and then lazily load parts of
    the page. See `LazyLoadMojit <../topics/mojito_frame_mojits.html#lazyloadmojit>`_
    to learn more.

------------

.. _moj_caching:
.. topic:: **Does Mojito have API methods for handling caching? If not, what's the best
           way for Mojito applications to handle caching?**

    Mojito currently does not have any API methods for handling caching. Although there is
    no definitive solution for caching for Mojito, here are a few possible ways to cache
    for Mojito applications:

    - **Client-Side Caching**

       - `Create an HTML5 application <../reference/mojito_cmdline.html#html5app>`_ and
         use the ``manifest.cache`` file.
       - Leverage the HTML5 ``localStorage`` object.
       - Use the `Storage Lite <http://yuilibrary.com/gallery/show/storage-lite>`_ YUI
         module that selects the best available local storage API supported by the browser
         it's running in.
       - `Create an addon <../topics/mojito_extensions.html#creating-new-addons>`_ that
         uses a singleton.

    - **Server-Side Caching (implementation depends on server)**

       - Use the ``fs`` Node.js module to write to the file system.
       - Use one of the Node.js modules for caching: `cradle <http://cloudhead.io/cradle>`_,
         `nodejs_redis <https://github.com/mranney/node_redis>`_,
         `node-optimist <https://github.com/substack/node-optimist>`_, etc.
       - Implement a tried and tested caching solution such as `memcached <http://memcached.org/>`_.

------------

.. _moj_run_client_server:
.. topic:: **Can Mojito make runtime decisions to run client-side or server-side code?**

    Yes, but it's up to the programmer to configure the application to be deployed to the
    client. Also, your application should have client and server versions, indicated by an
    `affinity <../reference/glossary.html#affinity>`_, of the controller, models, addons,
    etc., that you want to run on both the client and the server. To configure Mojito to
    deploy application code to the client, you set the ``deploy`` property of the
    application configuration to ``true``.
    See `Configuring Applications to Be Deployed to Client <../intro/mojito_configuring.html#configuring-applications-to-be-deployed-to-client>`_
    for more information.

    Mojito determines the client device based on the HTTP header ``User-Agent`` or the
    value of the query string parameter ``device`` and then will render the appropriate
    view if it exists--it's up to the developer to create the views. For example, if an
    iPhone is making a request, Mojito will render the view ``index.iphone.hb.html`` if it
    has been created. See `Views: Naming Conventions <../intro/mojito_mvc.html#naming-convention>`_
    for more information.

------------

.. _moj_node_start:
.. topic:: **Can Mojito be started with Node.js instead of using "mojito start"?**

    Yes. Although there is not a standard way for starting Mojito with Node.js, you could
    do the following::

       $ node --debug `which mojito` start

    Or you could specify the path to start a locally installed version of Mojito::

       $ node --debug node_modules/mojito/bin/mojito start

------------

.. _moj_optimize_performance:
.. topic:: **How can I improve the performance of my Mojito application?**

    The following sections offer some ideas about how to improve the performance of your
    Mojito application, but are by no means exhaustive. You should also review online
    articles about improving Node.js performance, such as
    `Blazing fast node.js: 10 performance tips
    from LinkedIn Mobile <http://bit.ly/uFyio2>`_ written by software engineer Shravya
    Garlapati.

    **Don't Add User Data to ac.context**

    The ``context`` property of the ``ActionContext`` object contains a small set of
    key-value pairs that define the run-time environment under which a mojit runs. These
    key-value pairs are used as a cache key. Adding your own key/values to ``ac.context``
    will cause the cache to bloat.

    As an alternative, you can share data using the following methods:

       * Parent mojits can share data with the child mojits by attaching data to the
         ``ActionContext`` object in the parent mojit's controller. For example, in the
         parent mojit, you could add an object to ``ac.composite.command.params.body``
         that the children can then access with
         ``ac.composite.command.params.body['{obj_name}']``.
       * From the server and before mojits are executed, middleware can be used to share
         information about static handling and routing.
       * Assets and data can be shared through the
         `template <../reference/glossary.html#view-template>`_ of a parent mojit or
         through a frame mojit such as
         `HTMLFrameMojit <../topics/mojito_frame_mojits.html#htmlframemojit>`_ that
         creates a parent template.

    **Rollup/Minify Assets**

    Rolling up and minifying assets will reduce the number of network calls and improve
    load time. For **rolling up assets**, we recommend that you use
    `Shaker <https://github.com/yahoo/mojito-shaker>`_, which is a static asset rollup
    manager.

    Mojito also allows you to configure your app to use rollups by setting the
    ``useRollups`` property in the ``application.json`` file to ``true`` as shown below::

      "staticHandling": {
        "useRollups": true
      }

    You can also compile rollups, inline CSS, or views using the Mojito command-line
    utility. See the `Compile System <../reference/mojito_cmdline.html#compile-system>`_
    to learn how.

    For **minification**, we recommend Shaker again. Other choices could be `YUI Compressor
    <http://yuilibrary.com/download/yuicompressor/>`_ or an npm module such as
    `UglifyJS <https://github.com/mishoo/UglifyJS>`_.

    **Use Lazy Loading**

    From the client, your Mojito application should lazy load assets as often as possible.
    For example, the `YUI ImageLoader Utility <http://yuilibrary.com/yui/docs/imageloader/>`_
    can be used to help you lazy load images. You can even lazy load a mojit from the client
    using the `LazyLoadMojit <../topics/mojito_frame_mojits.html#lazyloadmojit>`_.

Configuration
-------------

.. _moj_deploy:
.. topic:: **How do I configure Mojito to deploy my application to the client?**

    Binders always get deployed to the client, but to deploy your controller to the
    client, you need to use the `HTMLFrameMojit <../topics/mojito_frame_mojits.html#htmlframemojit>`_
    and set the ``deploy`` field to ``true`` in the ``application.json`` file. See
    `Deploying to Client <../topics/mojito_frame_mojits.html#deploying-to-client>`_
    for more details.

------------

.. _moj_client:
.. topic:: **How do you configure mojits to run on the client?**

    Run Mojito at build time to generate the HTML page using ``mojito build html5app``.
    This runs the Mojito infrastructure as if it were a running server instance and prints
    out the resulting HTML+JSON required to bootstrap a client-side mojit.
    Among other things, it leads down a path where it's very hard to do
    incremental builds because the Web server abstraction makes it hard to do the timestamp
    resolution that incremental builds require. A better approach would be to allow people
    to hard-code the top-level mojit bootstrap code by publishing mojit creation APIs that
    can be called from the top level.

------------

.. _moj_config_port:
.. topic:: **How do I configure the Mojito server to listen to specific port?**

    In the `configuration Object <../intro/mojito_configuring.html#configuration-object>`_
    of ``application.json``, you set the ``appPort`` property to the port number that you
    want Mojito to listen to.

------------

.. _moj_definition_defaults:
.. topic:: **What is the difference between 'definition.json' and 'defaults.json'?**

    The ``definitions.json`` file stores the class-level mojit values and is ideal for
    storing metadata. The ``defaults.json`` file stories default configurations for your
    mojit instance that will be overridden if they are found in the ``application.json``
    file. See `Configuring Defaults for Mojit Instances <../intro/mojito_configuring.html#configuring-defaults-for-mojit-instances>`_
    and `Mojit Configuration: Configuring Metadata <../intro/mojito_configuring.html#mojit-configuration>`_
    for more information.

Data
----

.. _moj_content:
.. topic:: **How do I get content for my mojits?**

    YQL is the preferred method for accessing data in Mojito applications. YUI 3 also has
    a `YQL module <http://yuilibrary.com/gallery/show/yql>`_ that makes calling the YQL
    Web Service easy.

------------

.. _moj_share_data:
.. topic:: **How is data shared among mojits?**

    You can create an application-level mojit that can share data with its children. Your
    application-level mojit would have a model to get data that can be stored data in a
    Model object. The child mojits can then access this data through the application-level
    mojit's model.

------------

.. _moj_parent_mojit_data:
.. topic:: **How does a parent mojit send data to the template?**

    From the controller of the parent mojit, pass an object to ``ac.composite.done``
    containing key-value pairs that can be added
    to the view template as Handlebars expressions. For example, the key ``foo``
    shown below can be included in the template as the Handlebars expression ``{{foo}}``.
    The ``{{foo}}`` expression will be replaced by the value 'bar' when the template
    is rendered.::

      // Inside parent mojit
      ac.composite.done({"foo": "bar"});

------------

.. _moj_params_controller_binder:
.. topic:: **In Mojito applications, how are parameters passed from the controller to binders?**

    Your controllers can pass parameters to binders using the ``Data`` addon.
    The controller requires the ``Data`` addon and then uses the ``data`` object with
    the ``set`` method to set (or expose) data for the client code (binders or templates):
    ``ac.data.set('app_framework', "Mojito");``

    From the binder, the ``mojitProxy`` object can then access the data set by the controller
    from the ``data`` object with the ``get`` method: ``mojitProxy.data.get('app_framework');``

    The mojit's template can access the set data through a Handlebars expression, so
    the ``index.hb.html`` could use ``{{app_framework}}`` to get the data set in the controller.

    The ``Data`` addon also allows you to share page-level data, so that mojits on the
    page can share data through ``ac.pageData.set`` and ``ac.pageData.get`` or ``mojitProxy.pageData.get``.
    See  `Sharing Data <../topics/mojito_data.html#sharing>`_ for more information and example code.

------------

.. _moj_pass_data_parent_to_child:
.. topic:: **How can data be passed from a parent mojit to its child mojits?**

    Currently the only way to do this is to pass data to the children in either the
    children config or parameters. If you use ``ac.composite.execute`` you can
    create/modify the children configuration in code before calling
    ``ac.composite.execute``. See `ac.composite.execute <../../api/classes/Composite.common.html#method_execute>`_
    for more information.

    If you want to pass the data to the children in the parameters, you can do that with
    the ``ac._dispatch`` function. See
    `ac._dispatch <../../api/classes/ActionContext.html#method__dispatch>`_ for more
    information.

Binders
-------

.. _moj_binders:
.. topic:: **What are binders and what do they do?**

    Binders are mojit code that is only deployed to the browser. A mojit may have zero,
    one, or many binders. The code can perform the following three functions:

       * allow event handlers to attach to the mojit DOM node
       * communicate with other mojits on the page
       * execute actions on the mojit that the binder is attached to

CSS/JavaScript Assets
---------------------

.. _moj_assets:
.. topic:: **How do I add assets templates?**

    You define the location of application-level or mojit-level assets in the
    ``application.json`` file. Once the location of your assets has been configured, you
    can statically add the path to the assets in your template. You can also add assets to
    your view using the `Assets addon <../../api/classes/Assets.common.html>`_ if your
    application is using the ``HTMLFrameMojit``. See the `Assets <../topics/mojito_assets.html>`_
    documentation for implementation details.

------------

.. _moj_dyn_assets:
.. topic:: **How are assets dynamically added to views?**

    The `Assets addon <../../api/classes/Assets.common.html>`_ allow you to dynamically
    add to your view. You need to use the ``HTMLFrameMojit``, however, to use the
    ``Assets addon``. See
    `Using the Assets Addon <../topics/mojito_assets.html#using-the-assets-addon>`_ for
    more information.

HTTP Headers/Responses
----------------------

.. _moj_req_res_instances:
.. topic:: **Can Mojito applications access the 'request' or 'response' instances of the
           Node.js classes 'http.ServerRequest' and 'http.ServerResponse'?**

    Yes, the Mojito API has the ``ActionContext`` addon ``Http.server`` that has methods
    for getting the ``request`` and ``response`` instances of the Node.js classes
    ``http.ServerRequest`` and ``http.ServerResponse``. From the ``ActionContext`` object
    ``ac`` shown below, you call ``http.getRequest`` and ``http.getResponse`` to get the
    ``request`` and ``response`` instances. See `Class Http.server <../../api/classes/Http.server.html>`_
    for more information.

    .. code-block:: javascript

       var request = ac.http.getRequest();
       var response = ac.http.getResponse();

------------

.. _moj_access_headers:
.. topic:: **Is it possible to access HTTP headers from a Mojito application?**

    Yes, the Mojito API has the ``ActionContext`` addon ``Http.server`` that allows you to
    get, set, and add HTTP headers. See `Class Http.server <../../api/classes/Http.server.html>`_
    for the available methods.

------------

.. _moj_cookie_exp:
.. topic:: **How does a Mojito application set the expiration of a cookie in the HTTP response?**

    The controller of your application can get the HTTP response with the ``Http``
    addon and then set the cookie and the max age (expiration) with the ``Cookie`` addon.
    In the example controller below, the cookie is set to expire in two weeks.
    Note that the value for ``maxAge`` is in milliseconds and that you need to
    require ``mojito-cookie-addon`` and ``mojito-http-addon`` to use the addons.

    .. code-block:: javascript

       YUI.add('setCookie', function(Y, NAME) {

         Y.namespace('mojito.controllers')[NAME] = {

           index: function(ac) {
            ac.http.getResponse().cookie("cookie_set", "true", { "maxAge": 1209600000 });
            ac.done({
                status: 'Cookie set to expire in two weeks (maxAge in milliseconds).',
            });
          }
        };
      }, '0.0.1', {requires: ['mojito', 'mojito-cookie-addon', 'mojito-http-addon']});

Mojits
------

.. _mojit_exp:
.. topic:: **What is a mojit?**

    The basic unit of composition and reuse in a Mojito application. It typically
    corresponds to a rectangular area of a page and uses MVC.

------------

.. _moj_children:
.. topic:: **Can mojits have child mojits?**

    Yes, you can configure your application to have mojits that have one or more child
    mojits. The parent mojit can execute the child mojits using the
    `Composite addon <../../api/classes/Composite.common.html>`_.
    See `Configuring Applications to Have Multiple Mojit <../intro/mojito_configuring.html#configuring-applications-to-have-multiple-mojits>`_
    and `Composite Mojits <../topics/mojito_composite_mojits.html#composite-mojits>`_.

    You can also use frame mojits, such as `HTMLFrameMojit <../topics/mojito_frame_mojits.html#htmlframemojit>`_
    that can execute one or more child mojits.

------------

.. _moj_objects:
.. topic:: **How do mojits share objects?**

    You create an application-level middleware or an ActionContext addon that all mojits
    can access. Your mojits can use this middleware or the ActionContext addon to share
    objects. See `Creating Addons <../topics/mojito_extensions.html#creating-new-addons>`_
    and `Middleware <../topics/mojito_extensions.html#middleware>`_ for implementation
    details.

------------

.. _moj_dynamic_creation:
.. topic:: **Can mojit instances be dynamically defined and then run?**

    You can run dynamically defined instances of mojits that you created with the Mojito
    command-line tool. You would create these instances in a mojit controller using the
    ``ActionContext`` object with either the ``_dispatch`` or ``execute`` methods.
    See `Running Dynamically Defined Mojit Instances <../topics/mojito_run_dyn_defined_mojits.html>`_
    for more information.

------------

.. _moj_resources:
.. topic:: **Is there a way to make all of the resources, such as assets, addons, binders,
           models, of one mojit available to other mojits?**

    To make the resources of one mojit available to other mojits, you set the ``appLevel``
    property in the ``application.json`` file to ``true``. Mojits wanting to use the
    resources of application-level mojit must include the YUI module of the
    application-level mojit in the ``requires`` array.
    See `Configuring Metadata <../intro/mojito_configuring.html#configuring-metadata>`_
    for more information.

------------

.. _moj_names_hyphens:
.. topic:: **Why does Mojito replace hyphens in the names of my mojits with underscores?**

    The ECMAScript syntax for ``Identifiers`` does not allow hyphens, so Mojito replaces
    them with underscores. See the section **Identifier Names and Identifiers** in the
    `ECMAScript Documentation <http://www.ecmascript.org/docs.php>`_ for the syntax rules
    for ``Identifier`` and ``IdentifierName``.

------------

.. _moj_reuse:
.. topic:: **Can I extend or re-use mojits?**

    Although inheritance isn't supported in mojits, there are ways of
    re-using mojit definitions and configuration, application building blocks, and
    extending mojits.

    The following sections offer a brief introduction to re-use and extension in Mojito
    as well as what cannot be re-used or extended.

    **Re-Using Mojit Definitions**

    You can re-use a mojit definition by using the `specs.base <../intro/mojito_configuring.html#specs-object>`_
    property in ``application.json``, so that mojit instance uses the same mojit
    definition of another mojit instance. This allows you to define a mojit instance
    once and have many instances use it.

    For example, the mojit instances ``index_page`` and ``profile_page`` use the
    re-use the ``basic_page`` mojit definition in the ``application.json``
    below:

    .. code-block:: javascript

       [
         {
           "settings": [ "master" ],
           "specs": {
             "basic_page": {
	             "type": "HTMLFrameMojit",
	             "config": {
	               "child" : {
	                "config" : {
	                  "children" : {
	                    "header" : {
	                      "type" : "Header"
	                    },
	                    "footer" : {
	                      "type" : "Footer"
	                    }
	                  }
	                }
	              },
               "index_page": {
                 "base" : "basic_page",
                   "config": {
	                   "title": "Home Page",
	                   "child" : {
	                     "type" : "Index"
                     }
                   }
                 }
               },
               "profile_page": {
                 "base" : "basic_page",
                   "config": {
	                   "title": "Your Profile",
	                   "child" : {
	                     "type" : "Profile"
                     }
                   }
                 }
               }
             }
           }
         }
       ]

    **Re-Using Application Building Blocks**

    In general, instead of extending a mojit, you would create a new
    mojit and then re-use building blocks such as YUI modules, assets,
    models, etc. For example, instead of having the ``stockProfile`` mojit
    extend the ``stockQuote`` mojit to get stock quotes, your ``stockProfile``
    mojit could use the same addon, YUI module, or model to get the stock quotes.

    See the following chapters on assets, extending Mojito, and models:

       - `Assets <../topics/mojito_assets.html>`_ - learn how to configure, access, and
         use the ``Assets`` addon.
       - `Extending Mojito <../topics/mojito_extensions.html>`_ - learn how
         to create addons and add YUI modules.
       - `Models <../intro/mojito_mvc.html#models>`_ - learn how to create and access
         models.

    **Requiring the Controller of Another Mojit**

    Starting with Mojito v0.5, you can create a new controller that requires
    the controller from another mojit. You simply require and merge the controller
    of the other mojit as shown below:

    .. code-block:: javascript

       YUI.add('bar', function(Y, NAME) {

         Y.namespace('mojito.controllers')[NAME] = Y.merge(Y.mojito.controllers.Foo, {
           anotherNewAction: function (ac){
            // do something
           },
           redefinedAction: function (ac) {
             // do something
             // you can also play with:
             // Y.mojito.controllers.Foo.redefinedAction.apply()
           }
         });

       }, '0.0.1', {requires: ['foo']});

    The same principle applies to binders and models.

    **What Can't Be Re-Used/Extended?**

    The mojit configuration files ``definition.json`` and ``defaults.json`` cannot be
    re-used like the controller, binder(s), and model(s). In the near future, you will
    be able to re-use these configurations with the help of the ``import_settings``
    directive in JSON and YAML files. Assets are also not extensible, so they will
    have to be included manually.

Views
-----

.. _moj_partials:
.. topic:: **Does Mojito support view partials?**

    Mojito does not support partials, but you do have the following options for rendering
    data through a template:

       * use a child mojit instead of a view partial
       * render data from a binder through a specific template with the
         `render <../../api/classes/MojitProxy.html#method_render>`_ method.
       * render data from the controller using `ac.partial.render <../../api/classes/Partial.common.html#method_render>`_.

    Not clear what view partials are? See `view partial <../reference/glossary.html#view-partial>`_
    in the `Mojito: Glossary <../reference/glossary.html>`_.

------------

.. _moj_devices:
.. topic:: **Do I have to create separate mojits for different devices?**

    The platform's capabilities allow mojits to be executed (and their results displayed)
    on every device in either set. For a module developer, the benefit is obvious: a single
    codebase that can address a wide range of devices. Mojits may still need to be
    customized for a specific device (or device class), however, to take advantage of
    device-specific capabilities. The platform does not perform an automated
    translation/degradation of HTML5 views to simpler layouts, for example.

------------

.. _moj_refresh_view:
.. topic:: **How do I refresh the view on the client?**

    To refresh a view, you need to deploy a binder on the client. From the ``mojitProxy``
    object of the binder, you can call the ``refreshView`` method to render a new DOM node
    for the current mojit and its children, as well as reattach all of the existing
    binders to their new nodes within the new markup. Because all binder instances are
    retained, state can be stored within a binder's scope. See
    `Refreshing Views <../intro/mojito_binders.html#refreshing-views>`_ and the
    `MojitProxy Class <../../api/classes/MojitProxy.html>`_ in the Mojito API
    documentation for more information.

------------

.. _moj_different_templating:
.. topic:: **Can I use a different templating system other than Handlebars?**

    Mojito currently only comes with a Handlebars rendering engine, but you can add other
    rendering engines for templating systems such as EJS or Jade. See the
    `View Engine <../topics/mojito_extensions.html#view-engines>`_ documentation for
    implementation details.

------------

.. _moj_controller_specify_view:
.. topic:: **Can the mojit controller specify which template should be rendered?**

    Yes, you can a ``view`` object as the second parameter to ``ac.done`` that specifies
    which template should receive the data and be rendered.
    See `Controllers: Specifying the View <../intro/mojito_mvc.html#specifying-the-view>`_
    for details.

Logging/Testing
---------------

.. _moj_log_level:
.. topic:: **How do I change the logging levels for my Mojito application?**

    You can set log levels for your application using the ``yui.config`` object in
    ``application.json``. You can also set default log levels using the ``yui.config``
    object in the ``defaults.json`` at the application or mojit level.

    See `Logging <../topics/mojito_logging.html>`_ for details and the code example
    `Simple Logging <../code_exs/simple_logging.html>`_.

------------

.. _moj_mod_log_exclusion:
.. topic:: **Is there a way to exclude specific modules from logging on the client?**

    Yes, you can use the ``logExclude`` property of the ``yui.config`` object to
    exclude the logging of specified modules.

    For example, the logging configuration set by ``yui.config`` below excludes
    logging from the module ``pagingBinder``:

    .. code-block:: javascript

       ...
          "yui": {
            "config": {
              "logExclude": "pagingBinder",
              "logLevel": "info"
            }
          }
      ...

    See `Including and Excluding Modules From Logging <../topics/mojito_logging.html#including-and-excluding-modules-from-logging>`_
    for more information.

------------

.. _moj_client_server_logging:
.. topic:: **Can logging be configured to be different for the client and server?**

    Yes, the ``application.json`` configuration file uses the ``yui.config`` object
    for configuring logging. You can use contexts to customize logging for
    different runtime environments. For instance, you could use the ``"runtime:client"``
    context to configure client-side logging and the ``"master"`` context to configure
    server-side logging. You can also use the properties ``logExclude`` and ``logInclude``
    of the ``yui.config`` object to log or not log certain components
    of your application.

    See `config Object <../intro/mojito_configuring.html#yui_config>`_
    and the `Log Configuration <../topics/mojito_logging.html#log-configuration>`_ for
    implementation details.

Addons/Libraries/Middleware
---------------------------

.. _moj_api_addons:
.. topic:: **Does the Mojito framework offer API methods or addons?**

    The Mojito framework provides API methods and addons through the ``ActionContext``
    object. For an overview of the API and addons, see
    `Mojito API Overview <../api_overview/>`_. To see the API specifications and the
    available addons, see the `Mojito API documentation <../../api/>`_.

------------

.. _moj_yui:
.. topic:: **Can I repurpose or extend existing YUI modules?**

    Although Mojit developers will have access to a library of modules, we realistically
    expect modules to require some tweaking before they can be re-purposed. Mojito,
    however, does offer facilities that make it possible and easy to extend existing
    modules.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Parmelia sulcata f. eusulcata Maas Geest.

### Remarks
null


text:
package sh.isaac.api.query.clauses;

import sh.isaac.api.Get;
import sh.isaac.api.SingleAssemblageSnapshot;
import sh.isaac.api.chronicle.LatestVersion;
import sh.isaac.api.collections.NidSet;
import sh.isaac.api.component.concept.ConceptSpecification;
import sh.isaac.api.component.semantic.SemanticChronology;
import sh.isaac.api.component.semantic.version.SemanticVersion;
import sh.isaac.api.coordinate.StampFilter;
import sh.isaac.api.query.ClauseComputeType;
import sh.isaac.api.query.ClauseSemantic;
import sh.isaac.api.query.LetItemKey;
import sh.isaac.api.query.Query;

import java.util.EnumSet;
import java.util.List;
import java.util.Map;

/**
 *
 * @author kec
 */
public class ReferencedComponentIsMemberOf
        extends ReferencedComponentWithManifoldAbstract {

    //~--- constructors --------------------------------------------------------
    /**
     * Instantiates a new refset contains concept.
     */
    public ReferencedComponentIsMemberOf() {
    }

    /**
     * Instantiates a new refset contains concept.
     *
     * @param enclosingQuery the enclosing query
     * @param assemblageSpecKey the refset spec key
     * @param stampCoordinateKey the manifold coordinate key
     */
    public ReferencedComponentIsMemberOf(Query enclosingQuery,
            LetItemKey assemblageSpecKey,
            LetItemKey stampCoordinateKey) {
        super(enclosingQuery, assemblageSpecKey, stampCoordinateKey);
    }

    //~--- methods -------------------------------------------------------------

    /**
     * Compute possible components.
     *
     * @param incomingPossibleComponents the incoming possible components
     * @return the nid set
     */
    @Override
    public Map<ConceptSpecification, NidSet> computePossibleComponents(Map<ConceptSpecification, NidSet> incomingPossibleComponents) {

        StampFilter stampFilter = (StampFilter) this.enclosingQuery.getLetDeclarations().get(getManifoldCoordinateKey());
        ConceptSpecification assemblageSpec = (ConceptSpecification) this.enclosingQuery.getLetDeclarations().get(getReferencedComponentSpecKey());

        SingleAssemblageSnapshot<SemanticVersion> snapshot = Get.assemblageService()
                .getSingleAssemblageSnapshot(assemblageSpec, SemanticVersion.class, stampFilter);

        NidSet possibleComponents = incomingPossibleComponents.get(getAssemblageForIteration());

        for (int nid: possibleComponents.asArray()) {
            SemanticChronology sc = Get.assemblageService().getSemanticChronology(nid);
            List<LatestVersion<SemanticVersion>> latestList
                    = snapshot.getLatestSemanticVersionsForComponentFromAssemblage(sc.getReferencedComponentNid());
            boolean isMemberOf = false;
            for (LatestVersion<SemanticVersion> latest : latestList) {
                if (test(latest)) {
                    isMemberOf = true;
                }
            }
            if (!isMemberOf) {
                possibleComponents.remove(nid);
            }
        }
        return incomingPossibleComponents;
    }

    protected boolean test(LatestVersion<SemanticVersion> latest) {
        return latest.isPresent();
    }

   //~--- get methods ---------------------------------------------------------

   /**
    * Gets the compute phases.
    *
    * @return the compute phases
    */
   @Override
   public EnumSet<ClauseComputeType> getComputePhases() {
      return PRE_ITERATION;
   }

    @Override
    public ClauseSemantic getClauseSemantic() {
        return ClauseSemantic.REFERENCED_COMPONENT_IS_MEMBER_OF;
    }
}


text:
package com.kanven.schedual.entity;

import java.io.Serializable;
import java.util.Date;

import org.apache.ibatis.type.Alias;

/**
 * 周期任务实体类
 *
 * @author kanven
 *
 */
@Alias("period")
public class PeriodTask implements Serializable {

	private static final long serialVersionUID = -6994016113690721456L;

	/**
	 * 任务编号
	 */
	private Long id;

	/**
	 * 项目名称
	 */
	private String projectName;

	/**
	 * 组别名称
	 */
	private String groupName;

	/**
	 * 任务名称
	 */
	private String taskName;

	/**
	 * 调用地址
	 */
	private String url;

	/**
	 * 表达式
	 */
	private String cron;

	/**
	 * 任务开始执行时间
	 */
	private Date startTime;

	/**
	 * 任务状态
	 */
	private Integer taskStatus;

	/**
	 * 任务描述
	 */
	private String description;

	/**
	 * 原IP地址
	 */
	private Integer srcIp;

	/**
	 * 目的IP地址
	 */
	private Integer destIp;

	/**
	 * 任务创建时间
	 */
	private Date createTime;

	/**
	 * 任务创建人
	 */
	private String createUser;

	/**
	 * 更新时间
	 */
	private Date updateTime;

	/**
	 * 任务更新人
	 */
	private String updateUser;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getProjectName() {
		return projectName;
	}

	public void setProjectName(String projectName) {
		this.projectName = projectName;
	}

	public String getGroupName() {
		return groupName;
	}

	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}

	public String getTaskName() {
		return taskName;
	}

	public void setTaskName(String taskName) {
		this.taskName = taskName;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getCron() {
		return cron;
	}

	public void setCron(String cron) {
		this.cron = cron;
	}

	public Date getStartTime() {
		return startTime;
	}

	public void setStartTime(Date startTime) {
		this.startTime = startTime;
	}

	public Integer getTaskStatus() {
		return taskStatus;
	}

	public void setTaskStatus(Integer taskStatus) {
		this.taskStatus = taskStatus;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Integer getSrcIp() {
		return srcIp;
	}

	public void setSrcIp(Integer srcIp) {
		this.srcIp = srcIp;
	}

	public Integer getDestIp() {
		return destIp;
	}

	public void setDestIp(Integer destIp) {
		this.destIp = destIp;
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public String getCreateUser() {
		return createUser;
	}

	public void setCreateUser(String createUser) {
		this.createUser = createUser;
	}

	public Date getUpdateTime() {
		return updateTime;
	}

	public void setUpdateTime(Date updateTime) {
		this.updateTime = updateTime;
	}

	public String getUpdateUser() {
		return updateUser;
	}

	public void setUpdateUser(String updateUser) {
		this.updateUser = updateUser;
	}

	@Override
	public String toString() {
		return "PeriodTask [id=" + id + ", projectName=" + projectName + ", groupName=" + groupName + ", taskName="
				+ taskName + ", url=" + url + ", cron=" + cron + ", startTime=" + startTime + ", taskStatus="
				+ taskStatus + ", description=" + description + ", srcIp=" + srcIp + ", destIp=" + destIp
				+ ", createTime=" + createTime + ", createUser=" + createUser + ", updateTime=" + updateTime
				+ ", updateUser=" + updateUser + "]";
	}

	public static enum TaskStatus {

		DEFAULT(-1), PAUSE(0), EXACTOR(1), CANCEL(-2);

		private int value;

		private TaskStatus(int value) {
			this.value = value;
		}

		public int value() {
			return this.value;
		}

	}

}


text:
module Fastlane
  module Actions
    # Adds a git tag to the current commit
    class PushToGitRemoteAction < Action
      def self.run(params)
        local_branch = params[:local_branch]
        local_branch ||= Actions.git_branch.gsub(%r{#{params[:remote]}\/}, '') if Actions.git_branch
        local_branch ||= 'master'

        remote_branch = params[:remote_branch] || local_branch

        # construct our command as an array of components
        command = [
          'git',
          'push',
          params[:remote],
          "#{local_branch}:#{remote_branch}",
          '--tags'
        ]

        # optionally add the force component
        command << '--force' if params[:force]

        # execute our command
        Actions.sh('pwd')
        return command.join(' ') if Helper.is_test?

        Actions.sh(command.join(' '))
        Helper.log.info 'Sucesfully pushed to remote.'
      end

      def self.description
        "Push local changes to the remote branch"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :local_branch,
                                       env_name: "FL_GIT_PUSH_LOCAL_BRANCH",
                                       description: "The local branch to push from. Defaults to the current branch",
                                       optional: true),
          FastlaneCore::ConfigItem.new(key: :remote_branch,
                                       env_name: "FL_GIT_PUSH_REMOTE_BRANCH",
                                       description: "The remote branch to push to. Defaults to the local branch",
                                       optional: true),
          FastlaneCore::ConfigItem.new(key: :force,
                                       env_name: "FL_PUSH_GIT_FORCE",
                                       description: "Force push to remote. Defaults to false",
                                       is_string: false,
                                       default_value: false),
          FastlaneCore::ConfigItem.new(key: :remote,
                                       env_name: "FL_GIT_PUSH_REMOTE",
                                       description: "The remote to push to. Defaults to `origin`",
                                       default_value: 'origin')
        ]
      end

      def self.author
        "lmirosevic"
      end

      def self.is_supported?(platform)
        true
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace BookingApp.Models
{
    public class Accommodation
    {

        private string address;
        private bool approved;
        private float averageGrade;
        private string description;
        private int id;
        private string imageURL;
        private double latitude;
        private double longitude;
        private string name;

        public List<Comment> m_Comment;

        public List<Room> m_Room;

        [ForeignKey("Place")]
        public int Place_Id { get; set; }

        public Place Place { get; set; }

        [ForeignKey("AppUser")]
        public int AppUser_Id { get; set; }

        public AppUser AppUser { get; set; }

        [ForeignKey("AccommodationType")]
        public int AccommodationType_Id { get; set; }

        public AccommodationType AccommodationType { get; set; }

        public Accommodation()
        {
            m_Comment = new List<Comment>();
            m_Room = new List<Room>();
        }

        ~Accommodation()
        {

        }

        public string Address
        {
            get
            {
                return address;
            }
            set
            {
                address = value;
            }
        }

        public bool Approved
        {
            get
            {
                return approved;
            }
            set
            {
                approved = value;
            }
        }

        public float AverageGrade
        {
            get
            {
                return averageGrade;
            }
            set
            {
                averageGrade = value;
            }
        }

        public string Description
        {
            get
            {
                return description;
            }
            set
            {
                description = value;
            }
        }

        public int Id
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }

        public string ImageURL
        {
            get
            {
                return imageURL;
            }
            set
            {
                imageURL = value;
            }
        }

        public double Latitude
        {
            get
            {
                return latitude;
            }
            set
            {
                latitude = value;
            }
        }

        public double Longitude
        {
            get
            {
                return longitude;
            }
            set
            {
                longitude = value;
            }
        }

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

    }//end Accommodation

}//end namespace System


text:
<?php

namespace Eloquent\Dumpling\Mysql\Client;

/**
 * Creates MySQL clients.
 */
class MysqlClientFactory implements MysqlClientFactoryInterface
{
    /**
     * Create a new MySQL client.
     *
     * @param string|null  $username The user to connect as.
     * @param string|null  $password The password for the user.
     * @param string|null  $host     The hostname or IP address of the server.
     * @param integer|null $port     The port of the server.
     *
     * @return MysqlClientInterface The new MySQL client.
     */
    public function create(
        $username = null,
        $password = null,
        $host = null,
        $port = null
    ) {
        return new MysqlClient($username, $password, $host, $port);
    }
}


text:
<?php
$startu = strtotime($this->eventdatetime->starttime);
$endu = strtotime($this->eventdatetime->endtime);
?>
<item>
	<title><?php echo UNL_UCBCN_Frontend::dbStringToHtml($this->event->title); ?></title>
	<link><?php echo $this->url; ?></link>
	<description>
		<?php
		echo '
'.UNL_UCBCN_Frontend::dbStringToHtml(strip_tags($this->event->description)).'
';
		if (isset($this->event->subtitle)) echo '
'.UNL_UCBCN_Frontend::dbStringToHtml($this->event->subtitle).'
';
		echo ''.date('l, F jS', $startu).'';

		if (isset($this->eventdatetime->starttime)) {
			if (strpos($this->eventdatetime->starttime,'00:00:00')) {
				echo ' | All day';
			} else {
	        	echo ' | '.date('g:i a', $startu).'';
			}
	    } else {
	        echo 'Unknown';
	    }
	    if (isset($this->eventdatetime->endtime) &&
	    	($this->eventdatetime->endtime != $this->eventdatetime->starttime) &&
	    	($this->eventdatetime->endtime > $this->eventdatetime->starttime)) {
	    	echo '-'.date('g:i a', $endu).'';
	    }
		if ($this->eventdatetime->location_id) {
		    $loc = $this->eventdatetime->getLink('location_id');
			echo ' | '.UNL_UCBCN_Frontend::dbStringToHtml($loc->name);
			if (isset($this->eventdatetime->room)) {
			    echo ' Room:'.UNL_UCBCN_Frontend::dbStringToHtml($this->eventdatetime->room);
			}
			echo '';
		} ?>
	</description>
	<pubDate><?php echo date('r',strtotime($this->event->datecreated)); ?></pubDate>
	<guid><?php echo $this->url; ?></guid>
</item>


text:
FOUNDATION_EXPORT double TesseractOCRVersionNumber;

//! Project version string for TesseractOCR.
FOUNDATION_EXPORT const unsigned char TesseractOCRVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <TesseractOCR/PublicHeader.h>
#ifndef Tesseract_OCR_iOS_TesseractOCR_h
#define Tesseract_OCR_iOS_TesseractOCR_h

#import "MGTesseract.h"
#import "MGRecognizedBlock.h"
#import "MGTesseractParameters.h"
#import "MGRecognitionOperation.h"
#import "MGConstants.h"
#import "UIImage+Filters.h"

#ifdef __cplusplus
#include <stdio.h>
#include <baseapi.h>
#include <renderer.h>
#include <allheaders.h>
#include <pix.h>
#endif

#endif