text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Grain Directory | Microsoft Orleans Documentation </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Grain Directory | Microsoft Orleans Documentation ">
    <meta name="generator" content="docfx 2">

    <link rel="shortcut icon" href="../../favicon.ico">
    <link rel="stylesheet" href="../../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../../styles/docfx.css">
    <link rel="stylesheet" href="../../styles/main.css">
    <meta property="docfx:navrel" content="../../toc.html">
    <meta property="docfx:tocrel" content="../toc.html">

    <meta property="docfx:rel" content="../../">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

Search Results for

          Show / Hide Table of Contents

Grain Directory

What is the Grain Directory?

Grains have stable logical identities and may get activated (instantiated) and deactivated many times over the life of the application, but at most one activation of grain exist at any point in time.
Each time a grain gets activated, it may be placed on a different silo in the cluster.
When a grain gets activated in the cluster, it gets registered in the global registry, Grain Directory.
This ensures that subsequent invocations of that grain will be delivered to that activation of the grain, and that no other activations (instances) of that grain will be created.
Grain Directory is responsible for keeping a mapping between a grain identity and where (which silo) its current activation is at.

By default, Orleans uses a built-in distributed in-memory directory.
This directory is eventually consistent and partitioned across all silos in the cluster in a form of a Distributed Hash Table.

Starting with 3.2.0, Orleans also supports pluggable implementations of Grain Directory.

Two such plugins are included in the 3.2.0 release:

an Azure Table implementation: Microsoft.Orleans.GrainDirectory.AzureStorage (beta)

a Redis Store implementation: Microsoft.Orleans.GrainDirectory.Redis (beta)

You can configure which Grain Directory implementation to use on a per-grain type basis, and you can even inject your own implementation.

Which Grain Directory should you use?

We recommend to always start with the default one (built-in in-memory distributed directory).
Even though it is eventually consistent and allows for occasional duplicate activation when cluster is unstable, the built-in directory is self-sufficient with no external dependencies, does not requires any configuration, and has been used in production the whole time.
When you have some experience with Orleans and have a use case for Grain Directory a with stronger single-activation guarantee and/or want to minimize the number of grain that get deactivated when a silo in the cluster shuts down, consider using a storage-based implementation of Grain Directory, such as the Redis implementation.
Try using it for one or a few grain types first, starting with those that are long-lived and have a significant amount of state or an expensive initialization process.

Configuration

Default Grain Directory configuration

You don't have do to anything; the in-memory grain directory will be automatically used and partitioned across the cluster.

Non-default Grain Directory configuration

You need to specify name of the directory plugin to use via an attribute on the grain class and inject the directory plugin with that name during the silo configuration.

Grain configuration

Specifying the Grain Directory plugin name with the GrainDirectory attribute:

[GrainDirectory(GrainDirectoryName = "my-grain-directory")]
public class MyGrain : Grain, IMyGrain
{
    [...]
}

Silo Configuration

Here we configure the Redis Grain Directory implementation:

siloBuilder.AddRedisGrainDirectory(
    "my-grain-directory",
    options => options.ConfigurationOptions = redisConfiguration);

The Azure Grain Directory is configured like this:

siloBuilder.AddAzureTableGrainDirectory(
    "my-grain-directory",
    options => options.ConnectionString =  = azureConnectionString);

You can configure multiple directories with different names to use for different grain classes:

siloBuilder
    .AddRedisGrainDirectory(
        "redis-directory-1",
        options => options.ConfigurationOptions = redisConfiguration1)
    .AddRedisGrainDirectory(
        "redis-directory-2",
        options => options.ConfigurationOptions = redisConfiguration2)
    .AddAzureTableGrainDirectory(
        "azure-directory",
        options => options.ConnectionString =  = azureConnectionString);

                    Improve this Doc

In This Article

              Back to top

            Generated by DocFX

redpajama_set_name: RedPajamaGithub


text:
package me.apidoc.swagger.translators

import me.apidoc.swagger.Util
import com.bryzek.apidoc.spec.v0.{ models => apidoc }
import com.wordnik.swagger.{ models => swagger }

object Resource {

  def apply(
    resolver: Resolver,
    model: apidoc.Model,
    url: String,
    path: swagger.Path
  ): apidoc.Resource = {
    // getVendorExtensions
    // getParameters

    apidoc.Resource(
      `type` = model.name,
      plural = model.plural,
      path = None,
      description = None,
      deprecation = None,
      operations = Seq(
        Option(path.getGet).map { Operation(resolver, apidoc.Method.Get, url, _) },
        Option(path.getPost).map { Operation(resolver, apidoc.Method.Post, url, _) },
        Option(path.getPut).map { Operation(resolver, apidoc.Method.Put, url, _) },
        Option(path.getDelete).map { Operation(resolver, apidoc.Method.Delete, url, _) },
        Option(path.getOptions).map { Operation(resolver, apidoc.Method.Options, url, _) },
        Option(path.getPatch).map { Operation(resolver, apidoc.Method.Patch, url, _) }
      ).flatten
    )
  }

  def mergeAll(resources: Seq[apidoc.Resource]): Seq[apidoc.Resource] = {
    resources.groupBy(_.`type`).flatMap {
      case (resourceType, resources) => {
        resources.toList match {
          case Nil => Nil
          case resource :: Nil => Seq(resource)
          case r1 :: r2 :: Nil => Seq(merge(r1, r2))
          case r1 :: r2 :: rest => mergeAll(Seq(merge(r1, r2)) ++ rest)
        }
      }
    }.toSeq
  }

  def merge(r1: apidoc.Resource, r2: apidoc.Resource): apidoc.Resource = {
    r1.copy(
      description = Util.choose(r1.description, r2.description),
      deprecation = Util.choose(r1.deprecation, r2.deprecation),
      operations = r1.operations ++ r2.operations
    )
  }

}


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 2000
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Conrad Carlen conrad@ingress.com
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

/**
 * Defines the property names for directories available from
 * nsIDirectoryService. These dirs are always available even if no
 * nsIDirectoryServiceProviders have been registered with the service.
 * Application level keys are defined in nsAppDirectoryServiceDefs.h.
 *
 * Keys whose definition ends in "DIR" or "FILE" return a single nsIFile (or
 * subclass). Keys whose definition ends in "LIST" return an nsISimpleEnumerator
 * which enumerates a list of file objects.
 *
 * Defines listed in this file are FROZEN.  This list may grow.
 */

#ifndef nsDirectoryServiceDefs_h___
#define nsDirectoryServiceDefs_h___

/* General OS specific locations */

#define NS_OS_HOME_DIR                          "Home"
#define NS_OS_TEMP_DIR                          "TmpD"
#define NS_OS_CURRENT_WORKING_DIR               "CurWorkD"

/* Property returns the directory in which the procces was started from.
 * On Unix this will be the path in the VBOX_XPCOM_HOME env var and if
 * unset will be the current working directory.
 */
#define NS_OS_CURRENT_PROCESS_DIR               "CurProcD"

/* This location is similar to NS_OS_CURRENT_PROCESS_DIR, however,
 * NS_XPCOM_CURRENT_PROCESS_DIR can be overriden by passing a "bin
 * directory" to NS_InitXPCOM2().
 */
#define NS_XPCOM_CURRENT_PROCESS_DIR            "XCurProcD"

/* Property will return the location of the application components
 * directory.  By default, this directory will be contained in the
 * NS_XPCOM_CURRENT_PROCESS_DIR.
 */
#define NS_XPCOM_COMPONENT_DIR                  "ComsD"

/* Property will return a list of components directories that will
 * will be registered after the application components directory.
 */
#define NS_XPCOM_COMPONENT_DIR_LIST             "ComsDL"

/* Property will return the location of the application components
 * registry file.
 */
#define NS_XPCOM_COMPONENT_REGISTRY_FILE        "ComRegF"

/* Property will return the location of the application XPTI
 * registry file.
 */
#define NS_XPCOM_XPTI_REGISTRY_FILE             "XptiRegF"

/* Property will return the location of the the XPCOM Shared Library.
 */
#define NS_XPCOM_LIBRARY_FILE                   "XpcomLib"

/* Property will return the current location of the the GRE directory.
 * If no GRE is used, this propery will behave like
 * NS_XPCOM_CURRENT_PROCESS_DIR.
 */
#define NS_GRE_DIR                              "GreD"

/* Property will return the current location of the the GRE component
 * directory.  If no GRE is used, this propery will behave like
 * NS_XPCOM_COMPONENT_DIR.
 */
#define NS_GRE_COMPONENT_DIR                    "GreComsD"

/* Platform Specific Locations */

#if !defined (XP_UNIX) || defined(XP_MACOSX)
    #define NS_OS_SYSTEM_DIR                    "SysD"
#endif

#if defined (XP_MACOSX)
    #define NS_MAC_DESKTOP_DIR                  "Desk"
    #define NS_MAC_TRASH_DIR                    "Trsh"
    #define NS_MAC_STARTUP_DIR                  "Strt"
    #define NS_MAC_SHUTDOWN_DIR                 "Shdwn"
    #define NS_MAC_APPLE_MENU_DIR               "ApplMenu"
    #define NS_MAC_CONTROL_PANELS_DIR           "CntlPnl"
    #define NS_MAC_EXTENSIONS_DIR               "Exts"
    #define NS_MAC_FONTS_DIR                    "Fnts"
    #define NS_MAC_PREFS_DIR                    "Prfs"
    #define NS_MAC_DOCUMENTS_DIR                "Docs"
    #define NS_MAC_INTERNET_SEARCH_DIR          "ISrch"
    #define NS_OSX_HOME_DIR                     "Home"
    #define NS_MAC_HOME_DIR                     NS_OSX_HOME_DIR
    #define NS_MAC_DEFAULT_DOWNLOAD_DIR         "DfltDwnld"
    #define NS_MAC_USER_LIB_DIR                 "ULibDir"   // Only available under OS X
    #define NS_OSX_DEFAULT_DOWNLOAD_DIR         NS_MAC_DEFAULT_DOWNLOAD_DIR
    #define NS_OSX_USER_DESKTOP_DIR             "UsrDsk"
    #define NS_OSX_LOCAL_DESKTOP_DIR            "LocDsk"
    #define NS_OSX_USER_APPLICATIONS_DIR        "UsrApp"
    #define NS_OSX_LOCAL_APPLICATIONS_DIR       "LocApp"
    #define NS_OSX_USER_DOCUMENTS_DIR           "UsrDocs"
    #define NS_OSX_LOCAL_DOCUMENTS_DIR          "LocDocs"
    #define NS_OSX_USER_INTERNET_PLUGIN_DIR     "UsrIntrntPlgn"
    #define NS_OSX_LOCAL_INTERNET_PLUGIN_DIR    "LoclIntrntPlgn"
    #define NS_OSX_USER_FRAMEWORKS_DIR          "UsrFrmwrks"
    #define NS_OSX_LOCAL_FRAMEWORKS_DIR         "LocFrmwrks"
    #define NS_OSX_USER_PREFERENCES_DIR         "UsrPrfs"
    #define NS_OSX_LOCAL_PREFERENCES_DIR        "LocPrfs"
    #define NS_OSX_PICTURE_DOCUMENTS_DIR        "Pct"
    #define NS_OSX_MOVIE_DOCUMENTS_DIR          "Mov"
    #define NS_OSX_MUSIC_DOCUMENTS_DIR          "Music"
    #define NS_OSX_INTERNET_SITES_DIR           "IntrntSts"
