text:
using System.Xml.Linq;

namespace Winkler.MyAir3Api
{
    public class SystemInfo
    {
        public int SystemType { get; private set; }
        public string Name { get; private set; }
        public string MyAppRevision { get; private set; }
        public bool HasUnitControl { get; private set; }
        public bool Dhcp { get; private set; }
        public string Ip { get; private set; }
        public string Netmask { get; private set; }
        public string Gateway { get; private set; }

        public SystemInfo(XElement data)
        {
            SystemType = int.Parse(data.Element("type").Value);
            Name = data.Element("name").Value;
            MyAppRevision = data.Element("MyAppRev").Value;
            HasUnitControl = int.Parse(data.Element("zoneStationHasUnitControl").Value) == 1;
            Dhcp = int.Parse(data.Element("dhcp").Value) == 1;
            Ip = data.Element("ip").Value;
            Netmask = data.Element("netmask").Value;
            Gateway = data.Element("gateway").Value;
        }
    }
}


text:
const path = require("path" )

module.exports = {
    entry: "./entry.ts",
    target: "electron",
    output: {
        library: true,
        libraryTarget: 'commonjs2',
        path: __dirname + "/dist",
        filename: "bundle.js",
        publicPath: 'http://localhost:8080/dist/'
    },
    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    // Add '.ts' and '.tsx' as resolvable extensions.
    resolve: {
        extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },
    module: {
        preLoaders: [
            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { test: /\.js$/, loader: "source-map-loader" }
        ],
        loaders: [
            { test: /\.css$/, loader: "style!css" },
            { test: /\.ts?$/, loader: "ts-loader", exclude: /node_modules/ }
        ]

    }
};

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.konstantinost.appcompare" >

    <uses-permission  android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/launcher_icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".StartActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MenuActivity"
            android:parentActivityName=".StartActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".StartActivity" />
        </activity>
        <activity
            android:name=".InstalledApplicationsActivity"
            android:parentActivityName=".MenuActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.konstantinost.appcompare.MenuActivity" />
        </activity>
        <activity
            android:name=".ResultActivity"
            android:parentActivityName=".MenuActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.konstantinost.appcompare.MenuActivity" />
        </activity>
        <activity
            android:name=".AboutActivity"
            android:parentActivityName=".MenuActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.konstantinost.appcompare.MenuActivity" />
        </activity>
    </application>

</manifest>


text:
package org.osgi.test.cases.converter.felix;

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

import org.osgi.dto.DTO;

public class MyDTO2 extends DTO {
	public static String		shouldBeIgnored	= "ignoreme";

	public List<Long>			longList;

	public Map<String,MyDTO3>	dtoMap;
}


text:
using System.Diagnostics;

namespace Shouldly.Configuration
{
    public interface ITestMethodFinder
    {
        TestMethodInfo GetTestMethodInfo(StackTrace stackTrace, int startAt = 0);
    }
}
#endif


text:
#include "ruby/ruby.h"
#include "ruby/io.h"

#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef HAVE_SYS_MOUNT_H
#include <sys/mount.h>
#endif
#ifdef HAVE_SYS_VFS_H
#include <sys/vfs.h>
#endif
#ifdef HAVE_SYS_STATVFS_H
#include <sys/statvfs.h>
#endif

#if defined HAVE_STRUCT_STATFS_F_FSTYPENAME
typedef struct statfs statfs_t;
# define STATFS(f, s) statfs((f), (s))
# define HAVE_STRUCT_STATFS_T_F_FSTYPENAME 1
# if defined HAVE_STRUCT_STATFS_F_TYPE
#   define HAVE_STRUCT_STATFS_T_F_TYPE 1
# endif
#elif defined(HAVE_STRUCT_STATVFS_F_FSTYPENAME) /* NetBSD */
typedef struct statvfs statfs_t;
# define STATFS(f, s) statvfs((f), (s))
# define HAVE_STRUCT_STATFS_T_F_FSTYPENAME 1
# if defined HAVE_STRUCT_STATVFS_F_TYPE
#   define HAVE_STRUCT_STATFS_T_F_TYPE 1
# endif
#elif defined(HAVE_STRUCT_STATVFS_F_BASETYPE) /* AIX, HP-UX, Solaris */
typedef struct statvfs statfs_t;
# define STATFS(f, s) statvfs((f), (s))
# define HAVE_STRUCT_STATFS_T_F_FSTYPENAME 1
# define f_fstypename f_basetype
# if defined HAVE_STRUCT_STATVFS_F_TYPE
#   define HAVE_STRUCT_STATFS_T_F_TYPE 1
# endif
#elif defined(HAVE_STRUCT_STATFS_F_TYPE) /* Linux */
typedef struct statfs statfs_t;
# define STATFS(f, s) statfs((f), (s))
# if defined HAVE_STRUCT_STATFS_F_TYPE
#   define HAVE_STRUCT_STATFS_T_F_TYPE 1
# endif
#endif

VALUE
get_fsname(VALUE self, VALUE str)
{
#ifdef STATFS
    statfs_t st;
# define CSTR(s) rb_str_new_cstr(s)

    FilePathValue(str);
    str = rb_str_encode_ospath(str);
    if (STATFS(StringValueCStr(str), &st) == -1) {
	rb_sys_fail_str(str);
    }
# ifdef HAVE_STRUCT_STATFS_T_F_FSTYPENAME
    if (st.f_fstypename[0])
	return CSTR(st.f_fstypename);
# endif
# ifdef HAVE_STRUCT_STATFS_T_F_TYPE
    switch (st.f_type) {
      case 0x9123683E: /* BTRFS_SUPER_MAGIC */
	return CSTR("btrfs");
      case 0x7461636f: /* OCFS2_SUPER_MAGIC */
	return CSTR("ocfs");
      case 0xEF53: /* EXT2_SUPER_MAGIC EXT3_SUPER_MAGIC EXT4_SUPER_MAGIC */
	return CSTR("ext4");
      case 0x58465342: /* XFS_SUPER_MAGIC */
	return CSTR("xfs");
      case 0x01021994: /* TMPFS_MAGIC */
	return CSTR("tmpfs");
    }
# endif
#endif
    return Qnil;
}

VALUE
get_noatime_p(VALUE self, VALUE str)
{
#ifdef STATFS
    statfs_t st;
    FilePathValue(str);
    str = rb_str_encode_ospath(str);
    if (STATFS(StringValueCStr(str), &st) == -1) {
       rb_sys_fail_str(str);
    }
# ifdef HAVE_STRUCT_STATFS_F_FLAGS
#  ifdef MNT_STRICTATIME
    if (!(st.f_flags & MNT_STRICTATIME)) return Qtrue;
#  endif
#  ifdef MNT_NOATIME
    return st.f_flags & MNT_NOATIME ? Qtrue : Qfalse;
#  elif defined(ST_NOATIME)
    return st.f_flags & ST_NOATIME ? Qtrue : Qfalse;
#  endif
# endif
#endif
    return Qnil;
}

void
Init_fs(VALUE module)
{
    VALUE fs = rb_define_module_under(module, "Fs");
    rb_define_module_function(fs, "fsname", get_fsname, 1);
    rb_define_module_function(fs, "noatime?", get_noatime_p, 1);
}


text:
Thanks for registering on joind.in!  In order to verify your email address, please click the link below:

[[website_url]/user/verification?token=[token]]([website_url]/user/verification?token=[token])


text:
package org.springframework.web.servlet.view.jasperreports;

import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import org.springframework.context.support.StaticApplicationContext;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

/**
 * @author Rob Harrop
 */
public class ExporterParameterTests extends AbstractJasperReportsTests {

	public void testParameterParsing() throws Exception {
		Map params = new HashMap();
		params.put("net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI", "/foo/bar");

		AbstractJasperReportsView view = new AbstractJasperReportsView() {
			protected void renderReport(
							JasperPrint filledReport, Map model, HttpServletResponse response)
							throws Exception {

				assertEquals("Invalid number of exporter parameters", 1, getConvertedExporterParameters().size());

				JRExporterParameter key = JRHtmlExporterParameter.IMAGES_URI;
				Object value = getConvertedExporterParameters().get(key);

				assertNotNull("Value not mapped to correct key", value);
				assertEquals("Incorrect value for parameter", "/foo/bar", value);
			}

			/**
			 * Merges the configured {@link net.sf.jasperreports.engine.JRExporterParameter JRExporterParameters} with any specified
			 * in the supplied model data. {@link net.sf.jasperreports.engine.JRExporterParameter JRExporterParameters} in the model
			 * override those specified in the configuration.
			 *
			 * @see #setExporterParameters(java.util.Map)
			 */
			protected Map mergeExporterParameters(Map model) {
				Map mergedParameters = new HashMap(getConvertedExporterParameters());
				for (Iterator iterator = model.keySet().iterator(); iterator.hasNext();) {
					Object key = iterator.next();

					if (key instanceof JRExporterParameter) {
						Object value = model.get(key);
						if (value instanceof String) {
							mergedParameters.put(key, value);
						}
						else {
							logger.warn("Ignoring exporter parameter [" + key + "]. Value is not a String.");
						}
					}
				}
				return mergedParameters;
			}
		};

		view.setExporterParameters(params);
		setViewProperties(view);
		view.render(getModel(), request, response);
	}

	public void testInvalidClass() throws Exception {
		Map params = new HashMap();
		params.put("foo.net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI", "/foo");

		AbstractJasperReportsView view = new JasperReportsHtmlView();
		setViewProperties(view);

		try {
			view.setExporterParameters(params);
			view.convertExporterParameters();
			fail("Should have thrown IllegalArgumentException");
		}
		catch (IllegalArgumentException ex) {
			// expected
		}
	}

	public void testInvalidField() {
		Map params = new HashMap();
		params.put("net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI_FOO", "/foo");

		AbstractJasperReportsView view = new JasperReportsHtmlView();
		setViewProperties(view);

		try {
			view.setExporterParameters(params);
			view.convertExporterParameters();
			fail("Should have thrown IllegalArgumentException");
		}
		catch (IllegalArgumentException ex) {
			// expected
		}
	}

	public void testInvalidType() {
		Map params = new HashMap();
		params.put("java.lang.Boolean.TRUE", "/foo");

		AbstractJasperReportsView view = new JasperReportsHtmlView();
		setViewProperties(view);

		try {
			view.setExporterParameters(params);
			view.convertExporterParameters();
			fail("Should have thrown IllegalArgumentException");
		}
		catch (IllegalArgumentException ex) {
			// expected
		}
	}

	public void testTypeConversion() {
		Map params = new HashMap();
		params.put("net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN", "true");

		AbstractJasperReportsView view = new JasperReportsHtmlView();
		setViewProperties(view);

		view.setExporterParameters(params);
		view.convertExporterParameters();
		Object value = view.getConvertedExporterParameters().get(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN);
		assertEquals(Boolean.TRUE, value);
	}

	private void setViewProperties(AbstractJasperReportsView view) {
		view.setUrl("org/springframework/ui/jasperreports/DataSourceReport.jasper");
		StaticApplicationContext ac = new StaticApplicationContext();
		ac.addMessage("page", Locale.GERMAN, "MeineSeite");
		ac.refresh();
		view.setApplicationContext(ac);
	}

}


text:
Package.describe({
	name: 'rocketchat:search',
	version: '0.0.1',
	summary: 'Rocketchat Search Providers',
	git: ''
});