#elif defined (XP_WIN)
    #define NS_WIN_WINDOWS_DIR                  "WinD"
    #define NS_WIN_HOME_DIR                     "Home"
    #define NS_WIN_DESKTOP_DIR                  "DeskV" // virtual folder at the root of the namespace
    #define NS_WIN_PROGRAMS_DIR                 "Progs"
    #define NS_WIN_CONTROLS_DIR                 "Cntls"
    #define NS_WIN_PRINTERS_DIR                 "Prnts"
    #define NS_WIN_PERSONAL_DIR                 "Pers"
    #define NS_WIN_FAVORITES_DIR                "Favs"
    #define NS_WIN_STARTUP_DIR                  "Strt"
    #define NS_WIN_RECENT_DIR                   "Rcnt"
    #define NS_WIN_SEND_TO_DIR                  "SndTo"
    #define NS_WIN_BITBUCKET_DIR                "Buckt"
    #define NS_WIN_STARTMENU_DIR                "Strt"
    #define NS_WIN_DESKTOP_DIRECTORY            "DeskP" // file sys dir which physically stores objects on desktop
    #define NS_WIN_DRIVES_DIR                   "Drivs"
    #define NS_WIN_NETWORK_DIR                  "NetW"
    #define NS_WIN_NETHOOD_DIR                  "netH"
    #define NS_WIN_FONTS_DIR                    "Fnts"
    #define NS_WIN_TEMPLATES_DIR                "Tmpls"
    #define NS_WIN_COMMON_STARTMENU_DIR         "CmStrt"
    #define NS_WIN_COMMON_PROGRAMS_DIR          "CmPrgs"
    #define NS_WIN_COMMON_STARTUP_DIR           "CmStrt"
    #define NS_WIN_COMMON_DESKTOP_DIRECTORY     "CmDeskP"
    #define NS_WIN_APPDATA_DIR                  "AppData"
    #define NS_WIN_PRINTHOOD                    "PrntHd"
    #define NS_WIN_COOKIES_DIR                  "CookD"
#elif defined (XP_UNIX)
    #define NS_UNIX_LOCAL_DIR                   "Locl"
    #define NS_UNIX_LIB_DIR                     "LibD"
    #define NS_UNIX_HOME_DIR                    "Home"
#elif defined (XP_OS2)
    #define NS_OS2_DIR                          "OS2Dir"
    #define NS_OS2_HOME_DIR                     "Home"
    #define NS_OS2_DESKTOP_DIR                  "Desk"
#elif defined (XP_BEOS)
    #define NS_BEOS_SETTINGS_DIR                "Setngs"
    #define NS_BEOS_HOME_DIR                    "Home"
    #define NS_BEOS_DESKTOP_DIR                 "Desk"
#endif

/* Deprecated */

#define NS_OS_DRIVE_DIR                         "DrvD"

#endif


text:
<?xml version="1.0" encoding="UTF-8" ?>
<Hyak>
  <Assembly>Microsoft.WindowsAzure.Management.CloudServices.Specification.dll</Assembly>
  <OutputDirectory>Generated</OutputDirectory>

  <Specification>
    <Type>Microsoft.WindowsAzure.Management.Scheduler.CloudServiceManagementClient</Type>

    <Platform>
      <Flavor>CSharp.Azure</Flavor>
      <OutputDirectory></OutputDirectory>
      <BaseNamespace>microsoft.windowsazure.management.scheduler</BaseNamespace>
      <Split>Namespace</Split>
    </Platform>
  </Specification>
</Hyak>


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('campaigns', '0002_auto_20150318_1926'),
    ]

    operations = [
        migrations.AlterField(
            model_name='campaignpixel',
            name='pixel_type',
            field=models.IntegerField(default=0, choices=[(0, b'Listing'), (1, b'Detail')]),
        ),
    ]


text:
\chapter{Wissensdomäne}
\label{chap:wissensdomäne}
Wie sich in der Vorarbeit herausgestellt hat, ist es notwendig die Domäne, in welcher Anfragen gestellt werden sollen, sehr detailliert abzubilden. Zudem ist die technische Umsetzung der Suche mittels Apache Stanbol weniger weit ausgearbeitet als ursprünglich angenommen.

Um die Komplexität in einem angemessenen Rahmen zu halten, gilt es die Entitäten, also die Modellierung der Umwelt, stark einzuschränken.

Als Folge dieser Erkenntnisse wird die Wissendomäne, mit welcher gearbeitet wird, eingeschränkt. Bei der gewählten Domäne handelt es sich um die Grundlagen der Programmierung am Beispiel der Programmiersprache Java.

Dies erlaubt es, dass der Aufbau der Wissensdatenbank überschaubar bleibt, hat aber den Nachteil, dass nur eine beschränkte Anzahl von Fragestellungen beantwortet werden können.


text:
package metadata

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestIntType_validate(t *testing.T) {
	test := &IntType{}
	assert.NotNil(t, test.validate("sample"))
	assert.Nil(t, test.validate("1000"))

}

func TestIntType_get(t *testing.T) {
	test := &IntType{}
	result, _ := test.get("1000")
	assert.IsType(t, result, 1000)
}

func TestStringType_get(t *testing.T) {
	test := &StringType{}
	result, _ := test.get("1000")
	assert.IsType(t, result, "sample")
}

func TestStringType_validate(t *testing.T) {
	test := &StringType{}
	assert.Nil(t, test.validate("sample"))
}

func TestLdapScopeType_validate(t *testing.T) {
	test := &LdapScopeType{}
	assert.NotNil(t, test.validate("3"))
	assert.Nil(t, test.validate("2"))
}

func TestInt64Type_validate(t *testing.T) {
	test := &Int64Type{}
	assert.NotNil(t, test.validate("sample"))
	assert.Nil(t, test.validate("1000"))
}

func TestInt64Type_get(t *testing.T) {
	test := &Int64Type{}
	result, _ := test.get("32")
	assert.Equal(t, result, int64(32))
}

func TestBoolType_validate(t *testing.T) {
	test := &BoolType{}
	assert.NotNil(t, test.validate("sample"))
	assert.Nil(t, test.validate("True"))
}

func TestBoolType_get(t *testing.T) {
	test := &BoolType{}
	result, _ := test.get("true")
	assert.Equal(t, result, true)
	result, _ = test.get("false")
	assert.Equal(t, result, false)
}

func TestPasswordType_validate(t *testing.T) {
	test := &PasswordType{}
	assert.Nil(t, test.validate("zhu88jie"))
}

func TestPasswordType_get(t *testing.T) {
	test := &PasswordType{}
	assert.Nil(t, test.validate("zhu88jie"))
}

func TestMapType_validate(t *testing.T) {
	test := &MapType{}
	assert.Nil(t, test.validate(`{"sample":"abc", "another":"welcome"}`))
	assert.NotNil(t, test.validate(`{"sample":"abc", "another":"welcome"`))
}

func TestMapType_get(t *testing.T) {
	test := &MapType{}
	result, _ := test.get(`{"sample":"abc", "another":"welcome"}`)
	assert.Equal(t, map[string]interface{}{"sample": "abc", "another": "welcome"}, result)
}

func TestStringToStringMapType_validate(t *testing.T) {
	test := &StringToStringMapType{}
	assert.Nil(t, test.validate(`{"sample":"abc", "another":"welcome"}`))
	assert.NotNil(t, test.validate(`{"sample":"abc", "another":123}`))
}

func TestStringToStringMapType_get(t *testing.T) {
	test := &StringToStringMapType{}
	result, _ := test.get(`{"sample":"abc", "another":"welcome"}`)
	assert.Equal(t, map[string]string{"sample": "abc", "another": "welcome"}, result)
}

func Test_parseInt64(t *testing.T) {
	type args struct {
		str string
	}
	tests := []struct {
		name    string
		args    args
		want    int64
		wantErr bool
	}{
		{"1", args{"1"}, int64(1), false},
		{"1.0", args{"1.0"}, int64(1), false},
		{"1.1", args{"1.1"}, int64(0), true},
		{"1E2", args{"1E2"}, int64(100), false},
		{"1.073741824e+11", args{"1.073741824e+11"}, int64(107374182400), false},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := parseInt64(tt.args.str)
			if (err != nil) != tt.wantErr {
				t.Errorf("parseInt64() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if got != tt.want {
				t.Errorf("parseInt64() = %v, want %v", got, tt.want)
			}
		})
	}
}


text:
package com.freetymekiyan.algorithms.level.medium;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 399. Evaluate Division
 *

 * Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real
 * number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.
 *

 * Example:
 * Given a / b = 2.0, b / c = 3.0.
 * queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
 * return [6.0, 0.5, -1.0, 1.0, -1.0 ].
 *

 * The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries ,
 * where equations.size() == values.size(), and the values are positive. This represents the equations. Return
 * vector<double>.
 *

 * According to the example above:
 *

 * equations = [ ["a", "b"], ["b", "c"] ],
 * values = [2.0, 3.0],
 * queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].
 *

 *

 * The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is
 * no contradiction.
 *

 * Companies: Google, Bloomberg, Uber, Amazon, Facebook, Adobe
 *

 * Related Topics: Union Find, Graph
 */
public class EvaluateDivision {

  public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
    Map<String, List<String>> pairs = new HashMap<>();
    Map<String, List<Double>> valuesPair = new HashMap<>();
    for (int i = 0; i < equations.length; i++) {
      String[] equation = equations[i];
      if (!pairs.containsKey(equation[0])) {
        pairs.put(equation[0], new ArrayList<>());
        valuesPair.put(equation[0], new ArrayList<>());
      }
      if (!pairs.containsKey(equation[1])) {
        pairs.put(equation[1], new ArrayList<>());
        valuesPair.put(equation[1], new ArrayList<>());
      }
      pairs.get(equation[0]).add(equation[1]);
      pairs.get(equation[1]).add(equation[0]);
      valuesPair.get(equation[0]).add(values[i]);
      valuesPair.get(equation[1]).add(1 / values[i]);
    }

    double[] result = new double[queries.length];
    for (int i = 0; i < queries.length; i++) {
      String[] query = queries[i];
      result[i] = dfs(query[0], query[1], pairs, valuesPair, new HashSet<String>(), 1.0);
      if (result[i] == 0.0) result[i] = -1.0;
    }
    return result;
  }

  private double dfs(String start, String end, Map<String, List<String>> pairs, Map<String, List<Double>> values, Set<String> set, double value) {
    if (set.contains(start)) return 0.0;
    if (!pairs.containsKey(start)) return 0.0;
    if (start.equals(end)) return value;
    set.add(start);

    List<String> strList = pairs.get(start);
    List<Double> valueList = values.get(start);
    double tmp = 0.0;
    for (int i = 0; i < strList.size(); i++) {
      tmp = dfs(strList.get(i), end, pairs, values, set, value * valueList.get(i));
      if (tmp != 0.0) {
        break;
      }
    }
    set.remove(start);
    return tmp;
  }
}


text:
@interface TSPlatformImpl : NSObject<TSPlatform> {}

- (NSString *)loadUuid;
- (NSMutableSet *)loadFiredEvents;
- (void)saveFiredEvents:(NSMutableSet *)firedEvents;
- (NSString *)getResolution;
- (NSString *)getManufacturer;
- (NSString *)getModel;
- (NSString *)getOs;
- (NSString *)getLocale;
- (NSString *)getWifiMac;
- (NSString *)getAppName;
- (NSString *)getAppVersion;
- (NSString *)getPackageName;
- (TSResponse *)request:(NSString *)url data:(NSString *)data method:(NSString *)method;
- (NSSet *)getProcessSet;
- (NSString *)getComputerGUID;
- (NSString *)getBundleIdentifier;
- (NSString *)getBundleShortVersion;
@end


text:
class IO;

class Output : public IO
{
public:
	Output() {}

};
//Include user definitions, switch state 1/0 and where it should target
#endif


text:
package com.bastienleonard.tomate.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;

public final class StreamUtils {
    private static final String TAG = "StreamUtil";

    private StreamUtils() {
    }

    public static String inputStreamToString(InputStream stream)
            throws IOException {
        if (stream == null) {
            return null;
        }

        char[] buffer = new char[4096];
        StringWriter writer = new StringWriter();
        InputStreamReader reader = new InputStreamReader(stream);

        try {
            while (true) {
                int bytesRead = reader.read(buffer);

                if (bytesRead == -1) {
                    break;
                }

                if (bytesRead > 0) {
                    writer.write(buffer, 0, bytesRead);
                }
            }
        } finally {
            try {
                writer.close();
                reader.close();
                stream.close();
            } catch (IOException e) {
                LogUtils.e(TAG, e);
            }
        }

        return writer.toString();
    }
}


text:
package cmd

// to be used for the set.go command
// set filename -t=fileType -v=someValue -k=someKey
// set ProductManager -t class -v 35.0 -k version
// set ProductManager -t page -v Inactive -k status
// ...


text:
[![Build Status][build-status-svg]][build-status-link]
[![License][license-svg]][license-link]
[![ktlint][ktlint-svg]][ktlint-link]

app:
[![codecov][coverage-svg-app]][coverage-link]
core:
[![codecov][coverage-svg-core]][coverage-link]

[build-status-svg]: https://travis-ci.org/mateuszwisniewski/Videooo.svg?branch=master
[build-status-link]: https://travis-ci.org/mateuszwisniewski/Videooo
[coverage-svg-app]: https://codecov.io/gh/mateuszwisniewski/Videooo/branch/master/graphs/badge.svg?flag=app
[coverage-svg-core]: https://codecov.io/gh/mateuszwisniewski/Videooo/branch/master/graphs/badge.svg?flag=core
[coverage-link]: https://codecov.io/gh/mateuszwisniewski/Videooo
[license-svg]: https://img.shields.io/badge/License-Apache%202.0-blue.svg
[license-link]: https://github.com/mateuszwisniewski/Videooo/blob/master/LICENSE
[ktlint-link]: hhttps://ktlint.github.io/
[ktlint-svg]: https://img.shields.io/badge/code%20style-%E2%9D%A4-FF4081.svg


text:
Original CodePen: http://codepen.io/AlcidesRC/pen/gafno

Goals of this repo:
 - Inject 'throbbs' dynamically based on a config
 - Store dismissed state for each one in a cookie
 - Allow beforeShow/afterShow/beforeClose/afterClose events so that we can do stuff 'around' the throbbs.
 - Make it work properly with both requirejs/browserify/plainjs


text:
package sqlr

// identMap is used to lookup identifiers that need to be replaced.
// There is no mutex because once a schema has been initialized, its
// identifier map should be immutable.
//
// When a schema is cloned from another schema, its identMap points to
// the identMap of the previous schema.
type identMap struct {
	prev        *identMap // points to the identMap for the previous schema
	identifiers map[string]string
}

func newIdentMap(prev *identMap) *identMap {
	return &identMap{
		prev:        prev,
		identifiers: make(map[string]string),
	}
}

func (im *identMap) add(identifier string, replacement string) {
	im.identifiers[identifier] = replacement
}

// lookup the field name in the field map and return a column name.
// The boolean returns true if there was a match. If there is a match
// and the string is empty, this means to fallback to the naming convention.
func (im *identMap) lookup(identifier string) (string, bool) {
	if replacement, ok := im.identifiers[identifier]; ok {
		return replacement, ok
	}
	if im.prev != nil {
		return im.prev.lookup(identifier)
	}
	return "", false
}


text:
using System.Windows;
using System.Windows.Controls;

namespace AuraPhotoViewer.Styles.CustomControls
{
    public class AuraCircleIconButton : Button
    {
        static AuraCircleIconButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(AuraCircleIconButton), new FrameworkPropertyMetadata(typeof(AuraCircleIconButton)));
        }

        public static readonly DependencyProperty AuraIconTypeProperty = DependencyProperty.Register("AuraIconType", typeof(AuraIconButtonType), typeof(AuraCircleIconButton), new FrameworkPropertyMetadata(AuraIconButtonType.NavigateBefore));

        public AuraIconButtonType AuraIconType
        {
            get
            {
                return (AuraIconButtonType)GetValue(AuraIconTypeProperty);
            }
            set
            {
                SetValue(AuraIconTypeProperty, value);
            }
        }
    }
}


text:
package org.apache.maven.continuum.execution.shared;

import org.apache.continuum.utils.file.FileSystemManager;
import org.codehaus.plexus.util.DirectoryScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

public class JUnitReportArchiver
{
    private static Logger log = LoggerFactory.getLogger( JUnitReportArchiver.class );

    private String[] includeFiles = {};

    private String[] excludeFiles = {};

    private FileSystemManager fsManager;

    public void setIncludeFiles( String[] includeFiles )
    {
        this.includeFiles = includeFiles;
    }

    public void setExcludeFiles( String[] excludeFiles )
    {
        this.excludeFiles = excludeFiles;
    }

    public void setFileSystemManager( FileSystemManager fsManager )
    {
        this.fsManager = fsManager;
    }

    public String[] findReports( File workingDir )
    {
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir( workingDir );
        scanner.setIncludes( includeFiles );
        scanner.setExcludes( excludeFiles );
        scanner.scan();
        return scanner.getIncludedFiles();
    }

    public void archiveReports( File workingDir, File backupDir )
        throws IOException
    {
        String[] testResultFiles = findReports( workingDir );
        if ( testResultFiles.length > 0 )
        {
            log.info( "Backing up {} test reports", testResultFiles.length );
        }
        for ( String testResultFile : testResultFiles )
        {
            File xmlFile = new File( workingDir, testResultFile );
            if ( backupDir != null )
            {
                fsManager.copyFileToDir( xmlFile, backupDir );
            }
        }
    }
}


text:
package org.quicktheories.highlevel;
import static org.junit.Assert.assertTrue;

import java.util.Date;

import org.junit.Test;
import org.quicktheories.WithQuickTheories;

public class DatesComponentTest extends ComponentTest<Date> implements WithQuickTheories {

    @Test
    public void shouldShrinkToEpoch() {
      assertThatFor(dates().withMilliseconds(53252224233L)).check(i -> false);
      listIsInDecreasingValueOrder();
      smallestValueIsEqualTo(new Date(0));
    }

    @Test
    public void shouldShrinkToEpochWhenBetweenEpochs() {
      assertThatFor(dates().withMillisecondsBetween(0, 0)).check(i -> false);
      smallestValueIsEqualTo(new Date(0));
    }

    @Test
    public void shouldShrinkToSmallestDateWhenBetween() {
      assertThatFor(dates().withMillisecondsBetween(32523, 789709709780952L)).check(i -> false);
      listIsInDecreasingValueOrder();
      smallestValueIsEqualTo(new Date(32523));
    }

    private void listIsInDecreasingValueOrder() {
      for (int i = 1; i < listOfShrunkenItems().size(); i++) {
        assertTrue(
            "Expected " + (listOfShrunkenItems().get(i - 1))
                + " to be bigger than " + (listOfShrunkenItems().get(i)),
            listOfShrunkenItems().get(i - 1)
                .compareTo(listOfShrunkenItems().get(i)) >= 0);
      }
    }

    private void smallestValueIsEqualTo(Date target) {
      assertTrue(
          "Expected " + smallestValueFound() + " to be equal to " + target,
          (target.compareTo(smallestValueFound()) == 0));
    }

  }


text:
using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T m_Instance;
    private static object m_Lock = new object();
    private static bool m_ApplicationIsQuitting = false;

    public static T Instance
    {
        get
        {
            if (m_ApplicationIsQuitting)
            {
                Debug.LogWarning("[Singleton] Instance '" + typeof(T) +
                    "' already destroyed on application quit." +
                    " Won't create again - returning null.");
                return null;
            }

            lock (m_Lock)
            {
                if (m_Instance == null)
                {
                    m_Instance = (T)FindObjectOfType(typeof(T));

                    if (FindObjectsOfType(typeof(T)).Length > 1)
                    {
                        Debug.LogError("[Singleton] Something went really wrong " +
                            " - there should never be more than 1 singleton!" +
                            " Reopenning the scene might fix it.");
                        return m_Instance;
                    }

                    if (m_Instance == null)
                    {
                        GameObject singleton = new GameObject();
                        m_Instance = singleton.AddComponent<T>();
                        singleton.name = typeof(T).ToString();
                        DontDestroyOnLoad(singleton);

                        Debug.Log("[Singleton] An instance of " + typeof(T) +
                            " is needed in the scene, so '" + singleton +
                            "' was created with DontDestroyOnLoad.");
                    }
                    else
                    {
                        Debug.Log("[Singleton] Using instance already created: " +
                            m_Instance.gameObject.name);
                    }
                }

                return m_Instance;
            }
        }
    }

    public void OnDestroy()
    {
        m_ApplicationIsQuitting = true;
    }
}


text: anyenv for homebrew


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Deutschl. Krypt. -Fl. (Leipzig) 1: 132 (1844)

#### Original name
Mucor castaneae Rabenh.

### Remarks
null


text:
package org.pentaho.di.engine.ui;

import org.apache.commons.lang.StringUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.base.AbstractMeta;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.engine.configuration.api.RunConfiguration;
import org.pentaho.di.engine.configuration.api.RunConfigurationService;
import org.pentaho.di.engine.configuration.api.RunOption;
import org.pentaho.di.engine.configuration.impl.pentaho.DefaultRunConfiguration;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.ui.core.ConstUI;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.pentaho.di.ui.util.SwtSvgImageUtil;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

/**
 * Created by bmorrise on 3/15/17.
 */
public class RunConfigurationDialog extends Dialog {

  private static Class<?> PKG = RunConfigurationDialog.class;
  public static final String CLUSTERED = "Clustered";

  private Supplier<Spoon> spoonSupplier = Spoon::getInstance;

  private Shell shell;

  private PropsUI props;

  private Label wlName;
  private Text wName;

  private Label wlDescription;
  private Text wDescription;

  private Label wlEngine;
  private CCombo wEngine;

  private Group gOptions;

  private Button wCancel;

  private Button wOK;

  private RunConfiguration runConfiguration;
  private RunConfiguration savedRunConfiguration;
  private Map<String, RunConfiguration> runConfigurationMap = new HashMap<>();

  private RunConfigurationService executionConfigurationManager;

  public RunConfigurationDialog( Shell parent, RunConfigurationService executionConfigurationManager,
                                 RunConfiguration runConfiguration ) {
    super( parent, SWT.NONE );
    this.props = PropsUI.getInstance();
    this.executionConfigurationManager = executionConfigurationManager;
    this.runConfiguration = runConfiguration;
    if ( runConfiguration != null ) {
      this.runConfigurationMap.put( runConfiguration.getType(), runConfiguration );
    }
  }

  public RunConfiguration open() {
    Shell parent = getParent();
    Display display = parent.getDisplay();

    shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX );
    props.setLook( shell );

    FormLayout formLayout = new FormLayout();
    formLayout.marginWidth = 15;
    formLayout.marginHeight = 15;

    shell.setLayout( formLayout );
    shell.setText( BaseMessages.getString( PKG, "RunConfigurationDialog.Title" ) );
    shell.setImage( getImage() );

    Composite wSettings = new Composite( shell, SWT.SHADOW_NONE );
    props.setLook( wSettings );

    FormLayout specLayout = new FormLayout();
    specLayout.marginWidth = 0;
    specLayout.marginHeight = 0;
    wSettings.setLayout( specLayout );

    wlName = new Label( wSettings, SWT.RIGHT );
    wlName.setText( BaseMessages.getString( PKG, "RunConfigurationDialog.Label.Name" ) );
    props.setLook( wlName );
    FormData fdlName = new FormData();
    fdlName.left = new FormAttachment( 0, 0 );
    fdlName.top = new FormAttachment( 0, 0 );
    wlName.setLayoutData( fdlName );