Package.onUse(function(api) {
	api.use([
		'ecmascript',
		'templating',
		'rocketchat:lib',
		'rocketchat:logger',
		'kadira:flow-router'
	]);

	api.addFiles([
		'client/search/search.html',
		'client/search/search.js',
		'client/provider/suggestion.html',
		'client/provider/result.html',
		'client/provider/result.js',
		'client/style/style.css'
	], 'client');

	api.mainModule('server/index.js', 'server');
});


text:
package org.apache.activemq.command;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.TemporaryQueue;
import javax.jms.TemporaryTopic;
import javax.jms.Topic;

import junit.framework.Test;

public class ActiveMQDestinationTest extends DataStructureTestSupport {

    public ActiveMQDestination destination;

    public void initCombosForTestDestinationMarshaling() {
        addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"),
                                                          new ActiveMQTopic("TEST"),
                                                          new ActiveMQTempQueue("TEST:1"),
                                                          new ActiveMQTempTopic("TEST:1"),
                                                          new ActiveMQTempQueue("TEST"),
                                                          new ActiveMQTempTopic("TEST"),
                                                          new ActiveMQQueue("TEST?option=value"),
                                                          new ActiveMQTopic("TEST?option=value"),
                                                          new ActiveMQTempQueue("TEST:1?option=value"),
                                                          new ActiveMQTempTopic("TEST:1?option=value")});
    }

    public void testDestinationMarshaling() throws IOException {
        assertBeanMarshalls(destination);
    }

    public void initCombosForTestDestinationOptions() {
        addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST?k1=v1&k2=v2"),
                                                          new ActiveMQTopic("TEST?k1=v1&k2=v2"),
                                                          new ActiveMQTempQueue("TEST:1?k1=v1&k2=v2"),
                                                          new ActiveMQTempTopic("TEST:1?k1=v1&k2=v2")});
    }

    public void testDestinationOptions() throws IOException {
        Map options = destination.getOptions();
        assertNotNull(options);
        assertEquals("v1", options.get("k1"));
        assertEquals("v2", options.get("k2"));
    }

    public void testSorting() throws Exception {
        SortedSet<ActiveMQDestination> set = new TreeSet<ActiveMQDestination>();
        ActiveMQDestination[] destinations = {new ActiveMQQueue("A"), new ActiveMQQueue("B"),
                                              new ActiveMQTopic("A"), new ActiveMQTopic("B")};
        List<ActiveMQDestination> expected = Arrays.asList(destinations);
        set.addAll(expected);
        List<ActiveMQDestination> actual = new ArrayList<ActiveMQDestination>(set);
        assertEquals("Sorted order", expected, actual);
    }

    // https://issues.apache.org/activemq/browse/AMQ-2630
    class CombyDest implements Queue, Topic, TemporaryQueue, TemporaryTopic {

        private final String qName;
        private final String topicName;

        public CombyDest(String qName, String topicName) {
            this.qName = qName;
            this.topicName = topicName;
        }

        public void delete() throws JMSException {
        }

        public String getTopicName() throws JMSException {
            return topicName;
        }

        public String getQueueName() throws JMSException {
            return qName;
        }
    }

    public void testTransformPollymorphic() throws Exception {
        ActiveMQQueue queue = new ActiveMQQueue("TEST");
        assertEquals(ActiveMQDestination.transform(queue), queue);
        assertTrue("is a q", ActiveMQDestination.transform(new CombyDest(null, "Topic")) instanceof ActiveMQTopic);
        assertTrue("is a q", ActiveMQDestination.transform(new CombyDest("Q", null)) instanceof ActiveMQQueue);
        try {
            ActiveMQDestination.transform(new CombyDest(null, null));
            fail("expect ex as cannot disambiguate");
        } catch (JMSException expected) {
        }
        try {
            ActiveMQDestination.transform(new CombyDest("Q", "T"));
            fail("expect ex as cannot disambiguate");
        } catch (JMSException expected) {
        }
    }

    public static Test suite() {
        return suite(ActiveMQDestinationTest.class);
    }

    public static void main(String[] args) {
        junit.textui.TestRunner.run(suite());
    }

    public void testEmptyQueueName() {
        try {
            new ActiveMQQueue("");
            fail("Should have thrown IllegalArgumentException");
        } catch (IllegalArgumentException e) {

        }
    }

    public void testEmptyTopicName() {
        try {
            new ActiveMQTopic("");
            fail("Should have thrown IllegalArgumentException");
        } catch (IllegalArgumentException e) {

        }
    }
}


text:
using System.Security.Claims;
using System.Threading.Tasks;

namespace Orchard.Security.Services
{
    public interface IMembershipService
    {
        Task<IUser> GetUserAsync(string userName);
        Task<bool> CheckPasswordAsync(string userName, string password);
        Task<ClaimsPrincipal> CreateClaimsPrincipal(IUser user);
    }
}


text:
fs = require('fs');

fs.readFile('example', 'utf8', function (err, data) {
    if (err) {
      return console.log(err);
    }
    console.log(data);
});
//====================
var data = fs.readFileSync('example','utf8');
console.log(data);


text:
solution("CryGame")
	location("solutions/vcproj" .. _ACTION)
	platforms { "x32", "x64" }

	language("C++")

	configurations{"Debug", "Release"}

	project("jio")
		location("solutions/" .. _ACTION)

		flags("NoMinimalRebuild")

		buildoptions
		{
			"/Gy",
			"/GS",
			"/GF",
			"/MP",
			"/arch:SSE",
		}

		language("C++")
		kind("Exe")

		targetdir("game/bin32/")
		targetname("CryGameSDK")

		objdir("obj/")

		includedirs(".")
		includedirs("external/protobuf-2.6.0/src")
		includedirs("test")

		files("**.hpp")

		configuration("Debug")
			flags("Symbols")

		configuration("Release")
			flags("Optimize")


text:
/*
Package loom implements a set of functions to interact with remote servers using SSH.
It is based on the Python fabric library.
*/
package loom

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"strconv"
	"strings"
	"sync"

	"golang.org/x/crypto/ssh"
)

// Config contains ssh and other configuration data needed for all the public functions in loom.
type Config struct {
	// The user name used in SSH connections. If not specified, the current user is assumed.
	User string

	// Password for SSH connections. This is optional. If the user has an ~/.ssh/id_rsa keyfile,
	// that will also be tried. In addition, other key files can be specified.
	Password string

	// The machine:port to connect to.
	Host string

	// The file names of additional key files to use for authentication (~/.ssh/id_rsa is defaulted).
	// RSA (PKCS#1), DSA (OpenSSL), and ECDSA private keys are supported.
	KeyFiles []string

	// If true, send command output to stdout.
	DisplayOutput bool

	// If true, errors are fatal and will abort immediately.
	AbortOnError bool
}

// parsekey is a private function that reads in a keyfile containing a private key and parses it.
func parsekey(file string) (ssh.Signer, error) {
	var private ssh.Signer
	privateBytes, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	private, err = ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		return nil, err
	}
	return private, nil
}

// connect is a private function to set up the ssh connection. It is called at the beginning of every public
// function.
func (config *Config) connect() (*ssh.Session, error) {

	sshconfig := &ssh.ClientConfig{
		User: config.User,
	}

	if config.User == "" {
		u, err := user.Current()
		if err != nil {
			return nil, err
		}
		sshconfig.User = u.Username
	}

	if config.Password != "" {
		sshconfig.Auth = append(sshconfig.Auth, ssh.Password(config.Password))
	}

	var pkey ssh.Signer
	var keyfile string
	var err error

	// Include additional key files
	for _, keyfile = range config.KeyFiles {
		pkey, err = parsekey(keyfile)
		if err != nil {
			if config.AbortOnError == true {
				log.Fatalf("%s", err)
			}
			return nil, err
		}
		sshconfig.Auth = append(sshconfig.Auth, ssh.PublicKeys(pkey))
	}

	// By default, we try to include ~/.ssh/id_rsa. It is not an error if this file
	// doesn't exist.
	keyfile = os.Getenv("HOME") + "/.ssh/id_rsa"
	pkey, err = parsekey(keyfile)
	if err == nil {
		fmt.Println("Adding default rsa key")
		sshconfig.Auth = append(sshconfig.Auth, ssh.PublicKeys(pkey))
	}

	host := config.Host
	if strings.Contains(host, ":") == false {
		host = host + ":22"
	}
	client, err := ssh.Dial("tcp", host, sshconfig)
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return nil, err
	}

	session, err := client.NewSession()
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return nil, err
	}
	return session, err
}

// doRun is called by both Run() and Sudo() to execute a command.
func (config *Config) doRun(cmd string, sudo bool) (string, error) {

	session, err := config.connect()
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return "", err
	}
	defer session.Close()

	// Set up terminal modes
	modes := ssh.TerminalModes{
		ssh.ECHO:          0,     // disable echoing
		ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
		ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
	}
	// Request pseudo terminal
	if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return "", err
	}

	if sudo == true {
		cmd = fmt.Sprintf("/usr/bin/sudo bash <<CMD\nexport PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin\n%s\nCMD", cmd)
	}

	// TODO: use pipes instead of CombinedOutput so that we can show the output of commands more interactively, instead
	// of now, which is after they're completely done executing.
	output, err := config.executeCommand(session, cmd, sudo)
	soutput := strings.Replace(string(output), "\r\n", "\n", -1)
	if err != nil {
		if config.DisplayOutput == true && len(soutput) > 0 {
			fmt.Printf("%s", soutput)
		}
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return "", err
	}
	session.SendRequest("close", false, nil)
	if config.DisplayOutput == true {
		fmt.Printf("%s", soutput)
	}
	return soutput, nil
}

type singleWriterReader struct {
	b         *bytes.Buffer
	b2        *bytes.Buffer
	teeReader io.Reader
	mu        sync.Mutex
	usingRead bool
}

func newSingleWriterReader() singleWriterReader {
	b := bytes.NewBuffer([]byte{})
	b2 := bytes.NewBuffer([]byte{})
	return singleWriterReader{b, b2, io.TeeReader(b, b2), sync.Mutex{}, false}
}

func (w *singleWriterReader) Write(p []byte) (int, error) {
	w.mu.Lock()
	defer w.mu.Unlock()
	return w.b.Write(p)
}

func (w *singleWriterReader) Read(p []byte) (int, error) {
	w.usingRead = true
	w.mu.Lock()
	defer w.mu.Unlock()
	n, err := w.teeReader.Read(p)
	return n, err
}

// Note: This should only be read once at the end, after everything has
// be written or read.
func (w *singleWriterReader) Bytes() []byte {
	w.mu.Lock()
	defer w.mu.Unlock()

	return append(w.b2.Bytes(), w.b.Bytes()...)
}

func (config *Config) executeCommand(s *ssh.Session, cmd string, sudo bool) ([]byte, error) {
	if s.Stdout != nil {
		return nil, errors.New("ssh: Stdout already set")
	}
	if s.Stderr != nil {
		return nil, errors.New("ssh: Stderr already set")
	}

	b := newSingleWriterReader()
	s.Stdout = &b
	s.Stderr = &b
	done := make(chan bool)

	if sudo {
		stdInWriter, err := s.StdinPipe()
		if err != nil {
			if config.AbortOnError == true {
				log.Fatalf("%s", err)
			}
			return nil, err
		}

		go config.injectSudoPasswordIfNecessary(done, &b, stdInWriter)
	}

	err := s.Run(cmd)
	close(done)
	return b.Bytes(), err
}

func (config *Config) injectSudoPasswordIfNecessary(done <-chan bool, stdOutReader io.Reader, stdInWriter io.Writer) error {
	matchFound := false
	sudoMatcher := newSudoMatcher(config.User)
	for matchFound == false {
		select {
		case <-done:
		default:
			bytesRead := make([]byte, sudoMatcher.totalMatchLength)
			_, err := stdOutReader.Read(bytesRead)
			if err == io.EOF {
				continue
			}

			if err != nil {
				return err
			}
			matchFound = sudoMatcher.Match(bytesRead)
			if matchFound {
				stdInWriter.Write([]byte(config.Password + "\n"))
				break
			}
		}
	}

	return nil
}

type sudoMatcher struct {
	currentIndexMatch int
	currentPrompt     string
	stringToFind      string
	totalMatchLength  int
}

func newSudoMatcher(user string) sudoMatcher {
	stringToFind := fmt.Sprintf("[sudo] password for %s:", user)
	totalMatchLength := len([]byte(stringToFind))
	return sudoMatcher{0, "", stringToFind, totalMatchLength}
}

func (m *sudoMatcher) Match(additionalBytes []byte) bool {
	readString := string(additionalBytes)
	for _, runeVal := range readString {
		if runeVal == rune(m.stringToFind[m.currentIndexMatch]) {
			m.currentPrompt = m.currentPrompt + string(runeVal)
			m.currentIndexMatch++
		} else {
			m.currentPrompt = ""
			m.currentIndexMatch = 0
		}

		if len(m.currentPrompt) == m.totalMatchLength {
			return true
		}
	}
	return false
}

// Run takes a command and runs it on the remote host, using ssh.
func (config *Config) Run(cmd string) (string, error) {
	if config.DisplayOutput == true {
		fmt.Printf("run: %s\n", cmd)
	}
	return config.doRun(cmd, false)
}

// Sudo takes a command and runs it as root on the remote host, using sudo over ssh.
func (config *Config) Sudo(cmd string) (string, error) {
	if config.DisplayOutput == true {
		fmt.Printf("sudo: %s\n", cmd)
	}
	return config.doRun(cmd, true)
}

// Put copies one or more local files to the remote host, using scp. localfiles can
// contain wildcards, and remotefile can be either a directory or a file.
func (config *Config) Put(localfiles string, remotefile string) error {

	files, err := filepath.Glob(localfiles)
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return err
	}
	if len(files) == 0 {
		err = fmt.Errorf("No files match %s", localfiles)
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return err
	}
	for _, localfile := range files {

		fmt.Printf("put: %s %s\n", localfile, remotefile)
		contents, err := ioutil.ReadFile(localfile)
		if err != nil {
			if config.AbortOnError == true {
				log.Fatalf("%s", err)
			}
			return err
		}

		// get the local file mode bits
		fi, err := os.Stat(localfile)
		if err != nil {
			if config.AbortOnError == true {
				log.Fatalf("%s", err)
			}
			return err
		}
		// the file mode bits are the 9 least significant bits of Mode()
		mode := fi.Mode() & 1023

		session, err := config.connect()
		if err != nil {
			if config.AbortOnError == true {
				log.Fatalf("%s", err)
			}
			return err
		}
		var stdoutBuf bytes.Buffer
		var stderrBuf bytes.Buffer
		session.Stdout = &stdoutBuf
		session.Stderr = &stderrBuf

		w, _ := session.StdinPipe()

		_, lfile := filepath.Split(localfile)
		err = session.Start("/usr/bin/scp -qrt " + remotefile)
		if err != nil {
			w.Close()
			session.Close()
			if config.AbortOnError == true {
				log.Fatalf("%s", err)
			}
			return err
		}
		fmt.Fprintf(w, "C%04o %d %s\n", mode, len(contents), lfile /*remotefile*/)
		w.Write(contents)
		fmt.Fprint(w, "\x00")
		w.Close()

		err = session.Wait()
		if err != nil {
			if config.AbortOnError == true {
				log.Fatalf("%s", err)
			}
			session.Close()
			return err
		}

		if config.DisplayOutput == true {
			stdout := stdoutBuf.String()
			stderr := stderrBuf.String()
			fmt.Printf("%s%s", stderr, stdout)
		}
		session.Close()

	}

	return nil
}

// PutString generates a new file on the remote host containing data. The file is created with mode 0644.
func (config *Config) PutString(data string, remotefile string) error {

	if config.DisplayOutput == true {
		fmt.Printf("putstring: %s\n", remotefile)
	}
	session, err := config.connect()
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return err
	}
	var stdoutBuf bytes.Buffer
	var stderrBuf bytes.Buffer
	session.Stdout = &stdoutBuf
	session.Stderr = &stderrBuf

	w, _ := session.StdinPipe()

	_, rfile := filepath.Split(remotefile)
	err = session.Start("/usr/bin/scp -qrt " + remotefile)
	if err != nil {
		w.Close()
		session.Close()
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return err
	}
	fmt.Fprintf(w, "C0644 %d %s\n", len(data), rfile)
	w.Write([]byte(data))
	fmt.Fprint(w, "\x00")
	w.Close()

	err = session.Wait()
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		session.Close()
		return err
	}

	if config.DisplayOutput == true {
		stdout := stdoutBuf.String()
		stderr := stderrBuf.String()
		fmt.Printf("%s%s", stderr, stdout)
	}
	session.Close()

	return nil
}

// Get copies the file from the remote host to the local host, using scp. Wildcards are not currently supported.
func (config *Config) Get(remotefile string, localfile string) error {

	if config.DisplayOutput == true {
		fmt.Printf("get: %s %s\n", remotefile, localfile)
	}

	session, err := config.connect()
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return err
	}
	defer session.Close()

	// TODO: Handle wildcards in remotefile

	var stdoutBuf bytes.Buffer
	var stderrBuf bytes.Buffer
	session.Stdout = &stdoutBuf
	session.Stderr = &stderrBuf
	w, _ := session.StdinPipe()

	err = session.Start("/usr/bin/scp -qrf " + remotefile)
	if err != nil {
		w.Close()
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return err
	}
	// TODO: better error checking than just firing and forgetting these nulls.
	fmt.Fprintf(w, "\x00")
	fmt.Fprintf(w, "\x00")
	fmt.Fprintf(w, "\x00")
	fmt.Fprintf(w, "\x00")
	fmt.Fprintf(w, "\x00")
	fmt.Fprintf(w, "\x00")

	err = session.Wait()
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return err
	}

	stdout := stdoutBuf.String()
	//stderr := stderrBuf.String()

	// first line of stdout contains file information
	fields := strings.SplitN(stdout, "\n", 2)
	mode, _ := strconv.ParseInt(fields[0][1:5], 8, 32)

	// need to generate final local file name
	// localfile could be a directory or a filename
	// if it's a directory, we need to append the remotefile filename
	// if it doesn't exist, we assume file
	var lfile string
	_, rfile := filepath.Split(remotefile)
	l := len(localfile)
	if localfile[l-1] == '/' {
		localfile = localfile[:l-1]
	}
	fi, err := os.Stat(localfile)
	if err != nil || fi.IsDir() == false {
		lfile = localfile
	} else if fi.IsDir() == true {
		lfile = localfile + "/" + rfile
	}
	// there's a trailing 0 in the file that we need to nuke
	l = len(fields[1])
	err = ioutil.WriteFile(lfile, []byte(fields[1][:l-1]), os.FileMode(mode))
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return err
	}
	return nil
}

// Local executes a command on the local host.
func (config *Config) Local(cmd string) (string, error) {
	if config.DisplayOutput == true {
		fmt.Printf("local: %s\n", cmd)
	}
	var command *exec.Cmd
	command = exec.Command("/bin/sh", "-c", cmd)
	var out bytes.Buffer
	command.Stdout = &out
	err := command.Run()
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return "", err
	}
	if config.DisplayOutput == true {
		fmt.Printf("%s", out.String())
	}
	return out.String(), nil
}


text:
package gengapic

import (
	"fmt"
	"net/url"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
	"time"

	"github.com/golang/protobuf/protoc-gen-go/descriptor"
	plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
	"github.com/googleapis/gapic-generator-go/internal/errors"
	"github.com/googleapis/gapic-generator-go/internal/pbinfo"
	"google.golang.org/genproto/googleapis/api/annotations"
	"google.golang.org/protobuf/proto"
)

const (
	emptyValue = "google.protobuf.Empty"
	// protoc puts a dot in front of name, signaling that the name is fully qualified.
	emptyType               = "." + emptyValue
	lroType                 = ".google.longrunning.Operation"
	httpBodyType            = ".google.api.HttpBody"
	alpha                   = "alpha"
	beta                    = "beta"
	disableDeadlinesVar     = "GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE"
	fieldTypeBool           = descriptor.FieldDescriptorProto_TYPE_BOOL
	fieldTypeString         = descriptor.FieldDescriptorProto_TYPE_STRING
	fieldTypeBytes          = descriptor.FieldDescriptorProto_TYPE_BYTES
	fieldTypeMessage        = descriptor.FieldDescriptorProto_TYPE_MESSAGE
	fieldLabelRepeated      = descriptor.FieldDescriptorProto_LABEL_REPEATED
	defaultPollInitialDelay = "time.Second" // 1 second
	defaultPollMaxDelay     = "time.Minute" // 1 minute
)

var headerParamRegexp = regexp.MustCompile(`{([_.a-z0-9]+)`)

// Gen is the entry point for GAPIC generation via the protoc plugin.
func Gen(genReq *plugin.CodeGeneratorRequest) (*plugin.CodeGeneratorResponse, error) {
	var g generator
	if err := g.init(genReq); err != nil {
		return &g.resp, err
	}

	var genServs []*descriptor.ServiceDescriptorProto
	for _, f := range genReq.GetProtoFile() {
		if !strContains(genReq.GetFileToGenerate(), f.GetName()) {
			continue
		}
		if !g.includeMixinInputFile(f.GetName()) {
			continue
		}
		genServs = append(genServs, f.GetService()...)
	}

	g.checkIAMPolicyOverrides(genServs)

	if g.serviceConfig != nil {
		g.apiName = g.serviceConfig.GetTitle()
	}

	protoPkg := g.descInfo.ParentFile[genServs[0]].GetPackage()

	if op, ok := g.descInfo.Type[fmt.Sprintf(".%s.Operation", protoPkg)]; g.opts.diregapic && ok {
		g.aux.customOp = &customOp{
			message:       op.(*descriptor.DescriptorProto),
			handles:       []*descriptor.ServiceDescriptorProto{},
			pollingParams: map[*descriptor.ServiceDescriptorProto][]string{}}
		g.loadCustomOpServices(genServs)
	}

	// Use the proto package from the parent file of the first Service seen.
	if len(genServs) > 0 {
		g.metadata.ProtoPackage = protoPkg
	}
	g.metadata.LibraryPackage = g.opts.pkgPath

	for _, s := range genServs {
		// TODO(pongad): gapic-generator does not remove the package name here,
		// so even though the client for LoggingServiceV2 is just "Client"
		// the file name is "logging_client.go".
		// Keep the current behavior for now, but we could revisit this later.
		outFile := pbinfo.ReduceServName(s.GetName(), "")
		outFile = camelToSnake(outFile)
		outFile = filepath.Join(g.opts.outDir, outFile)

		g.reset()
		if err := g.gen(s); err != nil {
			return &g.resp, err
		}
		g.commit(outFile+"_client.go", g.opts.pkgName)

		g.reset()
		if err := g.genExampleFile(s); err != nil {
			return &g.resp, errors.E(err, "example: %s", s.GetName())
		}
		g.imports[pbinfo.ImportSpec{Name: g.opts.pkgName, Path: g.opts.pkgPath}] = true
		g.commit(outFile+"_client_example_test.go", g.opts.pkgName+"_test")
	}

	g.reset()
	scopes, err := collectScopes(genServs)
	if err != nil {
		return &g.resp, err
	}

	serv := genServs[0]

	g.genDocFile(time.Now().Year(), scopes, serv)
	g.resp.File = append(g.resp.File, &plugin.CodeGeneratorResponse_File{
		Name:    proto.String(filepath.Join(g.opts.outDir, "doc.go")),
		Content: proto.String(g.pt.String()),
	})

	if g.opts.metadata {
		g.reset()
		g.genGapicMetadataFile()
		g.resp.File = append(g.resp.File, &plugin.CodeGeneratorResponse_File{
			Name:    proto.String(filepath.Join(g.opts.outDir, "gapic_metadata.json")),
			Content: proto.String(g.pt.String()),
		})
	}

	if g.aux.customOp != nil {
		g.reset()
		if err := g.customOperationType(); err != nil {
			return &g.resp, err
		}
		g.commit(filepath.Join(g.opts.outDir, "operations.go"), g.opts.pkgName)
	}

	return &g.resp, nil
}