    wName = new Text( wSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
    props.setLook( wName );
    FormData fdName = new FormData();
    fdName.left = new FormAttachment( 0, 0 );
    fdName.top = new FormAttachment( wlName, 5 );
    fdName.right = new FormAttachment( 100, 0 );
    wName.setLayoutData( fdName );
    wName.addModifyListener( modifyEvent -> {
      runConfiguration.setName( wName.getText() );
      if ( Utils.isEmpty( runConfiguration.getName() ) ) {
        wOK.setEnabled( false );
      } else {
        wOK.setEnabled( true );
      }
    } );

    wlDescription = new Label( wSettings, SWT.RIGHT );
    wlDescription.setText( BaseMessages.getString( PKG, "RunConfigurationDialog.Label.Description" ) );
    props.setLook( wlDescription );
    FormData fdlDescription = new FormData();
    fdlDescription.left = new FormAttachment( 0, 0 );
    fdlDescription.top = new FormAttachment( wName, 10 );
    wlDescription.setLayoutData( fdlDescription );

    wDescription = new Text( wSettings, SWT.MULTI | SWT.LEFT | SWT.BORDER );
    props.setLook( wDescription );
    FormData fdDescription = new FormData();
    fdDescription.height = 40;
    fdDescription.left = new FormAttachment( 0, 0 );
    fdDescription.top = new FormAttachment( wlDescription, 5 );
    fdDescription.right = new FormAttachment( 100, 0 );
    wDescription.setLayoutData( fdDescription );
    wDescription.addModifyListener( modifyEvent -> runConfiguration.setDescription( wDescription.getText() ) );

    wlEngine = new Label( wSettings, SWT.RIGHT );
    wlEngine.setText( BaseMessages.getString( PKG, "RunConfigurationDialog.Label.Engine" ) );
    props.setLook( wlEngine );
    FormData fdlEngine = new FormData();
    fdlEngine.left = new FormAttachment( 0, 0 );
    fdlEngine.top = new FormAttachment( wDescription, 10 );
    wlEngine.setLayoutData( fdlEngine );

    wEngine = new CCombo( wSettings, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER );
    wEngine.setItems( executionConfigurationManager.getTypes() );
    wEngine.addSelectionListener( new SelectionAdapter() {
      @Override public void widgetSelected( SelectionEvent selectionEvent ) {
        String engine = wEngine.getText();
        if ( !engine.equals( runConfiguration.getType() ) ) {
          updateOptions( engine );
        }
      }
    } );
    wEngine.select( 0 );
    props.setLook( wEngine );
    FormData fdEngine = new FormData();
    fdEngine.width = 150;
    fdEngine.left = new FormAttachment( 0, 0 );
    fdEngine.top = new FormAttachment( wlEngine, 5 );
    wEngine.setLayoutData( fdEngine );

    gOptions = new Group( wSettings, SWT.SHADOW_ETCHED_IN );
    gOptions.setText( BaseMessages.getString( PKG, "RunConfigurationDialog.Group.Settings" ) );
    props.setLook( gOptions );

    FormLayout gformLayout = new FormLayout();
    gformLayout.marginWidth = 10;
    gformLayout.marginHeight = 10;
    gOptions.setLayout( gformLayout );

    FormData fdOptions = new FormData();
    fdOptions.top = new FormAttachment( wEngine, 15 );
    fdOptions.right = new FormAttachment( 100 );
    fdOptions.left = new FormAttachment( 0 );
    fdOptions.height = 140;
    gOptions.setLayoutData( fdOptions );

    wCancel = new Button( shell, SWT.PUSH );
    wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) );
    FormData fdCancel = new FormData();
    fdCancel.right = new FormAttachment( 100, 0 );
    fdCancel.bottom = new FormAttachment( 100, 0 );
    wCancel.setLayoutData( fdCancel );

    wOK = new Button( shell, SWT.PUSH );
    wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) );
    FormData fdOk = new FormData();
    fdOk.right = new FormAttachment( wCancel, -5 );
    fdOk.bottom = new FormAttachment( 100, 0 );
    wOK.setLayoutData( fdOk );

    Label hSpacer = new Label( shell, SWT.HORIZONTAL | SWT.SEPARATOR );
    FormData fdhSpacer = new FormData();
    fdhSpacer.height = 1;
    fdhSpacer.left = new FormAttachment( 0, 0 );
    fdhSpacer.bottom = new FormAttachment( wCancel, -15 );
    fdhSpacer.right = new FormAttachment( 100, 0 );
    hSpacer.setLayoutData( fdhSpacer );

    FormData fdSettings = new FormData();
    fdSettings.left = new FormAttachment( 0 );
    fdSettings.top = new FormAttachment( 0 );
    fdSettings.right = new FormAttachment( 100 );
    fdSettings.bottom = new FormAttachment( hSpacer, -15 );
    wSettings.setLayoutData( fdSettings );

    setValues();

    Listener lsCancel = e -> cancel();
    Listener lsOK = e -> ok();

    wOK.addListener( SWT.Selection, lsOK );
    wCancel.addListener( SWT.Selection, lsCancel );

    BaseStepDialog.setSize( shell, 450, 300 );
    shell.setMinimumSize( 450, 300 );
    wName.setSelection( 0, wName.getText().length() );

    // Detect X or ALT-F4 or something that kills this window...
    shell.addShellListener( new ShellAdapter() {
      public void shellClosed( ShellEvent e ) {
        cancel();
      }
    } );

    shell.open();
    while ( !shell.isDisposed() ) {
      if ( !display.readAndDispatch() ) {
        display.sleep();
      }
    }

    return savedRunConfiguration;
  }

  private Image getImage() {
    return SwtSvgImageUtil
      .getImage( shell.getDisplay(), getClass().getClassLoader(), "images/run_tree.svg", ConstUI.ICON_SIZE,
        ConstUI.ICON_SIZE );
  }

  private void setValues() {
    if ( runConfiguration == null ) {
      runConfiguration = executionConfigurationManager.getRunConfigurationByType( DefaultRunConfiguration.TYPE );
      runConfigurationMap.put( DefaultRunConfiguration.TYPE, runConfiguration );
    }

    clearOptions();
    if ( runConfiguration.getType().equals( DefaultRunConfiguration.TYPE ) ) {
      showDefault();
    } else {
      showDynamic();
    }
    gOptions.layout();
    shell.pack();

    wEngine.setText( StringUtils.capitalize( runConfiguration.getType() ) );
    wName.setText( Const.NVL( runConfiguration.getName(), "" ) );
    wDescription.setText( Const.NVL( runConfiguration.getDescription(), "" ) );
  }

  private void clearOptions() {
    for ( Control control : gOptions.getChildren() ) {
      control.dispose();
    }
  }

  private void showDefault() {
    DefaultRunConfiguration defaultRunConfiguration = (DefaultRunConfiguration) runConfiguration;

    Composite wTarget = new Composite( gOptions, SWT.NONE );
    wTarget.setLayout( new FormLayout() );
    props.setLook( wTarget );

    Button wbLocal = new Button( wTarget, SWT.RADIO );
    props.setLook( wbLocal );
    wbLocal.setText( BaseMessages.getString( PKG, "RunConfigurationDialog.Label.Local" ) );
    wbLocal.setSelection( defaultRunConfiguration.isLocal() );
    FormData fdbLocal = new FormData();
    fdbLocal.top = new FormAttachment( 0 );
    fdbLocal.left = new FormAttachment( 0 );
    wbLocal.setLayoutData( fdbLocal );

    Button wbRemote = new Button( wTarget, SWT.RADIO );
    props.setLook( wbRemote );
    wbRemote.setText( BaseMessages.getString( PKG, "RunConfigurationDialog.Label.Remote" ) );
    wbRemote.setSelection( defaultRunConfiguration.isRemote() || defaultRunConfiguration.isClustered() );
    FormData fdbRemote = new FormData();
    fdbRemote.top = new FormAttachment( wbLocal, 5 );
    fdbRemote.left = new FormAttachment( 0 );
    wbRemote.setLayoutData( fdbRemote );

    FormData fdTarget = new FormData();
    fdTarget.left = new FormAttachment( 0 );
    fdTarget.top = new FormAttachment( 0 );
    wTarget.setLayoutData( fdTarget );

    Label vSpacer = new Label( gOptions, SWT.VERTICAL | SWT.SEPARATOR );
    FormData fdvSpacer = new FormData();
    fdvSpacer.width = 1;
    fdvSpacer.left = new FormAttachment( wTarget, 30 );
    fdvSpacer.top = new FormAttachment( 0, 0 );
    fdvSpacer.bottom = new FormAttachment( 100, 0 );
    vSpacer.setLayoutData( fdvSpacer );

    Composite wcLocal = new Composite( gOptions, SWT.NONE );
    props.setLook( wcLocal );
    wcLocal.setLayout( new GridLayout() );

    Text wlLocal = new Text( wcLocal, SWT.MULTI | SWT.WRAP );
    props.setLook( wlLocal );
    wlLocal.setText( BaseMessages.getString( PKG, "RunConfigurationDialog.Text.Local" ) );
    GridData gdlLocal = new GridData( GridData.FILL_HORIZONTAL );
    gdlLocal.widthHint = 200;
    wlLocal.setLayoutData( gdlLocal );

    FormData fdcLocal = new FormData();
    fdcLocal.left = new FormAttachment( vSpacer, 30 );
    fdcLocal.top = new FormAttachment( 0 );
    fdcLocal.right = new FormAttachment( 100 );
    fdcLocal.bottom = new FormAttachment( 100 );
    wcLocal.setLayoutData( fdcLocal );

    Composite wcRemote = new Composite( gOptions, SWT.NONE );
    props.setLook( wcRemote );
    wcRemote.setLayout( new FormLayout() );

    Label wlRemote = new Label( wcRemote, SWT.LEFT );
    props.setLook( wlRemote );
    wlRemote.setText( BaseMessages.getString( PKG, "RunConfigurationDialog.Label.Location" ) );
    FormData fdlRemote = new FormData();
    fdlRemote.left = new FormAttachment( 0 );
    fdlRemote.top = new FormAttachment( 0 );
    wlRemote.setLayoutData( fdlRemote );

    CCombo wcSlaveServer = new CCombo( wcRemote, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER );
    props.setLook( wcSlaveServer );
    FormData fdSlaveServer = new FormData();
    fdSlaveServer.width = 150;
    fdSlaveServer.top = new FormAttachment( wlRemote, 5 );
    fdSlaveServer.left = new FormAttachment( 0 );
    wcSlaveServer.setLayoutData( fdSlaveServer );

    Button wbSendResources = new Button( wcRemote, SWT.CHECK );
    wbSendResources.setSelection( defaultRunConfiguration.isSendResources() );
    wbSendResources
      .setVisible( !Utils.isEmpty( defaultRunConfiguration.getServer() ) && !defaultRunConfiguration.isClustered() );
    props.setLook( wbSendResources );
    wbSendResources.setText( BaseMessages.getString( PKG, "RunConfigurationDialog.Button.SendResources" ) );
    FormData fdbSendResources = new FormData();
    fdbSendResources.top = new FormAttachment( wcSlaveServer, 10 );
    fdbSendResources.left = new FormAttachment( 0 );
    wbSendResources.setLayoutData( fdbSendResources );
    wbSendResources.addSelectionListener( new SelectionAdapter() {
      @Override public void widgetSelected( SelectionEvent selectionEvent ) {
        defaultRunConfiguration.setSendResources( wbSendResources.getSelection() );
      }
    } );

    Button wbLogRemoteExecutionLocally = new Button( wcRemote, SWT.CHECK );
    wbLogRemoteExecutionLocally.setSelection( defaultRunConfiguration.isLogRemoteExecutionLocally() );
    wbLogRemoteExecutionLocally.setVisible( defaultRunConfiguration.isClustered() );
    props.setLook( wbLogRemoteExecutionLocally );
    wbLogRemoteExecutionLocally
      .setText( BaseMessages.getString( PKG, "RunConfigurationDialog.Checkbox.LogRemoteExecutionLocally" ) );
    FormData fdbLogRemoteExecutionLocally = new FormData();
    fdbLogRemoteExecutionLocally.top = new FormAttachment( wcSlaveServer, 10 );
    fdbLogRemoteExecutionLocally.left = new FormAttachment( 0 );
    wbLogRemoteExecutionLocally.setLayoutData( fdbLogRemoteExecutionLocally );
    wbLogRemoteExecutionLocally.addSelectionListener( new SelectionAdapter() {
      @Override public void widgetSelected( SelectionEvent selectionEvent ) {
        defaultRunConfiguration.setLogRemoteExecutionLocally( wbLogRemoteExecutionLocally.getSelection() );
      }
    } );

    Button wbShowTransformations = new Button( wcRemote, SWT.CHECK );
    wbShowTransformations.setSelection( defaultRunConfiguration.isShowTransformations() );
    wbShowTransformations.setVisible( defaultRunConfiguration.isClustered() );
    props.setLook( wbShowTransformations );
    wbShowTransformations
      .setText( BaseMessages.getString( PKG, "RunConfigurationDialog.Checkbox.ShowTransformation" ) );
    FormData fdbShowTransformations = new FormData();
    fdbShowTransformations.top = new FormAttachment( wbLogRemoteExecutionLocally, 10 );
    fdbShowTransformations.left = new FormAttachment( 0 );
    wbShowTransformations.setLayoutData( fdbShowTransformations );
    wbShowTransformations.addSelectionListener( new SelectionAdapter() {
      @Override public void widgetSelected( SelectionEvent selectionEvent ) {
        defaultRunConfiguration.setShowTransformations( wbShowTransformations.getSelection() );
      }
    } );

    FormData fdcRemote = new FormData();
    fdcRemote.left = new FormAttachment( vSpacer, 30 );
    fdcRemote.top = new FormAttachment( 0 );
    fdcRemote.right = new FormAttachment( 100 );
    fdcRemote.bottom = new FormAttachment( 100 );
    wcRemote.setLayoutData( fdcRemote );

    AbstractMeta meta = (AbstractMeta) spoonSupplier.get().getActiveMeta();

    if ( meta instanceof TransMeta && !Utils.isEmpty( ( (TransMeta) meta ).getClusterSchemas() ) ) {
      wcSlaveServer.add( CLUSTERED );
    }

    for ( int i = 0; i < meta.getSlaveServers().size(); i++ ) {
      SlaveServer slaveServer = meta.getSlaveServers().get( i );
      wcSlaveServer.add( slaveServer.toString() );
    }

    if ( !Utils.isEmpty( defaultRunConfiguration.getServer() ) ) {
      wcSlaveServer.setText( defaultRunConfiguration.getServer() );
    }

    wcLocal.setVisible( defaultRunConfiguration.isLocal() );
    wcRemote.setVisible( defaultRunConfiguration.isRemote() || defaultRunConfiguration.isClustered() );

    wcSlaveServer.addSelectionListener( new SelectionAdapter() {
      @Override public void widgetSelected( SelectionEvent selectionEvent ) {
        if ( wcSlaveServer.getText().equals( CLUSTERED ) ) {
          defaultRunConfiguration.setClustered( true );
          defaultRunConfiguration.setLocal( false );
          defaultRunConfiguration.setRemote( false );
          wbLogRemoteExecutionLocally.setVisible( true );
          wbShowTransformations.setVisible( true );
          wbSendResources.setVisible( false );
        } else {
          defaultRunConfiguration.setRemote( true );
          defaultRunConfiguration.setLocal( false );
          defaultRunConfiguration.setClustered( false );
          defaultRunConfiguration.setServer( wcSlaveServer.getText() );
          wbLogRemoteExecutionLocally.setVisible( false );
          wbShowTransformations.setVisible( false );
          wbSendResources.setVisible( true );
        }
        checkOKEnabled( defaultRunConfiguration, wcSlaveServer );
      }
    } );

    wbLocal.addSelectionListener( new SelectionAdapter() {
      @Override public void widgetSelected( SelectionEvent selectionEvent ) {
        wcLocal.setVisible( wbLocal.getSelection() );
        wcRemote.setVisible( wbRemote.getSelection() );
        defaultRunConfiguration.setLocal( wbLocal.getSelection() );
        defaultRunConfiguration.setRemote( false );
        defaultRunConfiguration.setClustered( false );
        checkOKEnabled( defaultRunConfiguration, wcSlaveServer );
      }
    } );

    wbRemote.addSelectionListener( new SelectionAdapter() {
      @Override public void widgetSelected( SelectionEvent selectionEvent ) {
        wcLocal.setVisible( wbLocal.getSelection() );
        wcRemote.setVisible( wbRemote.getSelection() );
        defaultRunConfiguration.setLocal( false );
        if ( Utils.isEmpty( wcSlaveServer.getText() ) ) {
          if ( meta instanceof TransMeta && !Utils.isEmpty( ( (TransMeta) meta ).getClusterSchemas() ) ) {
            wcSlaveServer.setText( CLUSTERED );
          } else if ( meta.getSlaveServers().size() > 0 ) {
            wcSlaveServer.setText( meta.getSlaveServers().get( 0 ).getName() );
          }
        }
        if ( !wcSlaveServer.getText().equals( CLUSTERED ) ) {
          defaultRunConfiguration.setRemote( true );
          defaultRunConfiguration.setClustered( false );
          wbSendResources.setVisible( true );
          wbShowTransformations.setVisible( false );
          wbLogRemoteExecutionLocally.setVisible( false );
        } else {
          defaultRunConfiguration.setClustered( true );
          defaultRunConfiguration.setRemote( false );
          wbSendResources.setVisible( false );
          wbShowTransformations.setVisible( true );
          wbLogRemoteExecutionLocally.setVisible( true );
        }
        checkOKEnabled( defaultRunConfiguration, wcSlaveServer );
        if ( !Utils.isEmpty( wcSlaveServer.getText() ) ) {
          defaultRunConfiguration.setServer( wcSlaveServer.getText() );
        }
      }
    } );

    if ( defaultRunConfiguration.isClustered() ) {
      wcSlaveServer.setText( CLUSTERED );
      wbSendResources.setVisible( false );
      wbShowTransformations.setVisible( true );
      wbLogRemoteExecutionLocally.setVisible( true );
    }
  }

  private void checkOKEnabled( DefaultRunConfiguration defaultRunConfiguration, CCombo wcSlaveServer ) {
    if ( ( defaultRunConfiguration.isRemote() && Utils.isEmpty( wcSlaveServer.getText() ) ) || Utils
      .isEmpty( wName.getText() ) ) {
      wOK.setEnabled( false );
    } else {
      wOK.setEnabled( true );
    }
  }

  private void showDynamic() {
    Control lastControl = null;

    for ( Field field : runConfiguration.getClass().getDeclaredFields() ) {
      RunOption runOption = field.getAnnotation( RunOption.class );
      if ( runOption != null ) {
        Label optionLabel = new Label( gOptions, SWT.LEFT );
        props.setLook( optionLabel );
        optionLabel.setText( runOption.label() );
        FormData fdlOption = new FormData();
        fdlOption.left = new FormAttachment( 0 );
        fdlOption.top = lastControl != null ? new FormAttachment( lastControl, 10 ) : new FormAttachment( 0 );
        optionLabel.setLayoutData( fdlOption );

        String value = invokeGetter( runConfiguration, field.getName(), runOption.value() );
        Text optionText = new Text( gOptions, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
        props.setLook( optionText );
        optionText.setText( value );
        FormData fdOption = new FormData();
        fdOption.left = new FormAttachment( 0 );
        fdOption.top = new FormAttachment( optionLabel, 5 );
        fdOption.right = new FormAttachment( 100 );
        optionText.setLayoutData( fdOption );

        invokeSetter( runConfiguration, field.getName(), optionText.getText() );

        optionText.addModifyListener( modifyEvent -> {
          if ( Utils.isEmpty( optionText.getText() ) ) {
            wOK.setEnabled( false );
          } else {
            wOK.setEnabled( true );
          }
          invokeSetter( runConfiguration, field.getName(), optionText.getText() );
        } );

        lastControl = optionText;
      }
    }
  }

  private void invokeSetter( Object object, String fieldName, String value ) {
    try {
      Method method =
        object.getClass().getMethod( "set" + StringUtils.capitalize( fieldName ), String.class );
      if ( method != null ) {
        method.invoke( object, value );
      }
    } catch ( NoSuchMethodException | IllegalAccessException | InvocationTargetException e ) {
      // Ignore exception
    }
  }

  private String invokeGetter( Object object, String fieldName, String defaultValue ) {
    try {
      Method method =
        object.getClass().getMethod( "get" + StringUtils.capitalize( fieldName ) );
      if ( method != null ) {
        String fieldValue = (String) method.invoke( runConfiguration );
        String value = fieldValue != null ? fieldValue : "";
        if ( Utils.isEmpty( value ) && !Utils.isEmpty( defaultValue ) ) {
          return defaultValue;
        }
        return value;
      }
    } catch ( NoSuchMethodException | IllegalAccessException | InvocationTargetException e ) {
      // Ignore exception
    }
    return "";
  }

  private void updateOptions( String type ) {
    RunConfiguration newRunConfiguration = runConfigurationMap.get( type );
    if ( newRunConfiguration == null ) {
      newRunConfiguration = executionConfigurationManager.getRunConfigurationByType( type );
      newRunConfiguration.setName( runConfiguration.getName() );
      newRunConfiguration.setDescription( runConfiguration.getDescription() );
      runConfigurationMap.put( type, newRunConfiguration );
    }
    runConfiguration = newRunConfiguration;
    setValues();
  }

  private void cancel() {
    shell.dispose();
  }

  private void ok() {
    if ( validated() ) {
      save();
      shell.dispose();
    }
  }

  private void save() {
    savedRunConfiguration = runConfiguration;
  }

  private boolean validated() {
    if ( StringUtils.containsAny( wName.getText(), "%\"\\/:[]*|\t\r\n" ) ) {
      MessageBox messageBox = new MessageBox( shell, SWT.ERROR );
      messageBox.setMessage( BaseMessages.getString( PKG, "RunConfiguration.InvalidChars.Message" ) );
      messageBox.setText( BaseMessages.getString( PKG, "RunConfiguration.InvalidChars.Title" ) );
      messageBox.open();
      return false;
    }

    return true;
  }

}