// gen generates client for the given service.
func (g *generator) gen(serv *descriptor.ServiceDescriptorProto) error {
	servName := pbinfo.ReduceServName(serv.GetName(), g.opts.pkgName)

	g.clientHook(servName)
	if err := g.clientOptions(serv, servName); err != nil {
		return err
	}
	if err := g.makeClients(serv, servName); err != nil {
		return err
	}

	for _, v := range g.opts.transports {
		switch v {
		case grpc:
			if err := g.genGRPCMethods(serv, servName); err != nil {
				return err
			}
		case rest:
			if err := g.genRESTMethods(serv, servName); err != nil {
				return err
			}
		}
	}

	// g.aux.lros is a map (set)
	// so that we generate types at most once,
	// but we want a deterministic order to prevent
	// spurious regenerations.
	var lros []*descriptor.MethodDescriptorProto
	for m := range g.aux.lros {
		lros = append(lros, m)
	}
	sort.Slice(lros, func(i, j int) bool {
		return lros[i].GetName() < lros[j].GetName()
	})
	for _, m := range lros {
		if err := g.lroType(servName, serv, m); err != nil {
			return err
		}
	}

	// clear LRO types between services
	g.aux.lros = map[*descriptor.MethodDescriptorProto]bool{}

	var iters []*iterType
	for _, iter := range g.aux.iters {
		// skip iterators that have already been generated in this package
		//
		// TODO(ndietz): investigate generating auxiliary types in a
		// separate file in the same package to avoid keeping this state
		if iter.generated {
			continue
		}

		iter.generated = true
		iters = append(iters, iter)
	}
	sort.Slice(iters, func(i, j int) bool {
		return iters[i].iterTypeName < iters[j].iterTypeName
	})
	for _, iter := range iters {
		g.pagingIter(iter)
	}

	return nil
}

// auxTypes gathers details of types we need to generate along with the client
type auxTypes struct {
	// List of LRO methods. For each method "Foo", we use this to create the "FooOperation" type.
	lros map[*descriptor.MethodDescriptorProto]bool

	// "List" of iterator types. We use these to generate FooIterator returned by paging methods.
	// Since multiple methods can page over the same type, we dedupe by the name of the iterator,
	// which is in turn determined by the element type name.
	iters map[string]*iterType

	customOp *customOp
}

func (g *generator) deadline(s, m string) {
	t, ok := g.grpcConf.Timeout(s, m)
	if !ok {
		return
	}

	g.printf("if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {")
	g.printf("  cctx, cancel := context.WithTimeout(ctx, %d * time.Millisecond)", t)
	g.printf("  defer cancel()")
	g.printf("  ctx = cctx")
	g.printf("}")

	g.imports[pbinfo.ImportSpec{Path: "time"}] = true
}

func (g *generator) getFormattedValue(m *descriptor.MethodDescriptorProto, field string, accessor string) (string, error) {
	f := g.lookupField(m.GetInputType(), field)
	value := ""
	// TODO(noahdietz): need to handle []byte for TYPE_BYTES.
	switch f.GetType() {
	case descriptor.FieldDescriptorProto_TYPE_STRING:
		value = fmt.Sprintf("url.QueryEscape(%s)", accessor)
	case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
		// Double and float are handled the same way.
		fallthrough
	case descriptor.FieldDescriptorProto_TYPE_FLOAT:
		// Format the floating point value with mode 'g' to allow for
		// exponent formatting when necessary, and decimal when adequate.
		// QueryEscape the resulting string in case there is a '+' in the
		// exponent.
		// See golang.org/pkg/fmt for more information on formatting.
		value = fmt.Sprintf(`url.QueryEscape(fmt.Sprintf("%%g", %s))`, accessor)
	case descriptor.FieldDescriptorProto_TYPE_ENUM:
		en := g.descInfo.Type[f.GetTypeName()]

		n, imp, err := g.descInfo.NameSpec(en)
		if err != nil {
			return "", err
		}
		g.imports[imp] = true

		// protobuf Go generates a mapping from number to string
		// representation of an enum, in UPPER_SNAKE_CASE form. The map
		// is named with the enum name and the _name suffix. If it is a
		// nested enum, the name is prefixed with the parent message name.
		// For example, Severity_name or Error_Severity_name.
		value = fmt.Sprintf("%s.%s_name[int32(%s)]", imp.Name, n, accessor)
	default:
		value = accessor
	}
	return value, nil
}

func (g *generator) insertImplicitRequestHeaders(m *descriptor.MethodDescriptorProto, headers [][]string) error {
	if len(headers) == 0 {
		return nil
	}

	seen := map[string]bool{}
	var formats, values strings.Builder
	for _, h := range headers {
		field := h[1]
		// skip fields that have multiple patterns, they use the same accessor
		if _, dupe := seen[field]; dupe {
			continue
		}
		seen[field] = true
		accessor := fmt.Sprintf("req%s", fieldGetter(field))
		accessor, err := g.getFormattedValue(m, field, accessor)
		if err != nil {
			return err
		}
		fmt.Fprintf(&values, " %q, %s,", url.QueryEscape(field), accessor)
		formats.WriteString("%s=%v&")
	}
	// Trim the trailing comma and ampersand symbols.
	f := formats.String()[:formats.Len()-1]
	v := values.String()[:values.Len()-1]
	g.printf("md := metadata.Pairs(\"x-goog-request-params\", fmt.Sprintf(%q,%s))", f, v)
	return nil
}

func (g *generator) insertDynamicRequestHeaders(m *descriptor.MethodDescriptorProto, headers [][]string) error {
	if len(headers) == 0 {
		return nil
	}

	g.printf(`routingHeaders := ""`)
	g.printf("routingHeadersMap := make(map[string]string)")
	for i := range headers {
		namedCaptureRegex := headers[i][0]
		field := headers[i][1]
		headerName := headers[i][2]
		accessor := fmt.Sprintf("req%s", fieldGetter(field))
		regexHelper := fmt.Sprintf("reg.FindStringSubmatch(%s)[1]", accessor)
		regexHelper, err := g.getFormattedValue(m, field, regexHelper)
		if err != nil {
			return err
		}
		// There could be an edge case where the request field is empty and the path template is a wildcard. In that case, we still don't want to send an empty header name.
		g.printf("if reg := regexp.MustCompile(%q); reg.MatchString(%s) && len(%s) > 0 {", namedCaptureRegex, accessor, regexHelper)
		g.printf("  routingHeadersMap[%q] = %s", headerName, regexHelper)
		g.printf("}")
	}
	g.printf("for headerName, headerValue := range routingHeadersMap {")
	g.printf(`  routingHeaders = fmt.Sprintf("%%s%%s=%%s&", routingHeaders, headerName, headerValue)`)
	g.printf("}")
	g.printf(`routingHeaders = strings.TrimSuffix(routingHeaders, "&")`)
	g.imports[pbinfo.ImportSpec{Path: "strings"}] = true
	g.printf("md := metadata.Pairs(\"x-goog-request-params\", routingHeaders)")
	g.imports[pbinfo.ImportSpec{Path: "regexp"}] = true
	return nil
}

func (g *generator) insertRequestHeaders(m *descriptor.MethodDescriptorProto, t transport) {
	p := g.printf
	// Implicit headers are parsed from the google.api.http annotations and are a default
	// behavior for generators per https://google.aip.dev/client-libraries/4222.
	headers := parseImplicitRequestHeaders(m)
	insertHeaders := g.insertImplicitRequestHeaders

	// If dynamic routing annotation exists, it supercedes injection of implicit headers
	// as described in https://google.aip.dev/client-libraries/4222.
	if dynamicRequestHeadersExist(m) {
		headers = parseDynamicRequestHeaders(m)
		insertHeaders = g.insertDynamicRequestHeaders
	}

	// Has request-based header parameters
	if len(headers) > 0 {
		insertHeaders(m, headers)
		p("")
		switch t {
		case grpc:
			p("ctx = insertMetadata(ctx, c.xGoogMetadata, md)")
		case rest:
			p(`headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json"))`)
		}
		g.imports[pbinfo.ImportSpec{Path: "fmt"}] = true
		g.imports[pbinfo.ImportSpec{Path: "net/url"}] = true
		return
	}
	// No request-based header parameters.
	switch t {
	case grpc:
		p("ctx = insertMetadata(ctx, c.xGoogMetadata)")
	case rest:
		p(`headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json"))`)
	}
}

func buildAccessor(field string, rawFinal bool) string {
	// Corner case if passed the result of strings.Join on an empty slice.
	if field == "" {
		return ""
	}

	var ax strings.Builder
	split := strings.Split(field, ".")
	idx := len(split)
	if rawFinal {
		idx--
	}
	for _, s := range split[:idx] {
		fmt.Fprintf(&ax, ".Get%s()", snakeToCamel(s))
	}
	if rawFinal {
		fmt.Fprintf(&ax, ".%s", snakeToCamel(split[len(split)-1]))
	}
	return ax.String()
}

// Given a chained description for a field in a proto message,
// e.g. squid.mantle.mass_kg
// return the string description of the go expression
// describing idiomatic access to the terminal field
// i.e. .GetSquid().GetMantle().GetMassKg()
//
// This is the normal way to retrieve values.
func fieldGetter(field string) string {
	return buildAccessor(field, false)
}

// Given a chained description for a field in a proto message,
// e.g. squid.mantle.mass_kg
// return the string description of the go expression
// describing direct access to the terminal field
// i.e. .GetSquid().GetMantle().MassKg
//
// This is used for determining field presence for terminal optional fields.
func directAccess(field string) string {
	return buildAccessor(field, true)
}

func (g *generator) lookupField(msgName, field string) *descriptor.FieldDescriptorProto {
	var desc *descriptor.FieldDescriptorProto
	msg := g.descInfo.Type[msgName]

	// If the message doesn't exist, fail cleanly.
	if msg == nil {
		return desc
	}

	msgProto := msg.(*descriptor.DescriptorProto)
	msgFields := msgProto.GetField()

	// Split the key name for nested fields, and traverse the message chain.
	for _, seg := range strings.Split(field, ".") {
		// Look up the desired field by name, stopping if the leaf field is
		// found, continuing if the field is a nested message.
		for _, f := range msgFields {
			if f.GetName() == seg {
				desc = f

				// Search the nested message for the next segment of the
				// nested field chain.
				if f.GetType() == descriptor.FieldDescriptorProto_TYPE_MESSAGE {
					msg = g.descInfo.Type[f.GetTypeName()]
					msgProto = msg.(*descriptor.DescriptorProto)
					msgFields = msgProto.GetField()
				}
				break
			}
		}
	}
	return desc
}