text:
const express = require("express");
const mongoose = require('mongoose');
const multer = require("multer");
const Jimp = require("jimp");
const codeDesc = require("../../codeDesc.js");
const User = require("../../db.js").user;
const Art = require("../../db.js").art;
const userAuth = require("../../auth.js").userAuth;

const router = express.Router();

router.get("/", userAuth, async (req, res, next) => {
    var result = {}
    result.info = {}

    if (req.query.page == undefined || req.query.page == null || req.query.page <= 0) {
        req.query.page = 1;
    }
    if (req.query.pagesize == null || req.query.pagesize == undefined || req.query.pagesize <= 0 || req.query.pagesize > 100) {
        req.query.pagesize = 15;
    }

    let user = await User.findOne({ email: req.cookies.email }).select("collections").populate("collections").exec();
    let count = user.collections.length;

    user.collections = user.collections.slice((parseInt(req.query.page) - 1) * parseInt(req.query.pagesize), (parseInt(req.query.page)) * parseInt(req.query.pagesize));

    for (let i = 0; i < user.collections.length; i++) {
        let image = await Jimp.read(user.collections[i].cover);
        user.collections[i]._doc.width = image.bitmap.width;
        user.collections[i]._doc.height = image.bitmap.height;
    }

    result.collections = await Art.populate(user.collections, [{ path: "author", select: "_id email info.galleryName info.name info.avatar" }]);

    result.pager = {};
    result.pager.page = parseInt(req.query.page);
    result.pager.pagesize = parseInt(req.query.pagesize);
    result.pager.pagecount = Math.ceil(count / req.query.pagesize);
    result.pager.count = count;
    result.info.code = 200;
    result.info.desc = codeDesc(200);

    res.status(200).jsonp(result);
});