func (g *generator) appendCallOpts(m *descriptor.MethodDescriptorProto) {
	g.printf("opts = append(%[1]s[0:len(%[1]s):len(%[1]s)], opts...)", "(*c.CallOptions)."+*m.Name)
}

// This is a helper function that checks whether a description contains a Deprecated header.
func containsDeprecated(com string) bool {
	for _, s := range strings.Split(com, "\n") {
		if strings.HasPrefix(s, "Deprecated:") {
			return true
		}
	}
	return false
}

func (g *generator) methodDoc(m *descriptor.MethodDescriptorProto) {
	com := g.comments[m]

	// If there's no comment and the method is not deprecated, adding method name is just confusing.
	if !m.GetOptions().GetDeprecated() && com == "" {
		return
	}

	if containsTransport(g.opts.transports, rest) && m.GetClientStreaming() {
		com = fmt.Sprintf("%s\n\nThis method is not supported for the REST transport.", com)
	}
	// If the method is marked as deprecated and there is no comment, then add default deprecation comment.
	// If the method has a comment but it does not include a deprecation notice, then append a default deprecation notice.
	// If the method includes a deprecation notice at the beginning of the comment, prepend a comment stating the method is deprecated and use the included deprecation notice.
	if m.GetOptions().GetDeprecated() {
		if com == "" {
			com = fmt.Sprintf("\n is deprecated.\n\nDeprecated: %s may be removed in a future version.", m.GetName())
		} else if strings.HasPrefix(com, "Deprecated:") {
			com = fmt.Sprintf("\n is deprecated.\n\n%s", com)
		} else if !containsDeprecated(com) {
			com = fmt.Sprintf("%s\n\nDeprecated: %s may be removed in a future version.", com, m.GetName())
		}
	}
	com = strings.TrimSpace(com)

	// Prepend the method name to all non-empty comments.
	com = m.GetName() + " " + lowerFirst(com)

	g.comment(com)
}

func (g *generator) comment(s string) {
	s = strings.TrimSpace(s)
	if s == "" {
		return
	}

	s = mdPlain(s)

	lines := strings.Split(s, "\n")
	for _, l := range lines {
		if strings.TrimSpace(l) == "" {
			g.printf("//")
		} else {
			g.printf("// %s", l)
		}
	}
}

// Similar functionality to 'comment', except specifically used for generating formatted code snippets.
func (g *generator) codesnippet(s string) {
	if s == "" {
		return
	}

	lines := strings.Split(s, "\n")
	for _, l := range lines {
		if strings.TrimSpace(l) == "" {
			g.printf("//")
		} else {
			// At least 2 spaces after the // are necessary for GoDoc code snippet formatting.
			g.printf("//  %s", l)
		}
	}
}

// isLRO determines if a given Method is a longrunning operation, ignoring
// those defined by the longrunning proto package.
func (g *generator) isLRO(m *descriptor.MethodDescriptorProto) bool {
	return m.GetOutputType() == lroType && g.descInfo.ParentFile[m].GetPackage() != "google.longrunning"
}

func (g *generator) isPaginated(m *descriptor.MethodDescriptorProto) bool {
	pf, _, err := g.getPagingFields(m)
	if err != nil {
		return false
	}

	return pf != nil
}

func (g *generator) returnType(m *descriptor.MethodDescriptorProto) (string, error) {
	outType := g.descInfo.Type[m.GetOutputType()]
	outSpec, err := g.descInfo.ImportSpec(outType)
	if err != nil {
		return "", err
	}
	info := getHTTPInfo(m)

	// Regular return type.
	retTyp := fmt.Sprintf("*%s.%s", outSpec.Name, outType.GetName())

	// Wrap the raw operation with a custom operation type.
	if g.isCustomOp(m, info) {
		// This will only be *Operation to start.
		retTyp = fmt.Sprintf("*%s", g.aux.customOp.message.GetName())
	}

	return retTyp, nil
}

func parseImplicitRequestHeaders(m *descriptor.MethodDescriptorProto) [][]string {
	var matches [][]string

	eHTTP := proto.GetExtension(m.GetOptions(), annotations.E_Http)
	if m == nil || m.GetOptions() == nil {
		return nil
	}

	http := eHTTP.(*annotations.HttpRule)
	rules := []*annotations.HttpRule{http}
	rules = append(rules, http.GetAdditionalBindings()...)

	for _, rule := range rules {
		pattern := ""

		switch rule.GetPattern().(type) {
		case *annotations.HttpRule_Get:
			pattern = rule.GetGet()
		case *annotations.HttpRule_Post:
			pattern = rule.GetPost()
		case *annotations.HttpRule_Patch:
			pattern = rule.GetPatch()
		case *annotations.HttpRule_Put:
			pattern = rule.GetPut()
		case *annotations.HttpRule_Delete:
			pattern = rule.GetDelete()
		}

		matches = append(matches, headerParamRegexp.FindAllStringSubmatch(pattern, -1)...)
	}

	return matches
}

// Determine whether routing annotation exists
func dynamicRequestHeadersExist(m *descriptor.MethodDescriptorProto) bool {
	return proto.HasExtension(m.GetOptions(), annotations.E_Routing)
}

// Parse routing annotations to be used as request headers
func parseDynamicRequestHeaders(m *descriptor.MethodDescriptorProto) [][]string {
	var matches [][]string

	reqHeaders := proto.GetExtension(m.GetOptions(), annotations.E_Routing)
	routingRule := reqHeaders.(*annotations.RoutingRule)
	routingParameter := routingRule.GetRoutingParameters()

	for _, param := range routingParameter {
		pathTemplateRegex := convertPathTemplateToRegex(param.GetPathTemplate())
		fieldReq := param.Field
		headerName := getHeaderName(param.GetPathTemplate())
		if len(headerName) < 1 {
			headerName = fieldReq
		}
		paramSlice := []string{pathTemplateRegex, fieldReq, headerName}
		matches = append(matches, paramSlice)
	}

	return matches
}


text:
package com.intellij.execution.lineMarker;

import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.daemon.LineMarkerSettings;
import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;

class RunnableStatusListener implements DaemonCodeAnalyzer.DaemonListener {

  @Override
  public void daemonFinished(@NotNull Collection<FileEditor> fileEditors) {
    if (!LineMarkerSettings.getSettings().isEnabled(new RunLineMarkerProvider())) return;

    for (FileEditor fileEditor : fileEditors) {
      if (fileEditor instanceof TextEditor) {
        Editor editor = ((TextEditor)fileEditor).getEditor();
        Project project = editor.getProject();
        VirtualFile file = fileEditor.getFile();
        if (file != null && project != null) {
          boolean hasRunMarkers = ContainerUtil.findInstance(
            DaemonCodeAnalyzerImpl.getLineMarkers(editor.getDocument(), project),
            RunLineMarkerProvider.RunLineMarkerInfo.class) != null;
          FileViewProvider vp = PsiManager.getInstance(project).findViewProvider(file);
          if (hasRunMarkers || (vp != null && weMayTrustRunGutterContributors(vp))) {
            RunLineMarkerProvider.markRunnable(file, hasRunMarkers);
          }
        }
      }
    }
  }

  private static boolean weMayTrustRunGutterContributors(FileViewProvider vp) {
    for (PsiFile file : vp.getAllFiles()) {
      for (RunLineMarkerContributor contributor : RunLineMarkerContributor.EXTENSION.allForLanguage(file.getLanguage())) {
        if (!contributor.producesAllPossibleConfigurations(file)) {
          return false;
        }
      }
    }
    return true;
  }
}


text:
<?php
use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\builder\Form;
use kartik\datecontrol\DateControl;
use kartik\widgets\FileInput;
use kartik\widgets\SwitchInput;