router.post("/add", userAuth, async (req, res, next) => {
    var result = {}
    result.info = {}

    if (req.body.aid == undefined || req.body.aid == null || req.body.aid == "") {
        result.info.code = 405
        result.info.desc = codeDesc(405);

        res.status(405).json(result);
        return;
    }

    let user = req.user;

    for (let i = 0; i < user.collections.length; i++) {
        if (user.collections[i].toString() == req.body.aid) {
            user.collections.splice(i, 1);
            user = await user.save();

            result.info.code = 200;
            result.info.desc = codeDesc(200);
            result.status = false;
            res.status(200).jsonp(result);

            return;
        }
    }
    user.collections.unshift(mongoose.Types.ObjectId(req.body.aid));

    user = await user.save();

    result.info.code = 200;
    result.info.desc = codeDesc(200);
    result.status = true;
    res.status(200).jsonp(result);
});

module.exports = router;


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.h"

#include <memory>
#include <string>
#include <utility>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "base/thread_task_runner_handle.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_api_unittest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_system_factory.h"
#include "chrome/browser/extensions/test_extension_prefs.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/easy_unlock_app_manager.h"
#include "chrome/browser/signin/easy_unlock_service_factory.h"
#include "chrome/browser/signin/easy_unlock_service_regular.h"
#include "chrome/common/extensions/api/easy_unlock_private.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/fake_easy_unlock_client.h"
#include "components/proximity_auth/cryptauth/proto/cryptauth_api.pb.h"
#include "components/proximity_auth/switches.h"
#include "device/bluetooth/dbus/bluez_dbus_manager.h"
#include "extensions/browser/api_test_utils.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/event_router_factory.h"
#include "extensions/browser/extension_prefs.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

namespace {

namespace api = extensions::api::easy_unlock_private;

using extensions::EasyUnlockPrivateGenerateEcP256KeyPairFunction;
using extensions::EasyUnlockPrivatePerformECDHKeyAgreementFunction;
using extensions::EasyUnlockPrivateCreateSecureMessageFunction;
using extensions::EasyUnlockPrivateUnwrapSecureMessageFunction;
using extensions::EasyUnlockPrivateSetAutoPairingResultFunction;

class TestableGetRemoteDevicesFunction
    : public extensions::EasyUnlockPrivateGetRemoteDevicesFunction {
 public:
  TestableGetRemoteDevicesFunction() {}

  // EasyUnlockPrivateGetRemoteDevicesFunction:
  std::string GetUserPrivateKey() override { return "user private key"; }

  std::vector<cryptauth::ExternalDeviceInfo> GetUnlockKeys() override {
    cryptauth::ExternalDeviceInfo unlock_key1;
    unlock_key1.set_friendly_device_name("test phone 1");
    unlock_key1.set_public_key("public key 1");
    unlock_key1.set_bluetooth_address("AA:BB:CC:DD:EE:FF");
    unlock_key1.set_unlock_key(true);

    cryptauth::ExternalDeviceInfo unlock_key2;
    unlock_key2.set_friendly_device_name("test phone 2");
    unlock_key2.set_public_key("public key 2");
    unlock_key2.set_bluetooth_address("FF:EE:DD:CC:BB:AA");
    unlock_key2.set_unlock_key(true);

    std::vector<cryptauth::ExternalDeviceInfo> unlock_keys;
    unlock_keys.push_back(unlock_key1);
    unlock_keys.push_back(unlock_key2);
    return unlock_keys;
  }

 private:
  ~TestableGetRemoteDevicesFunction() override {}

  DISALLOW_COPY_AND_ASSIGN(TestableGetRemoteDevicesFunction);
};

class TestableGetPermitAccessFunction
    : public extensions::EasyUnlockPrivateGetPermitAccessFunction {
 public:
  TestableGetPermitAccessFunction() {}

  // EasyUnlockPrivateGetPermitAccessFunction:
  void GetKeyPairForExperiment(std::string* user_public_key,
                               std::string* user_private_key) override {
    *user_public_key = "user public key";
    *user_private_key = "user private key";
  }

 private:
  ~TestableGetPermitAccessFunction() override {}

  DISALLOW_COPY_AND_ASSIGN(TestableGetPermitAccessFunction);
};

// Converts a string to a base::BinaryValue value whose buffer contains the
// string data without the trailing '\0'.
base::BinaryValue* StringToBinaryValue(const std::string& value) {
  return base::BinaryValue::CreateWithCopiedBuffer(value.data(),
                                                   value.length());
}

// Copies |private_key_source| and |public_key_source| to |private_key_target|
// and |public_key_target|. It is used as a callback for
// |EasyUnlockClient::GenerateEcP256KeyPair| to save the values returned by the
// method.
void CopyKeyPair(std::string* private_key_target,
                 std::string* public_key_target,
                 const std::string& private_key_source,
                 const std::string& public_key_source) {
  *private_key_target = private_key_source;
  *public_key_target = public_key_source;
}

// Copies |data_source| to |data_target|. Used as a callback to EasyUnlockClient
// methods to save the data returned by the method.
void CopyData(std::string* data_target, const std::string& data_source) {
  *data_target = data_source;
}

class EasyUnlockPrivateApiTest : public extensions::ExtensionApiUnittest {
 public:
  EasyUnlockPrivateApiTest() {}
  ~EasyUnlockPrivateApiTest() override {}

 protected:
  void SetUp() override {
    chromeos::DBusThreadManager::Initialize();
    bluez::BluezDBusManager::Initialize(
        chromeos::DBusThreadManager::Get()->GetSystemBus(),
        chromeos::DBusThreadManager::Get()->IsUsingStub(
            chromeos::DBusClientBundle::BLUETOOTH));
    client_ = chromeos::DBusThreadManager::Get()->GetEasyUnlockClient();

    extensions::ExtensionApiUnittest::SetUp();
  }

  void TearDown() override {
    extensions::ExtensionApiUnittest::TearDown();

    bluez::BluezDBusManager::Shutdown();
    chromeos::DBusThreadManager::Shutdown();
  }

  // Extracts a single binary value result from a run extension function
  // |function| and converts it to string.
  // It will fail if the extension doesn't have exactly one binary value result.
  // On failure, an empty string is returned.
  std::string GetSingleBinaryResultAsString(
        UIThreadExtensionFunction* function) {
    const base::ListValue* result_list = function->GetResultList();
    if (!result_list) {
      LOG(ERROR) << "Function has no result list.";
      return "";
    }

    if (result_list->GetSize() != 1u) {
      LOG(ERROR) << "Invalid number of results.";
      return "";
    }

    const base::BinaryValue* result_binary_value;
    if (!result_list->GetBinary(0, &result_binary_value) ||
        !result_binary_value) {
      LOG(ERROR) << "Result not a binary value.";
      return "";
    }

    return std::string(result_binary_value->GetBuffer(),
                       result_binary_value->GetSize());
  }

  chromeos::EasyUnlockClient* client_;
};

TEST_F(EasyUnlockPrivateApiTest, GenerateEcP256KeyPair) {
  scoped_refptr<EasyUnlockPrivateGenerateEcP256KeyPairFunction> function(
      new EasyUnlockPrivateGenerateEcP256KeyPairFunction());
  function->set_has_callback(true);

  ASSERT_TRUE(extension_function_test_utils::RunFunction(
      function.get(),
      "[]",
      browser(),
      extension_function_test_utils::NONE));

  const base::ListValue* result_list = function->GetResultList();
  ASSERT_TRUE(result_list);
  ASSERT_EQ(2u, result_list->GetSize());

  const base::BinaryValue* public_key;
  ASSERT_TRUE(result_list->GetBinary(0, &public_key));
  ASSERT_TRUE(public_key);

  const base::BinaryValue* private_key;
  ASSERT_TRUE(result_list->GetBinary(1, &private_key));
  ASSERT_TRUE(private_key);

  EXPECT_TRUE(chromeos::FakeEasyUnlockClient::IsEcP256KeyPair(
      std::string(private_key->GetBuffer(), private_key->GetSize()),
      std::string(public_key->GetBuffer(), public_key->GetSize())));
}

TEST_F(EasyUnlockPrivateApiTest, PerformECDHKeyAgreement) {
  scoped_refptr<EasyUnlockPrivatePerformECDHKeyAgreementFunction> function(
      new EasyUnlockPrivatePerformECDHKeyAgreementFunction());
  function->set_has_callback(true);

  std::string private_key_1;
  std::string public_key_1_unused;
  client_->GenerateEcP256KeyPair(
      base::Bind(&CopyKeyPair, &private_key_1, &public_key_1_unused));

  std::string private_key_2_unused;
  std::string public_key_2;
  client_->GenerateEcP256KeyPair(
      base::Bind(&CopyKeyPair, &private_key_2_unused, &public_key_2));

  std::string expected_result;
  client_->PerformECDHKeyAgreement(
      private_key_1,
      public_key_2,
      base::Bind(&CopyData, &expected_result));
  ASSERT_GT(expected_result.length(), 0u);

  std::unique_ptr<base::ListValue> args(new base::ListValue);
  args->Append(StringToBinaryValue(private_key_1));
  args->Append(StringToBinaryValue(public_key_2));

  ASSERT_TRUE(extension_function_test_utils::RunFunction(
      function.get(), std::move(args), browser(),
      extension_function_test_utils::NONE));

  EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get()));
}

TEST_F(EasyUnlockPrivateApiTest, CreateSecureMessage) {
  scoped_refptr<EasyUnlockPrivateCreateSecureMessageFunction> function(
      new EasyUnlockPrivateCreateSecureMessageFunction());
  function->set_has_callback(true);

  chromeos::EasyUnlockClient::CreateSecureMessageOptions create_options;
  create_options.key = "KEY";
  create_options.associated_data = "ASSOCIATED_DATA";
  create_options.public_metadata = "PUBLIC_METADATA";
  create_options.verification_key_id = "VERIFICATION_KEY_ID";
  create_options.decryption_key_id = "DECRYPTION_KEY_ID";
  create_options.encryption_type = easy_unlock::kEncryptionTypeAES256CBC;
  create_options.signature_type = easy_unlock::kSignatureTypeHMACSHA256;

  std::string expected_result;
  client_->CreateSecureMessage(
      "PAYLOAD",
      create_options,
      base::Bind(&CopyData, &expected_result));
  ASSERT_GT(expected_result.length(), 0u);

  std::unique_ptr<base::ListValue> args(new base::ListValue);
  args->Append(StringToBinaryValue("PAYLOAD"));
  args->Append(StringToBinaryValue("KEY"));
  base::DictionaryValue* options = new base::DictionaryValue();
  args->Append(options);
  options->Set("associatedData", StringToBinaryValue("ASSOCIATED_DATA"));
  options->Set("publicMetadata", StringToBinaryValue("PUBLIC_METADATA"));
  options->Set("verificationKeyId",
               StringToBinaryValue("VERIFICATION_KEY_ID"));
  options->Set("decryptionKeyId",
               StringToBinaryValue("DECRYPTION_KEY_ID"));
  options->SetString(
      "encryptType",
      api::ToString(api::ENCRYPTION_TYPE_AES_256_CBC));
  options->SetString(
      "signType",
      api::ToString(api::SIGNATURE_TYPE_HMAC_SHA256));

  ASSERT_TRUE(extension_function_test_utils::RunFunction(
      function.get(), std::move(args), browser(),
      extension_function_test_utils::NONE));

  EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get()));
}

TEST_F(EasyUnlockPrivateApiTest, CreateSecureMessage_EmptyOptions) {
  scoped_refptr<EasyUnlockPrivateCreateSecureMessageFunction> function(
      new EasyUnlockPrivateCreateSecureMessageFunction());
  function->set_has_callback(true);

  chromeos::EasyUnlockClient::CreateSecureMessageOptions create_options;
  create_options.key = "KEY";
  create_options.encryption_type = easy_unlock::kEncryptionTypeNone;
  create_options.signature_type = easy_unlock::kSignatureTypeHMACSHA256;

  std::string expected_result;
  client_->CreateSecureMessage(
      "PAYLOAD",
      create_options,
      base::Bind(&CopyData, &expected_result));
  ASSERT_GT(expected_result.length(), 0u);

  std::unique_ptr<base::ListValue> args(new base::ListValue);
  args->Append(StringToBinaryValue("PAYLOAD"));
  args->Append(StringToBinaryValue("KEY"));
  base::DictionaryValue* options = new base::DictionaryValue();
  args->Append(options);

  ASSERT_TRUE(extension_function_test_utils::RunFunction(
      function.get(), std::move(args), browser(),
      extension_function_test_utils::NONE));

  EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get()));
}