$this->title='Parsing / Upload Operator excel';
$this->params['breadcrumbs'][] = ['label' => 'Operators', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;

/* @var $this yii\web\View */
/* @var $model app\models\Operator */
/* @var $form yii\widgets\ActiveForm */
?>

Parsing Excel

            <?php
            $form = ActiveForm::begin([
                        'type' => ActiveForm::TYPE_HORIZONTAL,
                        'options' => ['enctype' => 'multipart/form-data']   // important, needed for file upload
            ]);
            ?>

                    <?php
                    echo $form->field($model, 'fileori')->widget(FileInput::classname(), [
                        'options' => ['accept' => '.xls'],
                    ]);
                    ?>

                    <?=                    Html::submitButton('Upload ', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'])
                    ?>

            <?php
            ActiveForm::end();
            ?>

            Format Sample : <a href="<?php echo Yii::$app->urlManager->createUrl('notification/sample');?>">notification.xls


text:
'use strict';

const serviceUtils = require('../serviceUtils');

/**
 * @summary Return Order Dialog ID based on name
 * @param  {String}   labelArg  Label or name of data set in OrderDialog collection
 * @param  {Object}   context  Session context information associated with the service call.
 * @param  {Function} callback Function called on process completion, with standard (err, result) signature.
 * @return {Integer}           Integer extracted from urn
 *
 * @memberof OrderMetaService
 * @instance
 */

function lookupOrderDialogId(labelArg, context, callback) {
    this.find('OrderDialog', {
        query: {
            label: labelArg,
            localStationNumber: context.stationId,
        },
        projection: serviceUtils.createProjection(['id']),
        options: { limit: 1 },
    }).then((res) => {
        const val = res ? res[0] : '';
        callback(null, val || '');
    }).catch(err => callback(err));
}

module.exports = {
    lookupOrderDialogId,
};


text:
let bsCodes = require('./data/busStopCodes.json');
let bsNames = require('./data/busStopNames.json');
let request = require('request');
let xmlReader = require('xmlreader');
let _ = require('underscore');
let jsdom = require('jsdom');

let correctXML = (xmlString) => {
	return xmlString.split('\\\"').join('\"').split('\\r').join('').split('\\n').join('').split('\\t').join('').slice(1,-1);
};

let _getStopInfoByCode = (code) => {
	return new Promise((resolve, reject)=>{
		request({
			method: 'GET',
			uri: 'https://application2.irantracking.com/FrontEndETA/MOBIL/api/ETA/GetETAPlusTripText2?currentStopId='+code+'&identifier=1&sequence=1'
		},(err,response,body)=>{
			if (err) reject(err);
			else {
				xmlReader.read(correctXML(body),(xmlError,xmlResponse)=>{
					if (xmlError) reject(xmlError);
					let result = xmlResponse.ETARoot.attributes().Result;
					let requestDate = xmlResponse.ETARoot.attributes().RequestDate;
					let currentStopName = xmlResponse.ETARoot.CurrentStop.attributes().Name;
					let currentStopCode = xmlResponse.ETARoot.CurrentStop.attributes().Code;
					let currentStopLng = xmlResponse.ETARoot.CurrentStop.attributes().Lng;
					let currentStopLat = xmlResponse.ETARoot.CurrentStop.attributes().Lat;
					let numberOfStops = xmlResponse.ETARoot.Stops.Stop.count();
					let stops = [];
					for (let i=0;i<numberOfStops;i++) {
						stops.push({
							routeCode: xmlResponse.ETARoot.Stops.Stop.at(i).attributes().RouteCode,
							originationName: xmlResponse.ETARoot.Stops.Stop.at(i).attributes().OriginationName,
							destinationName: xmlResponse.ETARoot.Stops.Stop.at(i).attributes().DestinationName,
							order: xmlResponse.ETARoot.Stops.Stop.at(i).attributes().Order,
							routeType: xmlResponse.ETARoot.Stops.Stop.at(i).attributes().RouteType,
							text: xmlResponse.ETARoot.Stops.Stop.at(i).ETA.attributes().Text,
							value: xmlResponse.ETARoot.Stops.Stop.at(i).ETA.attributes().Value,
							bus: xmlResponse.ETARoot.Stops.Stop.at(i).ETA.attributes().Bus
						});
					}
					resolve({
						result: result,
						requestDate: requestDate,
						currentStopName: currentStopName,
						currentStopCode: currentStopCode,
						currentStopLng: currentStopLng,
						currentStopLat: currentStopLat,
						numberOfStops: numberOfStops,
						stops: stops
					});
				})
			}
		})
	});
};

let _getStopRemainingTimesByCode = (code) => {
	return _getStopInfoByCode(code).then((stopInfo)=>{
		return stopInfo.stops;
	})
};

let _getStopRemainingTimesByName = (name) => {
	return _getStopRemainingTimesByCode(bsCodes[name]);
};

let _getRemainingTimes = (codeOrName) => {
	return !!Number(codeOrName)?_getStopRemainingTimesByCode(Number(codeOrName)):_getStopRemainingTimesByName(codeOrName);
};

let _updateStops = () => {
	return new Promise((resolve,reject)=>{
		jsdom.env('http://services20.tehran.ir/زمانبندی-حرکت-اتوبوس-ها/جدول-زمان-بندی-حرکت-اتوبوس-زنده',
			['http://code.jquery.com/jquery.js'],
			(err,window)=>{
				if (err) reject(err);
				else {
					// let $ = window.$;
					// Where are you fucking last script text?!
				}
			});
	});
};

let _getStopNames = () => {
	return _.keys(bsCodes);
};

let _getStops = () => {
	return bsNames;
};
//send get Request to: https://application2.irantracking.com/FrontEndETA/MOBIL/api/ETA/GetBusStopStaticTimeTable?currentStopId=1662&routeId=273&direction=82
let _getStopTimeTable = (stopCode,route,direction) => {
	return new Promise((resolve,reject)=>{
		request({
			method: 'GET',
			uri: 'https://application2.irantracking.com/FrontEndETA/MOBIL/api/ETA/GetBusStopStaticTimeTable?currentStopId='+stopCode+'&routeId='+route+'&direction=' + direction
		},(err,response,body)=>{
			if (err) reject(err);
			else {
				xmlReader.read(correctXML(body),(xmlError,xmlResponse)=>{
					if (xmlError) reject(xmlError);
					else {
						let result = xmlResponse.BusStopStaticTimeTable.attributes().Result;
						let requestDate = xmlResponse.BusStopStaticTimeTable.attributes().RequestDate;
						let dayType = xmlResponse.BusStopStaticTimeTable.attributes().DayType;
						let normal = xmlResponse.BusStopStaticTimeTable.Normal.text().split(';');
						let halfHoliday = xmlResponse.BusStopStaticTimeTable.HalfHoliday.text().split(';');
						let holiday = xmlResponse.BusStopStaticTimeTable.Holiday.text().split(';');
					}
				})
			}
		});
	});
}; //we don't know about direction

let _getStopLocationByName = (name) => {
	return _getStopInfoByCode(bsCodes[name]);
};

let _getStopLocationByCode = (code) => {
	return _getStopInfoByCode(code).then((stopInfo)=>{
		return {
			name: stopInfo.currentStopName,
			code: stopInfo.currentStopCode,
			lng: stopInfo.currentStopLng,
			lat: stopInfo.currentStopLat
		}
	})
};

let _getStopLocation = (codeOrName) => {
	return !!Number(codeOrName)?_getStopLocationByCode(Number(codeOrName)):_getStopLocationByName(codeOrName);
};

_getRemainingTimes('فروزانفر').then((res)=>{
	console.log(res);
})

module.exports = {
	getRemainingTimes: _getRemainingTimes,
	updateStops: _updateStops,
	stopNames: _getStopNames(),
	stops: _getStops(),
	getStopTimeTable: _getStopTimeTable,
	getStopLocation: _getStopLocation
};


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.InjectManifest = exports.GenerateSW = void 0;
const generate_sw_1 = require("./generate-sw");
Object.defineProperty(exports, "GenerateSW", { enumerable: true, get: function () { return generate_sw_1.GenerateSW; } });
const inject_manifest_1 = require("./inject-manifest");
Object.defineProperty(exports, "InjectManifest", { enumerable: true, get: function () { return inject_manifest_1.InjectManifest; } });
// TODO: remove this in v7.
// See https://github.com/GoogleChrome/workbox/issues/3033
exports.default = { GenerateSW: generate_sw_1.GenerateSW, InjectManifest: inject_manifest_1.InjectManifest };


text:
package org.sourcepit.b2.internal.generator;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.maven.model.Dependency;
import org.sourcepit.b2.model.interpolation.internal.module.B2MetadataUtils;
import org.sourcepit.b2.model.interpolation.internal.module.DefaultIncludesAndRequirementsResolver;
import org.sourcepit.b2.model.interpolation.internal.module.ResolutionContextResolver;
import org.sourcepit.b2.model.module.AbstractModule;
import org.sourcepit.b2.model.module.AbstractStrictReference;
import org.sourcepit.b2.model.module.FeatureInclude;
import org.sourcepit.b2.model.module.FeatureProject;
import org.sourcepit.b2.model.module.FeaturesFacet;
import org.sourcepit.b2.model.module.ModuleModelFactory;
import org.sourcepit.b2.model.module.PluginInclude;
import org.sourcepit.b2.model.module.PluginProject;
import org.sourcepit.b2.model.module.PluginsFacet;
import org.sourcepit.b2.model.module.RuledReference;
import org.sourcepit.b2.model.module.StrictReference;
import org.sourcepit.b2.model.module.internal.util.ReferenceUtils;
import org.sourcepit.common.manifest.osgi.Version;

import com.google.common.base.Objects;
import com.google.common.collect.SetMultimap;

@Named
public class TargetPlatformRequirementsCollector {
   private final ResolutionContextResolver contextResolver;

   @Inject
   public TargetPlatformRequirementsCollector(ResolutionContextResolver contextResolver) {
      this.contextResolver = contextResolver;
   }

   public List<Dependency> collectRequirements(AbstractModule module, boolean isTestScope) {
      checkArgument(module != null, "Module may not be null.");

      final List<Dependency> requirements = new ArrayList<Dependency>();
      addModuleRequirements(requirements, module, isTestScope);
      return requirements;
   }

   public List<Dependency> collectRequirements(PluginProject pluginProject) {
      checkArgument(pluginProject != null, "Plugin project may not be null.");

      final List<Dependency> requirements = new ArrayList<Dependency>();
      final AbstractModule module = pluginProject.getParent().getParent();
      addPluginRequirements(requirements, module, pluginProject);
      return requirements;
   }

   private void addModuleRequirements(final List<Dependency> requirements, AbstractModule module, boolean isTestScope) {
      final SetMultimap<AbstractModule, FeatureProject> scope = contextResolver.resolveResolutionContext(module,
         isTestScope);

      for (FeatureProject featureProject : scope.values()) {
         Dependency dependency = new Dependency();
         dependency.setArtifactId(featureProject.getId());
         final String version = Version.parse(featureProject.getVersion()).trimQualifier().toString();
         dependency.setVersion(version);
         dependency.setType("eclipse-feature");

         addUnique(requirements, dependency);
      }
   }

   private void addPluginRequirements(final List<Dependency> requirements, AbstractModule module,
      PluginProject pluginProject) {
      final FeatureProject featureProject = findIncludingFeature(pluginProject);
      checkState(featureProject != null, "Plug-in '" + pluginProject.getId() + "' is not contained in any feature.");

      boolean isTestScope = pluginProject.isTestPlugin();
      if (!isTestScope && featureProject != null) {
         isTestScope = B2MetadataUtils.isTestFeature(featureProject);
      }

      addModuleRequirements(requirements, module, isTestScope);
      addFeatureRequirements(requirements, featureProject);
   }

   private static void addFeatureRequirements(final List<Dependency> requirements, FeatureProject featureProject) {
      for (FeatureInclude includedFeature : featureProject.getIncludedFeatures()) {
         Dependency requirement = toRequirement(includedFeature);
         requirement.setType("eclipse-feature");
         addUnique(requirements, requirement);
      }

      final AbstractModule module = featureProject.getParent().getParent();

      for (PluginInclude includedPlugin : featureProject.getIncludedPlugins()) {
         if (module.resolveReference(includedPlugin, PluginsFacet.class) == null) {
            Dependency requirement = toRequirement(includedPlugin);
            requirement.setType("eclipse-plugin");
            addUnique(requirements, requirement);
         }
      }

      for (RuledReference requiredFeature : featureProject.getRequiredFeatures()) {
         Dependency requirement = toRequirement(requiredFeature);
         requirement.setType("eclipse-feature");
         addUnique(requirements, requirement);
      }

      for (RuledReference requiredPlugin : featureProject.getRequiredPlugins()) {
         final Dependency requirement = toRequirement(requiredPlugin);
         requirement.setType("eclipse-plugin");
         addUnique(requirements, requirement);
      }
   }

   private static void addUnique(final List<Dependency> requirements, Dependency requirement) {
      for (Dependency dependency : requirements.toArray(new Dependency[requirements.size()])) {
         if (Objects.equal(dependency.getArtifactId(), requirement.getArtifactId())) {
            if (Objects.equal(dependency.getType(), requirement.getType())) {
               requirements.remove(dependency);
            }
         }
      }
      requirements.add(requirement);
   }

   private static FeatureProject findIncludingFeature(PluginProject pluginProject) {
      FeatureProject featureProject = DefaultIncludesAndRequirementsResolver.findFeatureProjectForPluginsFacet(
         pluginProject.getParent(), false);
      if (featureProject == null) {
         final String featureId = B2MetadataUtils.getBrandedFeature(pluginProject);
         if (featureId != null) {
            final StrictReference reference = ModuleModelFactory.eINSTANCE.createStrictReference();
            reference.setId(featureId);

            final FeatureProject brandedFeature = pluginProject.getParent()
               .getParent()
               .resolveReference(reference, FeaturesFacet.class);

            if (brandedFeature != null && isIncluded(brandedFeature, pluginProject)) {
               featureProject = brandedFeature;
            }
         }
      }
      return featureProject;
   }

   private static boolean isIncluded(final FeatureProject featureProject, PluginProject pluginProject) {
      for (PluginInclude pluginInclude : featureProject.getIncludedPlugins()) {
         if (pluginInclude.isSatisfiableBy(pluginProject)) {
            return true;
         }
      }
      return false;
   }

   private static Dependency toRequirement(RuledReference featureReference) {
      final Dependency dependency = new Dependency();
      dependency.setArtifactId(featureReference.getId());
      dependency.setVersion(ReferenceUtils.toVersionRange(featureReference.getVersion(),
         featureReference.getVersionMatchRule()).toString());
      return dependency;
   }

   static Dependency toRequirement(AbstractStrictReference strictReference) {
      final Dependency dependency = new Dependency();
      dependency.setArtifactId(strictReference.getId());
      String version = strictReference.getVersion();
      if (version != null && version.endsWith(".qualifier")) {
         version = version.substring(0, version.length() - ".qualifier".length());
      }
      dependency.setVersion(version);
      return dependency;
   }
}


text:
//**************************************************************************
//
//
//                       National Institute Of Standards and Technology
//                                     DTS Version 1.0
//
//                                      Comment Interface
//
// Written by: Carmelo Montanez
//
// Ported to System.Xml by: Mizrahi Rafael rafim@mainsoft.com
// Mainsoft Corporation (c) 2003-2004
//
//**************************************************************************
using System;
using System.Xml;
using nist_dom;
using NUnit.Framework;

namespace nist_dom.fundamental
{
    /// <summary>
    /// Summary description for Comment.
    /// </summary>
    [TestFixture]
    public class CommentTest : Assertion//,ITest
    {
        public static int i = 1;
/*
        public testResults[] RunTests()
        {
            testResults[] tests = new testResults[] {core0001CO()};

            return tests;
        }
*/
        //------------------------ test case core-0001CO ------------------------
        //
        // Testing feature - A comment is all the characters between the starting
        //                   "<!--" and ending "-->" strings.
        //
        // Testing approach - Retrieve the third child in the DOM document.
        //                    This node is a comment node and its value is the
        //                    content of the node.
        //
        // Semantic Requirements: 1
        //
        //----------------------------------------------------------------------------

	[Test]
        public void core0001CO()
        {
            string computedValue = "";
            string expectedValue = " This is comment number 1.";
            System.Xml.XmlNode testNode = null;

            testResults results = new testResults("Core0001CO");

            results.description = "A comment is all the characters between the " + "start comment and end comment strings.";
            //
            // Retrieve the targeted data and access its nodeValue.
            //
            testNode = util.getDOMDocument().ChildNodes.Item(2);
            computedValue = testNode.Value;//nodeValue;
            //
            // Write out results
            //

            results.expected = expectedValue;
            results.actual = computedValue;

            AssertEquals (results.expected, results.actual);
        }

        //------------------------ End test case core-0001CO --------------------------
    }

}


text:
<!DOCTYPE html>
<!--
Copyright (c) 2013 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.
-->

<link rel="import" href="/tracing/base/base.html">
<script>
'use strict';

tr.exportTo('tr.e.cc', function() {
  /**
   * @constructor
   */
  function PictureAsImageData(picture, errorOrImageData) {
    this.picture_ = picture;
    if (errorOrImageData instanceof ImageData) {
      this.error_ = undefined;
      this.imageData_ = errorOrImageData;
    } else {
      this.error_ = errorOrImageData;
      this.imageData_ = undefined;
    }
  }

  /**
   * Creates a new pending PictureAsImageData (no image data and no error).
   *
   * @return {PictureAsImageData} a new pending PictureAsImageData.
   */
  PictureAsImageData.Pending = function(picture) {
    return new PictureAsImageData(picture, undefined);
  };

  PictureAsImageData.prototype = {
    get picture() {
      return this.picture_;
    },

    get error() {
      return this.error_;
    },

    get imageData() {
      return this.imageData_;
    },

    isPending() {
      return this.error_ === undefined && this.imageData_ === undefined;
    },

    asCanvas() {
      if (!this.imageData_) return;

      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');

      canvas.width = this.imageData_.width;
      canvas.height = this.imageData_.height;
      ctx.putImageData(this.imageData_, 0, 0);
      return canvas;
    }
  };

  return {
    PictureAsImageData,
  };
});
</script>


text:
function addIFrame(host) {
  document.write(['<iframe src="http://', host, ':', location.port,
                  '/files/extensions/api_test/executescript',
                  '/permissions/empty.html"> </iframe>'].join(''));
}
addIFrame("a.com");
addIFrame("b.com");
addIFrame("c.com");


text:
package mprog.nl.programmeerproject.Classes;

/**
 * UserRequestItem class that gives the data of the specific user that wants to chat with you.
 */
public class UserReqestItem {

    String userName;
    String data;
    String age;
    String gender;
    String description;

    public UserReqestItem(String userName, String data, String age, String gender, String description) {
        super();
        this.userName = userName;
        this.data = data;
        this.age = age;
        this.gender = gender;
        this.description = description;
    }

    public UserReqestItem() {

    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getData() {
        return data;
    }

    public void setData(String messageUser) {
        this.data = data;
    }

    public String getAge() {
        return age;
    }

    public String getGender() {
        return gender;
    }

    public String getDescription() {
        return description;
    }

}


text:
package auth0;

import com.auth0.jwt.JWTVerifier;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Map;

/**
 * Strange!!!!!
 * (1) dieses Tool schlägt auch fehl: http://jwt.1blau.com/#/
 * (2) dieses Tool funzt: http://jwt.io/
 */
public class JwtAuthVerifier {

  public static void main(String[] args) {
    try {
      Map<String, Object> payload = verify(new JwtAuthProvider().create());

      // Get custom fields from decoded Payload
      System.out.println(payload.get("name"));
    } catch (SignatureException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static Map<String, Object> verify(String token) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException {
    final String secret = "This is a secret";
    return new JWTVerifier(secret)
        .verify(token);
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

<title>
FFTW FAQ - Section 5
</title>
<link rev="made" href="mailto:fftw@fftw.org">
<link rel="Contents" href="index.html">
<link rel="Start" href="index.html">
<link rel="Previous" href="section4.html"><link rel="Bookmark" title="FFTW FAQ" href="index.html">

FFTW FAQ - Section 5

Known bugs

Q5.1. FFTW 1.1 crashes in rfftwnd on Linux.

Q5.2. The MPI transforms in FFTW 1.2 give incorrect results/leak
memory.

Q5.3. The test programs in FFTW 1.2.1 fail when I change FFTW to use single
precision.

Q5.4. The test program in FFTW 1.2.1 fails for n >
46340.

Q5.5. The threaded code fails on Linux Redhat 5.0

Q5.6. FFTW 2.0's rfftwnd fails for rank > 1 transforms with a final
dimension >= 65536.

Q5.7. FFTW 2.0's complex transforms give the wrong results with prime
factors 17 to 97.

Q5.8. FFTW 2.1.1's MPI test programs crash with
MPICH.

Q5.9. FFTW 2.1.2's multi-threaded transforms don't work on
AIX.

Q5.10. FFTW 2.1.2's complex transforms give incorrect results for large prime
sizes.

Q5.11. FFTW 2.1.3's multi-threaded transforms don't give any speedup on
Solaris.

Q5.12. FFTW 2.1.3 crashes on AIX.

Question 5.1.  FFTW 1.1 crashes in rfftwnd on
Linux.

This bug was fixed in FFTW 1.2.  There was a bug in
rfftwnd causing an incorrect amount of memory to be allocated.  The bug showed
up in Linux with libc-5.3.12 (and nowhere else that we know of).

Question 5.2.  The MPI transforms in FFTW 1.2 give incorrect
results/leak memory.

These bugs were corrected in FFTW 1.2.1.  The MPI transforms (really,
just the transpose routines) in FFTW 1.2 had bugs that could cause
errors in some situations.

Question 5.3.  The test programs in FFTW 1.2.1 fail when I change FFTW
to use single precision.

This bug was fixed in FFTW 1.3.  (Older versions of FFTW did
work in single precision, but the test programs didn't--the error
tolerances in the tests were set for double precision.)

Question 5.4.  The test program in FFTW 1.2.1 fails for n >
46340.

This bug was fixed in FFTW 1.3.  FFTW 1.2.1 produced the right answer,
but the test program was wrong.  For large n, n*n in the naive
transform that we used for comparison overflows 32 bit integer
precision, breaking the test.

Question 5.5.  The threaded code fails on Linux Redhat
5.0

We had problems with glibc-2.0.5.  The code should work with
glibc-2.0.7.

Question 5.6.  FFTW 2.0's rfftwnd fails for rank > 1 transforms
with a final dimension >= 65536.

This bug was fixed in FFTW 2.0.1.  (There was a 32-bit integer
overflow due to a poorly-parenthesized expression.)

Question 5.7.  FFTW 2.0's complex transforms give the wrong results
with prime factors 17 to 97.

There was a bug in the complex transforms that could cause incorrect
results under (hopefully rare) circumstances for lengths with
intermediate-size prime factors (17-97).  This bug was fixed in FFTW
2.1.1.

Question 5.8.  FFTW 2.1.1's MPI test programs crash with
MPICH.

This bug was fixed in FFTW 2.1.2.  The 2.1/2.1.1 MPI test programs
crashed when using the MPICH implementation of MPI with the
ch_p4 device (TCP/IP); the transforms themselves worked fine.

Question 5.9.  FFTW 2.1.2's multi-threaded transforms don't work on
AIX.

This bug was fixed in FFTW 2.1.3.  The multi-threaded transforms in
previous versions didn't work with AIX's
pthreads implementation, which idiosyncratically creates threads in detached
(non-joinable) mode by default.

Question 5.10.  FFTW 2.1.2's complex transforms give incorrect results
for large prime sizes.

This bug was fixed in FFTW 2.1.3.  FFTW's complex-transform algorithm
for prime sizes (in versions 2.0 to 2.1.2) had an integer overflow
problem that caused incorrect results for many primes greater than
32768 (on 32-bit machines).  (Sizes without large prime factors are
not affected.)

Question 5.11.  FFTW 2.1.3's multi-threaded transforms don't give any
speedup on Solaris.

This bug was fixed in FFTW 2.1.4.  (By default, Solaris creates
threads that do not parallelize over multiple processors, so one has
to request the proper behavior specifically.)

Question 5.12.  FFTW 2.1.3 crashes on AIX.

The FFTW 2.1.3 configure script picked incorrect compiler flags for the xlc compiler on newer IBM processors.  This
is fixed in FFTW 2.1.4.

Back: Internals of FFTW.

Return to contents.

<address>
Matteo Frigo and Steven G. Johnson / fftw@fftw.org
- 04 March 2014
</address>

Extracted from FFTW Frequently Asked Questions with Answers,
Copyright © 2014 Matteo Frigo and Massachusetts Institute of Technology.


text:
package com.koonen.photostream;

/**
 *
 * @author Glick
 *
 */
public interface WallPaperExecutor {
	void onCleanWallPaper();
	void onShowWallpaperSuccess();
	void onFinish();
}


text:
layout: post
date: 2017-01-06
title: Project Benson
---
## Exploring MTA Data
Using data from SFMTA to explore turnstile data. This was a first introduction to metis and my classmates. The work was difficult at first, but I was very excited to get started quickly. We were given a team and asked to solve a problem.


text:
package com.netty.scoket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.UUID;

/**
 * Created by wangyong on 2017/5/19.
 */
public class MyServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + ":" + msg);
        ctx.channel().writeAndFlush("from server:" + UUID.randomUUID());
    }

    /**
     * 异常处理
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}


text:
namespace RosettaStone::SimpleTasks
{
HeroPowerTask::HeroPowerTask(Entity* target) : ITask(nullptr, target)
{
    // Do nothing
}

TaskID HeroPowerTask::GetTaskID() const
{
    return TaskID::HERO_POWER;
}

TaskStatus HeroPowerTask::Impl(Player& player)
{
    HeroPower* power = player.GetHero()->heroPower;

    if (!Generic::IsPlayableByPlayer(player, power) ||
        !Generic::IsPlayableByCardReq(power) ||
        !Generic::IsValidTarget(power, m_target))
    {
        return TaskStatus::STOP;
    }

    // Spend mana to play cards
    if (power->GetCost() > 0)
    {
        int tempUsed = std::min(player.GetTemporaryMana(), power->GetCost());
        player.SetTemporaryMana(player.GetTemporaryMana() - tempUsed);
        player.SetUsedMana(player.GetUsedMana() + power->GetCost() - tempUsed);
    }

    // Process target trigger
    if (m_target != nullptr)
    {
        Trigger::ValidateTriggers(player.GetGame(), power,
                                  SequenceType::TARGET);
        player.GetGame()->taskQueue.StartEvent();
        player.GetGame()->triggerManager.OnTargetTrigger(&player, power);
        player.GetGame()->ProcessTasks();
        player.GetGame()->taskQueue.EndEvent();
    }

    // Process power tasks
    player.GetGame()->taskQueue.StartEvent();
    power->ActivateTask(PowerType::POWER, m_target);
    player.GetGame()->ProcessTasks();
    player.GetGame()->taskQueue.EndEvent();

    player.GetGame()->ProcessDestroyAndUpdateAura();

    power->SetExhausted(true);

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::SimpleTasks


text:
package edu.uci.ics.jung.visualization.control;

import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Point2D;

import edu.uci.ics.jung.visualization.Layer;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.transform.MutableTransformer;

/**
 * ViewTranslatingGraphMousePlugin uses a MouseButtonOne press and
 * drag gesture to translate the graph display in the x and y
 * direction by changing the AffineTransform applied to the Graphics2D.
 * The default MouseButtonOne modifier can be overridden
 * to cause a different mouse gesture to translate the display.
 *
 *
 * @author Tom Nelson
 */
public class ViewTranslatingGraphMousePlugin extends AbstractGraphMousePlugin
    implements MouseListener, MouseMotionListener {

	/**
	 */
	public ViewTranslatingGraphMousePlugin() {
	    this(MouseEvent.BUTTON1_MASK);
	}

	/**
	 * create an instance with passed modifer value
	 * @param modifiers the mouse event modifier to activate this function
	 */
	public ViewTranslatingGraphMousePlugin(int modifiers) {
	    super(modifiers);
        this.cursor = Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR);
	}

	/**
     * Check the event modifiers. Set the 'down' point for later
     * use. If this event satisfies the modifiers, change the cursor
     * to the system 'move cursor'
	 * @param e the event
	 */
	public void mousePressed(MouseEvent e) {
	    VisualizationViewer<?,?> vv = (VisualizationViewer<?,?>)e.getSource();
	    boolean accepted = checkModifiers(e);
	    down = e.getPoint();
	    if(accepted) {
	        vv.setCursor(cursor);
	    }
	}

	/**
	 * unset the 'down' point and change the cursoe back to the system
     * default cursor
	 */
    public void mouseReleased(MouseEvent e) {
        VisualizationViewer<?,?> vv = (VisualizationViewer<?,?>)e.getSource();
        down = null;
        vv.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }

    /**
     * chack the modifiers. If accepted, translate the graph according
     * to the dragging of the mouse pointer
     * @param e the event
	 */
    public void mouseDragged(MouseEvent e) {
        VisualizationViewer<?,?> vv = (VisualizationViewer<?,?>)e.getSource();
        boolean accepted = checkModifiers(e);
        if(accepted) {
            MutableTransformer viewTransformer = vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW);
            vv.setCursor(cursor);
            try {
                Point2D q = viewTransformer.inverseTransform(down);
                Point2D p = viewTransformer.inverseTransform(e.getPoint());
                float dx = (float) (p.getX()-q.getX());
                float dy = (float) (p.getY()-q.getY());

                viewTransformer.translate(dx, dy);
                down.x = e.getX();
                down.y = e.getY();
            } catch(RuntimeException ex) {
                System.err.println("down = "+down+", e = "+e);
                throw ex;
            }

            e.consume();
        }
    }

    public void mouseClicked(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }

    public void mouseMoved(MouseEvent e) {
    }
}


text:
package io.lyracommunity.bolt.api;

import io.lyracommunity.bolt.api.event.BoltEventType;

/**
 * Marker interface for a Bolt event.
 *
 * @author Cian.
 */
public interface BoltEvent {

    /**
     * @return the type of event this is.
     */
    BoltEventType getEventType();

}


text:
namespace content {
class BrowserContext;
}  // namespace content

namespace autofill_assistant {

class CommonDependencies;

// Factory class for creating |AutofillAssistant|.
class AutofillAssistantFactory {
 public:
  static std::unique_ptr<AutofillAssistant> CreateForBrowserContext(
      content::BrowserContext* browser_context,
      std::unique_ptr<CommonDependencies> dependencies);
};
}  // namespace autofill_assistant

#endif  // COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_PUBLIC_AUTOFILL_ASSISTANT_FACTORY_H_


text:
// Copyright 2012 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.

package org.chromium.sync.notifier.signin;

import android.accounts.Account;
import android.content.Context;
import android.test.InstrumentationTestCase;
import android.test.suitebuilder.annotation.SmallTest;

import org.chromium.sync.signin.AccountManagerHelper;
import org.chromium.sync.test.util.AccountHolder;
import org.chromium.sync.test.util.MockAccountManager;
import org.chromium.sync.test.util.SimpleFuture;

/**
 * Test class for {@link AccountManagerHelper}.
 */
public class AccountManagerHelperTest extends InstrumentationTestCase {

    private MockAccountManager mAccountManager;
    private AccountManagerHelper mHelper;

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        Context context = getInstrumentation().getTargetContext();
        mAccountManager = new MockAccountManager(context, context);
        AccountManagerHelper.overrideAccountManagerHelperForTests(context, mAccountManager);
        mHelper = AccountManagerHelper.get(context);
    }

    @SmallTest
    public void testCanonicalAccount() throws InterruptedException {
        addTestAccount("test@gmail.com", "password");

        assertTrue(hasAccountForName("test@gmail.com"));
        assertTrue(hasAccountForName("Test@gmail.com"));
        assertTrue(hasAccountForName("te.st@gmail.com"));
    }

    // If this test starts flaking, please re-open crbug.com/568636 and make sure there is some sort
    // of stack trace or error message in that bug BEFORE disabling the test.
    @SmallTest
    public void testNonCanonicalAccount() throws InterruptedException {
        addTestAccount("test.me@gmail.com", "password");

        assertTrue(hasAccountForName("test.me@gmail.com"));
        assertTrue(hasAccountForName("testme@gmail.com"));
        assertTrue(hasAccountForName("Testme@gmail.com"));
        assertTrue(hasAccountForName("te.st.me@gmail.com"));
    }

    private Account addTestAccount(String accountName, String password) {
        Account account = AccountManagerHelper.createAccountFromName(accountName);
        AccountHolder.Builder accountHolder =
                AccountHolder.create().account(account).password(password).alwaysAccept(true);
        mAccountManager.addAccountHolderExplicitly(accountHolder.build());
        return account;
    }

    private boolean hasAccountForName(String accountName) throws InterruptedException {
        SimpleFuture<Boolean> result = new SimpleFuture<Boolean>();
        mHelper.hasAccountForName(accountName, result.createCallback());
        return result.get();
    }
}


text:
<?php
// DIC configuration
$container = $app->getContainer();

// view renderer
$container['renderer'] = function ($c) {
    $settings = $c->get('settings')['renderer'];
    return new Slim\Views\PhpRenderer($settings['template_path']);
};
// session
$container['session'] = function ($c) {
    return new \SlimSession\Helper;
};


text:
package com.ajjpj.asysmon.impl;

import com.ajjpj.asysmon.config.log.ASysMonLogger;
import com.ajjpj.asysmon.data.AScalarDataPoint;
import com.ajjpj.asysmon.measure.scalar.AScalarMeasurer;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * This class limits the impact on A-SysMon itself if some measurer runs into problems or uses large amounts of resources
 *
 * @author arno
 */
class RobustScalarMeasurerWrapper {
    private static final ASysMonLogger log = ASysMonLogger.get(RobustScalarMeasurerWrapper.class);

    private final AScalarMeasurer inner;

    private final long timeoutNanos;
    private final int maxNumTimeouts;

    private final AtomicInteger numTimeouts = new AtomicInteger(0);

    private interface Strategy {
        void prepareMeasurements(Map<String, Object> mementos);
        void contributeMeasurements(Map<String, AScalarDataPoint> data, long timestamp, Map<String, Object> mementos);
    }

    private final Strategy ENABLED = new Strategy() {
        @Override public void prepareMeasurements(Map<String, Object> mementos) {
            try {
                final long start = System.nanoTime();
                inner.prepareMeasurements(mementos);
                handleDuration(System.nanoTime() - start);
            } catch (Exception e) {
                log.warn("Disabling scalar measurer " + inner.getClass().getName() + " because an exception occurred", e);
                strategy = DISABLED;
            }
        }

        private void handleDuration(long durationNanos) {
            if(durationNanos > timeoutNanos) {
                log.warn("Scalar measurer " + inner.getClass().getName() + " timed out (took " + durationNanos + "ns)");
                numTimeouts.incrementAndGet();
                strategy = TIMED_OUT;
            }
        }

        @Override public void contributeMeasurements(Map<String, AScalarDataPoint> data, long timestamp, Map<String, Object> mementos) {
            try {
                final long start = System.nanoTime();
                inner.contributeMeasurements(data, timestamp, mementos);
                handleDuration(System.nanoTime() - start);
            } catch (Exception e) {
                log.warn("Disabling scalar measurer " + inner.getClass().getName() + " because an exception occurred", e);
                strategy = DISABLED;
            }
        }
    };

    private final Strategy TIMED_OUT = new Strategy() {
        @Override public void prepareMeasurements(Map<String, Object> mementos) {
            try {
                final long start = System.nanoTime();
                inner.prepareMeasurements(mementos);
                handleDuration(System.nanoTime() - start);
            } catch (Exception e) {
                log.warn("Disabling scalar measurer " + inner.getClass().getName() + " because an exception occurred", e);
                strategy = DISABLED;
            }
        }

        private void handleDuration(long durationNanos) {
            if(durationNanos > timeoutNanos) {
                if(numTimeouts.incrementAndGet() >= maxNumTimeouts) {
                    log.warn("Scalar measurer " + inner.getClass().getName() + " timed out " + maxNumTimeouts + " times in row - permanently disabling");
                    strategy = DISABLED;
                }
                else {
                    strategy = ENABLED;
                }
            }
        }

        @Override public void contributeMeasurements(Map<String, AScalarDataPoint> data, long timestamp, Map<String, Object> mementos) {
            try {
                final long start = System.nanoTime();
                inner.contributeMeasurements(data, timestamp, mementos);
                handleDuration(System.nanoTime() - start);
            } catch (Exception e) {
                log.warn("Disabling scalar measurer " + inner.getClass().getName() + " because an exception occurred", e);
                strategy = DISABLED;
            }
        }
    };

    private final Strategy DISABLED = new Strategy() {
        @Override public void prepareMeasurements(Map<String, Object> mementos) {
        }

        @Override public void contributeMeasurements(Map<String, AScalarDataPoint> data, long timestamp, Map<String, Object> mementos) {
        }
    };

    private volatile Strategy strategy = ENABLED;

    RobustScalarMeasurerWrapper(AScalarMeasurer inner, long timeoutNanos, int maxNumTimeouts) {
        this.inner = inner;
        this.timeoutNanos = timeoutNanos;
        this.maxNumTimeouts = maxNumTimeouts;
    }

    public void prepareMeasurements(Map<String, Object> mementos) {
        strategy.prepareMeasurements(mementos);
    }

    public void contributeMeasurements(Map<String, AScalarDataPoint> data, long timestamp, Map<String, Object> mementos) {
        strategy.contributeMeasurements(data, timestamp, mementos);
    }

    public void shutdown() {
        try {
            inner.shutdown();
        } catch (Exception exc) {
            log.error("failed to shut down scalar measurer " + inner.getClass().getName() + ".", exc);
        }
    }
}