TEST_F(EasyUnlockPrivateApiTest, CreateSecureMessage_AsymmetricSign) {
  scoped_refptr<EasyUnlockPrivateCreateSecureMessageFunction> function(
      new EasyUnlockPrivateCreateSecureMessageFunction());
  function->set_has_callback(true);

  chromeos::EasyUnlockClient::CreateSecureMessageOptions create_options;
  create_options.key = "KEY";
  create_options.associated_data = "ASSOCIATED_DATA";
  create_options.verification_key_id = "VERIFICATION_KEY_ID";
  create_options.encryption_type = easy_unlock::kEncryptionTypeNone;
  create_options.signature_type = easy_unlock::kSignatureTypeECDSAP256SHA256;

  std::string expected_result;
  client_->CreateSecureMessage(
      "PAYLOAD",
      create_options,
      base::Bind(&CopyData, &expected_result));
  ASSERT_GT(expected_result.length(), 0u);

  std::unique_ptr<base::ListValue> args(new base::ListValue);
  args->Append(StringToBinaryValue("PAYLOAD"));
  args->Append(StringToBinaryValue("KEY"));
  base::DictionaryValue* options = new base::DictionaryValue();
  args->Append(options);
  options->Set("associatedData",
               StringToBinaryValue("ASSOCIATED_DATA"));
  options->Set("verificationKeyId",
               StringToBinaryValue("VERIFICATION_KEY_ID"));
  options->SetString(
      "signType",
      api::ToString(api::SIGNATURE_TYPE_ECDSA_P256_SHA256));

  ASSERT_TRUE(extension_function_test_utils::RunFunction(
      function.get(), std::move(args), browser(),
      extension_function_test_utils::NONE));

  EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get()));
}

TEST_F(EasyUnlockPrivateApiTest, UnwrapSecureMessage) {
  scoped_refptr<EasyUnlockPrivateUnwrapSecureMessageFunction> function(
      new EasyUnlockPrivateUnwrapSecureMessageFunction());
  function->set_has_callback(true);

  chromeos::EasyUnlockClient::UnwrapSecureMessageOptions unwrap_options;
  unwrap_options.key = "KEY";
  unwrap_options.associated_data = "ASSOCIATED_DATA";
  unwrap_options.encryption_type = easy_unlock::kEncryptionTypeAES256CBC;
  unwrap_options.signature_type = easy_unlock::kSignatureTypeHMACSHA256;

  std::string expected_result;
  client_->UnwrapSecureMessage(
      "MESSAGE",
      unwrap_options,
      base::Bind(&CopyData, &expected_result));
  ASSERT_GT(expected_result.length(), 0u);

  std::unique_ptr<base::ListValue> args(new base::ListValue);
  args->Append(StringToBinaryValue("MESSAGE"));
  args->Append(StringToBinaryValue("KEY"));
  base::DictionaryValue* options = new base::DictionaryValue();
  args->Append(options);
  options->Set("associatedData", StringToBinaryValue("ASSOCIATED_DATA"));
  options->SetString(
      "encryptType",
      api::ToString(api::ENCRYPTION_TYPE_AES_256_CBC));
  options->SetString(
      "signType",
      api::ToString(api::SIGNATURE_TYPE_HMAC_SHA256));

  ASSERT_TRUE(extension_function_test_utils::RunFunction(
      function.get(), std::move(args), browser(),
      extension_function_test_utils::NONE));

  EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get()));
}

TEST_F(EasyUnlockPrivateApiTest, UnwrapSecureMessage_EmptyOptions) {
  scoped_refptr<EasyUnlockPrivateUnwrapSecureMessageFunction> function(
      new EasyUnlockPrivateUnwrapSecureMessageFunction());
  function->set_has_callback(true);

  chromeos::EasyUnlockClient::UnwrapSecureMessageOptions unwrap_options;
  unwrap_options.key = "KEY";
  unwrap_options.encryption_type = easy_unlock::kEncryptionTypeNone;
  unwrap_options.signature_type = easy_unlock::kSignatureTypeHMACSHA256;

  std::string expected_result;
  client_->UnwrapSecureMessage(
      "MESSAGE",
      unwrap_options,
      base::Bind(&CopyData, &expected_result));
  ASSERT_GT(expected_result.length(), 0u);

  std::unique_ptr<base::ListValue> args(new base::ListValue);
  args->Append(StringToBinaryValue("MESSAGE"));
  args->Append(StringToBinaryValue("KEY"));
  base::DictionaryValue* options = new base::DictionaryValue();
  args->Append(options);

  ASSERT_TRUE(extension_function_test_utils::RunFunction(
      function.get(), std::move(args), browser(),
      extension_function_test_utils::NONE));

  EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get()));
}

TEST_F(EasyUnlockPrivateApiTest, UnwrapSecureMessage_AsymmetricSign) {
  scoped_refptr<EasyUnlockPrivateUnwrapSecureMessageFunction> function(
      new EasyUnlockPrivateUnwrapSecureMessageFunction());
  function->set_has_callback(true);

  chromeos::EasyUnlockClient::UnwrapSecureMessageOptions unwrap_options;
  unwrap_options.key = "KEY";
  unwrap_options.associated_data = "ASSOCIATED_DATA";
  unwrap_options.encryption_type = easy_unlock::kEncryptionTypeNone;
  unwrap_options.signature_type = easy_unlock::kSignatureTypeECDSAP256SHA256;

  std::string expected_result;
  client_->UnwrapSecureMessage(
      "MESSAGE",
      unwrap_options,
      base::Bind(&CopyData, &expected_result));
  ASSERT_GT(expected_result.length(), 0u);

  std::unique_ptr<base::ListValue> args(new base::ListValue);
  args->Append(StringToBinaryValue("MESSAGE"));
  args->Append(StringToBinaryValue("KEY"));
  base::DictionaryValue* options = new base::DictionaryValue();
  args->Append(options);
  options->Set("associatedData",
               StringToBinaryValue("ASSOCIATED_DATA"));
  options->SetString(
      "signType",
      api::ToString(api::SIGNATURE_TYPE_ECDSA_P256_SHA256));

  ASSERT_TRUE(extension_function_test_utils::RunFunction(
      function.get(), std::move(args), browser(),
      extension_function_test_utils::NONE));

  EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get()));
}

struct AutoPairingResult {
  AutoPairingResult() : success(false) {}

  void SetResult(bool success, const std::string& error) {
    this->success = success;
    this->error = error;
  }

  bool success;
  std::string error;
};

// Test factory to register EasyUnlockService.
std::unique_ptr<KeyedService> BuildTestEasyUnlockService(
    content::BrowserContext* context) {
  std::unique_ptr<EasyUnlockServiceRegular> service(
      new EasyUnlockServiceRegular(Profile::FromBrowserContext(context)));
  service->Initialize(
      EasyUnlockAppManager::Create(extensions::ExtensionSystem::Get(context),
                                   -1 /* manifest id */, base::FilePath()));
  return std::move(service);
}

// A fake EventRouter that logs event it dispatches for testing.
class FakeEventRouter : public extensions::EventRouter {
 public:
  FakeEventRouter(
      Profile* profile,
      std::unique_ptr<extensions::TestExtensionPrefs> extension_prefs)
      : EventRouter(profile, extension_prefs->prefs()),
        extension_prefs_(std::move(extension_prefs)),
        event_count_(0) {}

  void DispatchEventToExtension(
      const std::string& extension_id,
      std::unique_ptr<extensions::Event> event) override {
    ++event_count_;
    last_extension_id_ = extension_id;
    last_event_name_ = event ? event->event_name : std::string();
  }

  int event_count() const { return event_count_; }
  const std::string& last_extension_id() const { return last_extension_id_; }
  const std::string& last_event_name() const { return last_event_name_; }

 private:
  std::unique_ptr<extensions::TestExtensionPrefs> extension_prefs_;
  int event_count_;
  std::string last_extension_id_;
  std::string last_event_name_;
};

// FakeEventRouter factory function
std::unique_ptr<KeyedService> FakeEventRouterFactoryFunction(
    content::BrowserContext* profile) {
  std::unique_ptr<extensions::TestExtensionPrefs> extension_prefs(
      new extensions::TestExtensionPrefs(base::ThreadTaskRunnerHandle::Get()));
  return base::WrapUnique(new FakeEventRouter(static_cast<Profile*>(profile),
                                              std::move(extension_prefs)));
}

TEST_F(EasyUnlockPrivateApiTest, AutoPairing) {
  FakeEventRouter* event_router = static_cast<FakeEventRouter*>(
      extensions::EventRouterFactory::GetInstance()->SetTestingFactoryAndUse(
          profile(), &FakeEventRouterFactoryFunction));

  EasyUnlockServiceFactory::GetInstance()->SetTestingFactoryAndUse(
      profile(), &BuildTestEasyUnlockService);

  AutoPairingResult result;

  // Dispatch OnStartAutoPairing event on EasyUnlockService::StartAutoPairing.
  EasyUnlockService* service = EasyUnlockService::Get(profile());
  service->StartAutoPairing(base::Bind(&AutoPairingResult::SetResult,
                                       base::Unretained(&result)));
  EXPECT_EQ(1, event_router->event_count());
  EXPECT_EQ(extension_misc::kEasyUnlockAppId,
            event_router->last_extension_id());
  EXPECT_EQ(
      extensions::api::easy_unlock_private::OnStartAutoPairing::kEventName,
      event_router->last_event_name());

  // Test SetAutoPairingResult call with failure.
  scoped_refptr<EasyUnlockPrivateSetAutoPairingResultFunction> function(
      new EasyUnlockPrivateSetAutoPairingResultFunction());
  ASSERT_TRUE(extension_function_test_utils::RunFunction(
      function.get(),
      "[{\"success\":false, \"errorMessage\":\"fake_error\"}]",
      browser(),
      extension_function_test_utils::NONE));
  EXPECT_FALSE(result.success);
  EXPECT_EQ("fake_error", result.error);

  // Test SetAutoPairingResult call with success.
  service->StartAutoPairing(base::Bind(&AutoPairingResult::SetResult,
                                       base::Unretained(&result)));
  function = new EasyUnlockPrivateSetAutoPairingResultFunction();
  ASSERT_TRUE(extension_function_test_utils::RunFunction(
      function.get(),
      "[{\"success\":true}]",
      browser(),
      extension_function_test_utils::NONE));
  EXPECT_TRUE(result.success);
  EXPECT_TRUE(result.error.empty());
}

// Checks that the chrome.easyUnlockPrivate.getRemoteDevices API returns the
// natively synced devices if the kEnableBluetoothLowEnergyDiscovery switch is
// set.
TEST_F(EasyUnlockPrivateApiTest, GetRemoteDevicesExperimental) {
  base::CommandLine::ForCurrentProcess()->AppendSwitch(
      proximity_auth::switches::kEnableBluetoothLowEnergyDiscovery);
  EasyUnlockServiceFactory::GetInstance()->SetTestingFactoryAndUse(
      profile(), &BuildTestEasyUnlockService);

  scoped_refptr<TestableGetRemoteDevicesFunction> function(
      new TestableGetRemoteDevicesFunction());
  std::unique_ptr<base::Value> value(
      extensions::api_test_utils::RunFunctionAndReturnSingleResult(
          function.get(), "[]", profile()));
  ASSERT_TRUE(value.get());
  ASSERT_EQ(base::Value::TYPE_LIST, value->GetType());

  base::ListValue* list_value = static_cast<base::ListValue*>(value.get());
  EXPECT_EQ(2u, list_value->GetSize());

  base::Value* remote_device1;
  base::Value* remote_device2;
  ASSERT_TRUE(list_value->Get(0, &remote_device1));
  ASSERT_TRUE(list_value->Get(1, &remote_device2));
  EXPECT_EQ(base::Value::TYPE_DICTIONARY, remote_device1->GetType());
  EXPECT_EQ(base::Value::TYPE_DICTIONARY, remote_device2->GetType());

  std::string name1, name2;
  EXPECT_TRUE(static_cast<base::DictionaryValue*>(remote_device1)
                  ->GetString("name", &name1));
  EXPECT_TRUE(static_cast<base::DictionaryValue*>(remote_device2)
                  ->GetString("name", &name2));

  EXPECT_EQ("test phone 1", name1);
  EXPECT_EQ("test phone 2", name2);
}

// Checks that the chrome.easyUnlockPrivate.getRemoteDevices API returns the
// stored value if the kEnableBluetoothLowEnergyDiscovery switch is not set.
TEST_F(EasyUnlockPrivateApiTest, GetRemoteDevicesNonExperimental) {
  EasyUnlockServiceFactory::GetInstance()->SetTestingFactoryAndUse(
      profile(), &BuildTestEasyUnlockService);

  scoped_refptr<TestableGetRemoteDevicesFunction> function(
      new TestableGetRemoteDevicesFunction());
  std::unique_ptr<base::Value> value(
      extensions::api_test_utils::RunFunctionAndReturnSingleResult(
          function.get(), "[]", profile()));
  ASSERT_TRUE(value.get());
  ASSERT_EQ(base::Value::TYPE_LIST, value->GetType());

  base::ListValue* list_value = static_cast<base::ListValue*>(value.get());
  EXPECT_EQ(0u, list_value->GetSize());
}

// Checks that the chrome.easyUnlockPrivate.getPermitAccess API returns the
// native permit access if the kEnableBluetoothLowEnergyDiscovery switch is
// set.
TEST_F(EasyUnlockPrivateApiTest, GetPermitAccessExperimental) {
  base::CommandLine::ForCurrentProcess()->AppendSwitch(
      proximity_auth::switches::kEnableBluetoothLowEnergyDiscovery);
  EasyUnlockServiceFactory::GetInstance()->SetTestingFactoryAndUse(
      profile(), &BuildTestEasyUnlockService);

  scoped_refptr<TestableGetPermitAccessFunction> function(
      new TestableGetPermitAccessFunction());
  std::unique_ptr<base::Value> value(
      extensions::api_test_utils::RunFunctionAndReturnSingleResult(
          function.get(), "[]", profile()));
  ASSERT_TRUE(value);
  ASSERT_EQ(base::Value::TYPE_DICTIONARY, value->GetType());
  base::DictionaryValue* permit_access =
      static_cast<base::DictionaryValue*>(value.get());

  std::string user_public_key, user_private_key;
  EXPECT_TRUE(permit_access->GetString("id", &user_public_key));
  EXPECT_TRUE(permit_access->GetString("data", &user_private_key));
  EXPECT_EQ("user public key", user_public_key);
  EXPECT_EQ("user private key", user_private_key);
}

// Checks that the chrome.easyUnlockPrivate.getPermitAccess API returns the
// stored value if the kEnableBluetoothLowEnergyDiscovery switch is not set.
TEST_F(EasyUnlockPrivateApiTest, GetPermitAccessNonExperimental) {
  EasyUnlockServiceFactory::GetInstance()->SetTestingFactoryAndUse(
      profile(), &BuildTestEasyUnlockService);

  scoped_refptr<TestableGetPermitAccessFunction> function(
      new TestableGetPermitAccessFunction());
  std::unique_ptr<base::Value> value(
      extensions::api_test_utils::RunFunctionAndReturnSingleResult(
          function.get(), "[]", profile()));
  EXPECT_FALSE(value);
}

}  // namespace


text:
package no.ssb.vtl.script.expressions.equality;

import no.ssb.vtl.model.VTLExpression;
import no.ssb.vtl.model.VTLObject;

public class LesserOrEqualExpression extends AbstractEqualityExpression {

    public LesserOrEqualExpression(VTLExpression leftOperand, VTLExpression rightOperand) {
        super(leftOperand, rightOperand);
    }

    @Override
    protected boolean compare(VTLObject leftOperand, VTLObject rightOperand) {
        return leftOperand.compareTo(rightOperand) <= 0;
    }
}


text:
package lostsoulsquasher.actors.bonus.classes;

import lostsoulsquasher.Entity;
import lostsoulsquasher.LostSoulWorld;
import lostsoulsquasher.factormodifier.FactorModifierActor;
import lostsoulsquasher.render.RenderBehavior;

public class BonusEnemySlowDown extends BonusClass {
    @Override
    public void activate(LostSoulWorld world) {
        world.getGame().getAudio().playSound(world.getGame().getContent().turtleSound);
        world.addSpeedModifierActor(new FactorModifierActor(world.getGame(), 0.2f, 3.0f));
    }

    @Override
    public RenderBehavior mkRender(Entity entity) {
        return mkBonusRender(entity, entity.getGame().getContent().bonusTurtle);
    }

    @Override
    public float getWeight() {
        return 1.0f;
    }
}


text:
package org.jivesoftware.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;

/**
 * Openfire makes use of a logging facade (slf4j) to manage its log output. The
 * facade is backed up by Log4j by default. This class provides utility methods.
 *

 * Additionally, this class provides methods that can be used to record logging
 * statements. These methods are exact duplicates of the previous Log
 * implementation of Openfire and are kept for backwards-compatibility (the are
 * deprecated). These methods will delegate logging functionality to slf4j.
 * Instead of these methods, slf4j logging functionality should be used
 * directly.
 *
 * @author Guus der Kinderen, guus.der.kinderen@gmail.com
 * @see http://www.slf4j.org/
 */
public final class Log {

    private static final org.slf4j.Logger Logger = org.slf4j.LoggerFactory.getLogger(Log.class);
    public static final SystemProperty<Boolean> DEBUG_ENABLED = SystemProperty.Builder.ofType(Boolean.class)
        .setKey("log.debug.enabled")
        .setDefaultValue(false)
        .setDynamic(true)
        .addListener(Log::setDebugEnabled)
        .build();

    public static final SystemProperty<Boolean> TRACE_ENABLED = SystemProperty.Builder.ofType(Boolean.class)
        .setKey("log.trace.enabled")
        .setDefaultValue(false)
        .setDynamic(true)
        .addListener(Log::setTraceEnabled)
        .build();

    private static Level lastLogLevel = getRootLogLevel();

    public static void setDebugEnabled(final boolean enabled) {
        if (enabled && getRootLogLevel().isMoreSpecificThan(Level.DEBUG)) {
            lastLogLevel = getRootLogLevel();
            setLogLevel(Level.DEBUG);
        } else if (!enabled && getRootLogLevel().isLessSpecificThan(Level.DEBUG)) {
            setLogLevel(lastLogLevel != Level.DEBUG ? lastLogLevel : Level.INFO);
            lastLogLevel = Level.DEBUG;
        }
    }

    public static void setTraceEnabled(final boolean enabled) {
        if (enabled && getRootLogLevel().isMoreSpecificThan(Level.TRACE)) {
            lastLogLevel = getRootLogLevel();
            setLogLevel(Level.TRACE);
        } else if (!enabled && getRootLogLevel().isLessSpecificThan(Level.TRACE)) {
            setLogLevel(lastLogLevel != Level.TRACE ? lastLogLevel : Level.INFO);
            lastLogLevel = Level.TRACE;
        }
    }

    public static Level getRootLogLevel() {
        // SLF4J doesn't provide a hook into the logging implementation. We'll have to do this 'direct', bypassing slf4j.
        final LoggerContext ctx = (LoggerContext) LogManager.getContext( false );
        final Configuration config = ctx.getConfiguration();
        final LoggerConfig loggerConfig = config.getRootLogger();
        return loggerConfig.getLevel();
    }

    private static void setLogLevel(Level newLevel) {
        // SLF4J doesn't provide a hook into the logging implementation. We'll have to do this 'direct', bypassing slf4j.
        final LoggerContext ctx = (LoggerContext) LogManager.getContext( false );
        final Configuration config = ctx.getConfiguration();
        final LoggerConfig loggerConfig = config.getRootLogger();
        loggerConfig.setLevel( newLevel );
        ctx.updateLoggers();  // This causes all Loggers to refetch information from their LoggerConfig.
    }

    public static void rotateOpenfireLogFile() {
        // SLF4J doesn't provide a hook into the logging implementation. We'll have to do this 'direct', bypassing slf4j.
        File logFile = new File(Log.getLogDirectory(), "openfire.log");
        emptyFile(logFile);
    }

    public static void markOpenfireLogFile(String username) {
        String message = getMarkMessage(username);
        File logFile = new File(Log.getLogDirectory(), "openfire.log");

        try(FileWriter fw = new FileWriter(logFile, true);
            PrintWriter out = new PrintWriter(fw))
        {
            out.println(message);
        } catch (IOException e) {
            e.printStackTrace(); // Writing it to the logfile feels wrong, as we're processing the logfile here.
        }
    }

    /**
     * Returns the directory that log files exist in. The directory name will
     * have a File.separator as the last character in the string.
     *
     * @return the directory that log files exist in.
     */
    public static String getLogDirectory() {
        // SLF4J doesn't provide a hook into the logging implementation. We'll have to do this 'direct', bypassing slf4j.
        final StringBuilder sb = new StringBuilder();
        sb.append(JiveGlobals.getHomeDirectory());
        if (!sb.substring(sb.length()-1).startsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append("logs");
        sb.append(File.separator);
        return sb.toString();
    }

    private static String getMarkMessage(String username) {
        final List<String> args = new ArrayList<>();
        args.add(username);
        args.add(JiveGlobals.formatDateTime(new java.util.Date()));
        return LocaleUtils.getLocalizedString("log.marker_inserted_by", args);
    }

    private static void printToStdErr(String s, Throwable throwable) {
        if (s != null) {
            System.err.println(s);
        }
        if (throwable != null) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            throwable.printStackTrace(pw);
            System.err.print(sw.toString());
            System.err.print("\n");
        }
    }

    private static void emptyFile(File logFile) {
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new FileWriter(logFile));
            out.write("");
        } catch (IOException ex) {
            Logger.warn("Could not empty file " + logFile.getName(), ex);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                    Logger.warn("Could not close file.", ex);
                }
            }
        }
    }
}


text:
<?php

namespace BoomCMS\Events;

use BoomCMS\Foundation\Events\PageEvent;

class PageWasReverted extends PageEvent
{
}


text:
package itesm.mx.commitment_app;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by nloyola on 6/11/16.
 */
public class Commitment {

    public String name;
    public String description;
    public String id;
    public HashMap<String, Survey> surveys;
    public String survey_time;

    public Commitment() {

    }

    public Commitment(String name, String description) {
        this.name = name;
        this.description = description;
    }

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

    public void setSurveys(HashMap<String, Survey> surveys) {
        this.surveys = surveys;
    }

    public void setSurveyTime(String survey_time) {
        this.survey_time = survey_time;
    }

}


text:
#nullable enable
namespace ControlzEx.Theming
{
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    using JetBrains.Annotations;

    /// <summary>
    /// Options being used to generate one single <see cref="LibraryTheme"/>.
    /// </summary>
    [PublicAPI]
    public class RuntimeThemeOptions : INotifyPropertyChanged
    {
        public RuntimeThemeOptions(bool useHSL, bool isHighContrast, ThemeGenerator.ThemeGeneratorParameters? generatorParameters, ThemeGenerator.ThemeGeneratorBaseColorScheme? baseColorScheme)
        {
            this.UseHSL = useHSL;
            this.IsHighContrast = isHighContrast;
            this.GeneratorParameters = generatorParameters;
            this.BaseColorScheme = baseColorScheme;
        }

        public bool UseHSL { get; }

        public bool IsHighContrast { get; }

        public ThemeGenerator.ThemeGeneratorParameters? GeneratorParameters { get; }

        public ThemeGenerator.ThemeGeneratorBaseColorScheme? BaseColorScheme { get; }

        public event PropertyChangedEventHandler? PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}