text:
from pytz import (
    timezone,
    utc
)

from accelerator.models import (
    ACTIVE_PROGRAM_STATUS,
    UserRole,
)

HOUR_MINUTE_FORMAT = "%I:%M %p"
MONTH_DAY_FORMAT = "%B %d"
DEFAULT_TIMEZONE = "UTC"

VALID_KEYS_NOTE = "Valid keys are: {}"

def valid_keys_note(keys):
    return VALID_KEYS_NOTE.format(", ".join(sorted(keys)))

def coalesce_dictionaries(data, merge_field="id"):
    """Takes a sequence of dictionaries, merges those that share the
    same merge_field, and returns a list of resulting dictionaries"""
    result = {}
    for datum in data:
        merge_id = datum[merge_field]
        item = result.get(merge_id, {})
        item.update(datum)
        result[merge_id] = item
    return result.values()

def map_data(klass, query, order, data_keys, output_keys):
    result = klass.objects.filter(query).order_by(order)
    data = result.values_list(*data_keys)
    return [dict(zip(output_keys, values))
            for values in data]

def email_template_path(template_name):
    return "emails/{}".format(template_name)

# Note: this function should be replaced with calls to
# office_hour.local_start once the re-monolith is complete
def localized_office_hour_start_time(office_hour):
    tz = timezone(get_timezone(office_hour))
    return office_hour.start_date_time.astimezone(tz)

# Note: this function should be replaced with calls to
# office_hour.local_end once the re-monolith is complete
def localized_office_hour_end_time(office_hour):
    tz = timezone(get_timezone(office_hour))
    return office_hour.end_date_time.astimezone(tz)

def is_office_hour_reserver(user):
    """Returns True iff user has an office-hour reserver user role
    with respect to an active program
    Office-hour reserver roles are FINALIST, AIR, ALUM
    """
    reserver_roles = [UserRole.FINALIST, UserRole.AIR, UserRole.ALUM]
    return user.programrolegrant_set.filter(
        program_role__user_role__name__in=reserver_roles,
        program_role__program__program_status=ACTIVE_PROGRAM_STATUS).exists()

def office_hour_time_info(office_hour, last_office_hour=None):
    start_time = localized_office_hour_start_time(office_hour)
    last_office_hour = last_office_hour or office_hour
    end_time = localized_office_hour_end_time(last_office_hour)
    return {"start_time": start_time.strftime(HOUR_MINUTE_FORMAT),
            "end_time": end_time.strftime(HOUR_MINUTE_FORMAT),
            "date": start_time.strftime(MONTH_DAY_FORMAT),
            "timezone": get_timezone(office_hour)}

def get_timezone(office_hour):
    if office_hour.location and office_hour.location.timezone:
        return office_hour.location.timezone
    return DEFAULT_TIMEZONE

def datetime_is_in_past(date_time):
    return date_time.astimezone(utc) < utc.localize(date_time.utcnow())

def get_office_hours_url():
    site_url = 'accelerate.masschallenge.org'
    return 'https://{}/officehours/'.format(site_url)

def get_office_hour_shared_context(office_hour, message=None):
    tz = timezone(get_timezone(office_hour))
    date = office_hour.start_date_time.astimezone(tz).strftime('%A, %d %B, %Y')
    start_time = office_hour.start_date_time.astimezone(tz).strftime('%I:%M%p')
    end_time = office_hour.end_date_time.astimezone(tz).strftime('%I:%M%p')
    program = office_hour.program
    phone = program.program_family.phone_number if program else ''
    return {
        'date': date,
        'start_time': start_time,
        'end_time': end_time,
        'location': office_hour.location.name if office_hour.location else '',
        'dashboard_url': get_office_hours_url(),
        'mentor_name': office_hour.mentor.get_profile().full_name(),
        'phone': phone,
        'message': message,
    }


text:
package CC205_XML.Pull;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.StringReader;

/**
 * Created by Administrator on 2016/5/19.
 * pull解析
 */
public class Text_Pull {
    public static void main(String[] args)   throws XmlPullParserException, IOException
    {
        //工厂类
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        //是否支持域名空间的解析
        factory.setNamespaceAware(true);
        //获取解析器对象
        XmlPullParser xpp = factory.newPullParser();

        xpp.setInput ( new StringReader( "<foo>Hello World!</foo>" ) );
        int eventType = xpp.getEventType();
        while (eventType != xpp.END_DOCUMENT) {
            if(eventType == xpp.START_DOCUMENT) {
                System.out.println("Start document");
            } else if(eventType == xpp.END_DOCUMENT) {
                System.out.println("End document");
            } else if(eventType == xpp.START_TAG) {
                System.out.println("Start tag: "+xpp.getName());
            } else if(eventType == xpp.END_TAG) {
                System.out.println("End tag: "+xpp.getName());
            } else if(eventType == xpp.TEXT) {
                System.out.println("Text: "+xpp.getText());
            }
            //移动指针
            eventType = xpp.next();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;

    /// <summary>
    /// The type WorkbookFunctionsLogNorm_InvRequestBody.
    /// </summary>
    [DataContract]
    public partial class WorkbookFunctionsLogNorm_InvRequestBody
    {

        /// <summary>
        /// Gets or sets Probability.
        /// </summary>
        [DataMember(Name = "probability", EmitDefaultValue = false, IsRequired = false)]
        public Newtonsoft.Json.Linq.JToken Probability { get; set; }

        /// <summary>
        /// Gets or sets Mean.
        /// </summary>
        [DataMember(Name = "mean", EmitDefaultValue = false, IsRequired = false)]
        public Newtonsoft.Json.Linq.JToken Mean { get; set; }

        /// <summary>
        /// Gets or sets StandardDev.
        /// </summary>
        [DataMember(Name = "standardDev", EmitDefaultValue = false, IsRequired = false)]
        public Newtonsoft.Json.Linq.JToken StandardDev { get; set; }

    }
}


text:
package org.springframework.boot.admin;

import java.lang.management.ManagementFactory;

import javax.management.InstanceNotFoundException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.test.util.ReflectionTestUtils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

/**
 * Tests for {@link SpringApplicationAdminMXBeanRegistrar}.
 *
 * @author Stephane Nicoll
 * @author Andy Wilkinson
 */
public class SpringApplicationAdminMXBeanRegistrarTests {

	private static final String OBJECT_NAME = "org.springframework.boot:type=Test,name=SpringApplication";

	@Rule
	public final ExpectedException thrown = ExpectedException.none();

	private MBeanServer mBeanServer;

	private ConfigurableApplicationContext context;

	@Before
	public void setup() throws MalformedObjectNameException {
		this.mBeanServer = ManagementFactory.getPlatformMBeanServer();
	}

	@After
	public void closeContext() {
		if (this.context != null) {
			this.context.close();
		}
	}

	@Test
	public void validateReadyFlag() {
		final ObjectName objectName = createObjectName(OBJECT_NAME);
		SpringApplication application = new SpringApplication(Config.class);
		application.setWebApplicationType(WebApplicationType.NONE);
		application.addListeners(new ApplicationListener<ContextRefreshedEvent>() {
			@Override
			public void onApplicationEvent(ContextRefreshedEvent event) {
				try {
					assertThat(isApplicationReady(objectName)).isFalse();
				}
				catch (Exception ex) {
					throw new IllegalStateException(
							"Could not contact spring application admin bean", ex);
				}
			}
		});
		this.context = application.run();
		assertThat(isApplicationReady(objectName)).isTrue();
	}

	@Test
	public void eventsFromOtherContextsAreIgnored() throws MalformedObjectNameException {
		SpringApplicationAdminMXBeanRegistrar registrar = new SpringApplicationAdminMXBeanRegistrar(
				OBJECT_NAME);
		ConfigurableApplicationContext context = mock(
				ConfigurableApplicationContext.class);
		registrar.setApplicationContext(context);
		registrar.onApplicationReadyEvent(
				new ApplicationReadyEvent(new SpringApplication(), null,
						mock(ConfigurableApplicationContext.class)));
		assertThat(isApplicationReady(registrar)).isFalse();
		registrar.onApplicationReadyEvent(
				new ApplicationReadyEvent(new SpringApplication(), null, context));
		assertThat(isApplicationReady(registrar)).isTrue();
	}

	private boolean isApplicationReady(SpringApplicationAdminMXBeanRegistrar registrar) {
		return (Boolean) ReflectionTestUtils.getField(registrar, "ready");
	}

	@Test
	public void environmentIsExposed() {
		final ObjectName objectName = createObjectName(OBJECT_NAME);
		SpringApplication application = new SpringApplication(Config.class);
		application.setWebApplicationType(WebApplicationType.NONE);
		this.context = application.run("--foo.bar=blam");
		assertThat(isApplicationReady(objectName)).isTrue();
		assertThat(isApplicationEmbeddedWebApplication(objectName)).isFalse();
		assertThat(getProperty(objectName, "foo.bar")).isEqualTo("blam");
		assertThat(getProperty(objectName, "does.not.exist.test")).isNull();
	}

	@Test
	public void shutdownApp() throws InstanceNotFoundException {
		final ObjectName objectName = createObjectName(OBJECT_NAME);
		SpringApplication application = new SpringApplication(Config.class);
		application.setWebApplicationType(WebApplicationType.NONE);
		this.context = application.run();
		assertThat(this.context.isRunning()).isTrue();
		invokeShutdown(objectName);
		assertThat(this.context.isRunning()).isFalse();
		this.thrown.expect(InstanceNotFoundException.class); // JMX cleanup
		this.mBeanServer.getObjectInstance(objectName);
	}

	private Boolean isApplicationReady(ObjectName objectName) {
		return getAttribute(objectName, Boolean.class, "Ready");
	}

	private Boolean isApplicationEmbeddedWebApplication(ObjectName objectName) {
		return getAttribute(objectName, Boolean.class, "EmbeddedWebApplication");
	}

	private String getProperty(ObjectName objectName, String key) {
		try {
			return (String) this.mBeanServer.invoke(objectName, "getProperty",
					new Object[] { key }, new String[] { String.class.getName() });
		}
		catch (Exception ex) {
			throw new IllegalStateException(ex.getMessage(), ex);
		}
	}

	private <T> T getAttribute(ObjectName objectName, Class<T> type, String attribute) {
		try {
			Object value = this.mBeanServer.getAttribute(objectName, attribute);
			assertThat(value == null || type.isInstance(value)).isTrue();
			return type.cast(value);
		}
		catch (Exception ex) {
			throw new IllegalStateException(ex.getMessage(), ex);
		}
	}

	private void invokeShutdown(ObjectName objectName) {
		try {
			this.mBeanServer.invoke(objectName, "shutdown", null, null);
		}
		catch (Exception ex) {
			throw new IllegalStateException(ex.getMessage(), ex);
		}
	}

	private ObjectName createObjectName(String jmxName) {
		try {
			return new ObjectName(jmxName);
		}
		catch (MalformedObjectNameException e) {
			throw new IllegalStateException("Invalid jmx name " + jmxName, e);
		}
	}

	@Configuration
	static class Config {

		@Bean
		public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar()
				throws MalformedObjectNameException {
			return new SpringApplicationAdminMXBeanRegistrar(OBJECT_NAME);
		}

	}

}


text:
package godelbrot

import (
	"encoding/json"
	"fmt"
	"github.com/johnny-morrice/godelbrot/config"
	"io"
	"math/big"
	"strconv"
)

type NativeInfo struct {
	UserRequest config.Request
	// Describe the render strategy in use
	RenderStrategy config.RenderMode
	// Describe the numerics system in use
	NumericsStrategy config.NumericsMode
	PaletteType      PaletteKind
	Precision        uint
}

type PaletteKind uint8

const (
	Grayscale = PaletteKind(iota)
	Redscale
	Pretty
)

type BigInfo struct {
	RealMin big.Float
	RealMax big.Float
	ImagMin big.Float
	ImagMax big.Float
}

type SerialBigInfo struct {
	RealMin string
	RealMax string
	ImagMin string
	ImagMax string
}

// Info completely describes the render process
type Info struct {
	NativeInfo
	BigInfo
}

func (info *Info) bignums() []*big.Float {
	return []*big.Float{
		&info.RealMin,
		&info.RealMax,
		&info.ImagMin,
		&info.ImagMax,
	}
}

// IsAccurate returns True if the bignums used internally by info are all accurate.
func (info *Info) IsAccurate() bool {
	for _, x := range info.bignums() {
		if x.Acc() == big.Below {
			return false
		}
	}
	return true
}

// AddPrec increases the precision of all Infos internal bignums by delta bits.
func (info *Info) AddPrec(delta int) {
	nextPrec := int(info.Precision) + delta
	if nextPrec <= 0 {
		msg := fmt.Sprintf("Invalid precision: %v", nextPrec)
		panic(msg)
	}
	prec := uint(nextPrec)
	info.Precision = prec
	for _, x := range info.bignums() {
		x.SetPrec(prec)
	}
}

// Generate a user request that corresponts to the info numerics
func (info *Info) GenRequest() config.Request {
	req := info.UserRequest
	req.RealMin = emitBig(&info.RealMin)
	req.RealMax = emitBig(&info.RealMax)
	req.ImagMin = emitBig(&info.ImagMin)
	req.ImagMax = emitBig(&info.ImagMax)

	return req
}

// UserInfo is a variant of Info that can be easily serialized
type UserInfo struct {
	NativeInfo
	SerialBigInfo
}

func Friendly(desc *Info) *UserInfo {
	userDesc := &UserInfo{}
	userDesc.NativeInfo = desc.NativeInfo
	userDesc.RealMin = emitBig(&desc.RealMin)
	userDesc.RealMax = emitBig(&desc.RealMax)
	userDesc.ImagMin = emitBig(&desc.ImagMin)
	userDesc.ImagMax = emitBig(&desc.ImagMax)
	return userDesc
}

func Unfriendly(userDesc *UserInfo) (*Info, error) {
	desc := &Info{}
	desc.NativeInfo = userDesc.NativeInfo

	ubnds := []string{
		userDesc.RealMin,
		userDesc.RealMax,
		userDesc.ImagMin,
		userDesc.ImagMax,
	}
	bnds := make([]*big.Float, len(ubnds))

	for i, u := range ubnds {
		b, err := parseBig(u)
		if err != nil {
			return nil, fmt.Errorf("Error parsing bound: %v", err)
		}
		b.SetPrec(userDesc.Precision)
		bnds[i] = b
	}

	desc.RealMin = *bnds[0]
	desc.RealMax = *bnds[1]
	desc.ImagMin = *bnds[2]
	desc.ImagMax = *bnds[3]

	return desc, nil
}

func ToJSON(desc *Info) ([]byte, error) {
	userDesc := Friendly(desc)
	return json.MarshalIndent(userDesc, "", "    ")
}

func FromJSON(format []byte) (*Info, error) {
	userDesc := new(UserInfo)
	err := json.Unmarshal(format, userDesc)
	if err == nil {
		desc, converr := Unfriendly(userDesc)
		return desc, converr
	} else {
		return nil, err
	}
}

func WriteInfo(w io.Writer, desc *Info) error {
	text, jerr := ToJSON(desc)
	if jerr != nil {
		return jerr
	}
	_, werr := w.Write(text)
	return werr
}

func ReadInfo(r io.Reader) (*Info, error) {
	ui := &UserInfo{}
	dec := json.NewDecoder(r)
	err := dec.Decode(ui)
	if err != nil {
		return nil, err
	}
	return Unfriendly(ui)
}

type InfoPkt struct {
	Info *Info
	Err  error
}

type uipkt struct {
	ui  *UserInfo
	err error
}

func ReadInfoStream(r io.Reader) <-chan InfoPkt {
	uich := make(chan uipkt)
	go func() {
		dec := json.NewDecoder(r)
		for i := 0; dec.More(); i++ {
			ui := &UserInfo{}
			readerr := dec.Decode(ui)
			if readerr != nil {
				message := fmt.Errorf("Error after %v JSON objects: %v", i, readerr)
				uich <- uipkt{err: message}
				continue
			}
			uich <- uipkt{ui: ui}
		}
		close(uich)
	}()

	infoch := make(chan InfoPkt)
	go func() {
		for uipkt := range uich {
			if uipkt.err != nil {
				infoch <- InfoPkt{Err: uipkt.err}
				continue
			}
			inf, err := Unfriendly(uipkt.ui)
			if err != nil {
				infoch <- InfoPkt{Err: uipkt.err}
				continue
			}
			infoch <- InfoPkt{Info: inf}
		}
		close(infoch)
	}()

	return infoch
}

func DefaultRequest() *config.Request {
	return &config.Request{
		IterateLimit:   DefaultIterations,
		DivergeLimit:   DefaultDivergeLimit,
		RegionCollapse: DefaultCollapse,
		RegionSamples:  DefaultRegionSamples,
		RealMin:        float2str(real(MandelbrotMin)),
		ImagMin:        float2str(imag(MandelbrotMin)),
		RealMax:        float2str(real(MandelbrotMax)),
		ImagMax:        float2str(imag(MandelbrotMax)),
		ImageHeight:    DefaultImageHeight,
		ImageWidth:     DefaultImageWidth,
		FixAspect:      config.Shrink,
		PaletteCode:    "grayscale",
		Jobs:           1,
	}
}

func float2str(num float64) string {
	return strconv.FormatFloat(num, 'f', -1, 64)
}


text:
package me.jessyan.mvparms.demo.app;

import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;

import me.jessyan.mvparms.demo.R;
import timber.log.Timber;

/**
 * ================================================
 * 展示 {@link Application.ActivityLifecycleCallbacks} 的用法
 * <p>
 * Created by JessYan on 04/09/2017 17:14
 * Contact with jess.yan.effort@gmail.com
 * Follow me on https://github.com/JessYanCoding
 * ================================================
 */
public class ActivityLifecycleCallbacksImpl implements Application.ActivityLifecycleCallbacks {

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        Timber.w(activity + " - onActivityCreated");
    }

    @Override
    public void onActivityStarted(Activity activity) {
        Timber.w(activity + " - onActivityStarted");
        if (!activity.getIntent().getBooleanExtra("isInitToolbar", false)) {
            //由于加强框架的兼容性,故将 setContentView 放到 onActivityCreated 之后,onActivityStarted 之前执行
            //而 findViewById 必须在 Activity setContentView() 后才有效,所以将以下代码从之前的 onActivityCreated 中移动到 onActivityStarted 中执行
            activity.getIntent().putExtra("isInitToolbar", true);
            //这里全局给Activity设置toolbar和title,你想象力有多丰富,这里就有多强大,以前放到BaseActivity的操作都可以放到这里
            if (activity.findViewById(R.id.toolbar) != null) {
                if (activity instanceof AppCompatActivity) {
                    ((AppCompatActivity) activity).setSupportActionBar((Toolbar) activity.findViewById(R.id.toolbar));
                    ((AppCompatActivity) activity).getSupportActionBar().setDisplayShowTitleEnabled(false);
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        activity.setActionBar((android.widget.Toolbar) activity.findViewById(R.id.toolbar));
                        activity.getActionBar().setDisplayShowTitleEnabled(false);
                    }
                }
            }
            if (activity.findViewById(R.id.toolbar_title) != null) {
                ((TextView) activity.findViewById(R.id.toolbar_title)).setText(activity.getTitle());
            }
            if (activity.findViewById(R.id.toolbar_back) != null) {
                activity.findViewById(R.id.toolbar_back).setOnClickListener(v -> {
                    activity.onBackPressed();
                });
            }
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {
        Timber.w(activity + " - onActivityResumed");
    }

    @Override
    public void onActivityPaused(Activity activity) {
        Timber.w(activity + " - onActivityPaused");
    }

    @Override
    public void onActivityStopped(Activity activity) {
        Timber.w(activity + " - onActivityStopped");
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        Timber.w(activity + " - onActivitySaveInstanceState");
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        Timber.w(activity + " - onActivityDestroyed");
    }
}


text:
from __future__ import absolute_import, division, print_function, unicode_literals

import os, sys

from botocore.exceptions import ClientError

from .. import logger
from .aws import resources, expect_error_codes
from .compat import subprocess, makedirs

def new_ssh_key(bits=2048):
    from paramiko import RSAKey
    return RSAKey.generate(bits=bits)

def get_public_key_from_pair(key):
    return key.get_name() + " " + key.get_base64()

def key_fingerprint(key):
    fingerprint = key.get_fingerprint()
    if isinstance(fingerprint[0], int):
        return key.get_name() + " " + ":".join("{:02x}".format(i) for i in fingerprint)
    else:
        return key.get_name() + " " + ":".join("{:02x}".format(ord(i)) for i in fingerprint)

def get_ssh_key_path(name):
    return os.path.expanduser("~/.ssh/{}.pem".format(name))

def ensure_ssh_key(name=None, base_name=__name__, verify_pem_file=True):
    from paramiko import RSAKey
    if name is None:
        from getpass import getuser
        from socket import gethostname
        name = base_name + "." + getuser() + "." + gethostname().split(".")[0]

    try:
        ec2_key_pairs = list(resources.ec2.key_pairs.filter(KeyNames=[name]))
        if verify_pem_file and not os.path.exists(get_ssh_key_path(name)):
            msg = "Key {} found in EC2, but not in ~/.ssh."
            msg += " Delete the key in EC2, copy it to {}, or specify another key."
            raise KeyError(msg.format(name, get_ssh_key_path(name)))
    except ClientError as e:
        expect_error_codes(e, "InvalidKeyPair.NotFound")
        ec2_key_pairs = None

    if not ec2_key_pairs:
        if os.path.exists(get_ssh_key_path(name)):
            ssh_key = RSAKey.from_private_key_file(get_ssh_key_path(name))
        else:
            logger.info("Creating key pair %s", name)
            ssh_key = new_ssh_key()
            makedirs(os.path.dirname(get_ssh_key_path(name)), exist_ok=True)
            ssh_key.write_private_key_file(get_ssh_key_path(name))
        resources.ec2.import_key_pair(KeyName=name,
                                      PublicKeyMaterial=get_public_key_from_pair(ssh_key))
        logger.info("Imported SSH key %s", get_ssh_key_path(name))
    try:
        subprocess.check_call(["ssh-add", get_ssh_key_path(name)], timeout=5)
    except Exception as e:
        logger.warn("Failed to add %s to SSH keychain: %s. Connections may fail", get_ssh_key_path(name), e)
    return name

def hostkey_line(hostnames, key):
    from paramiko import hostkeys
    return hostkeys.HostKeyEntry(hostnames=hostnames, key=key).to_line()

def add_ssh_host_key_to_known_hosts(host_key_line):
    ssh_known_hosts_path = os.path.expanduser("~/.ssh/known_hosts")
    with open(ssh_known_hosts_path, "a") as fh:
        fh.write(host_key_line)


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@drawable/ic_tab_stopwatch_selected"
        android:state_selected="true" />

    <item
        android:drawable="@drawable/ic_tab_stopwatch_unselected"
        android:state_selected="false" />

</selector>


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.apache.cxf.staxutils (Apache CXF API 2.7.5 API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.cxf.staxutils

Classes

AbstractDOMStreamReader

AbstractDOMStreamReader.ElementFrame

CachingXmlEventWriter

DelegatingXMLStreamWriter

DepthRestrictingStreamReader

DepthXMLStreamReader

DocumentDepthProperties

FastStack

FragmentStreamReader

OverlayW3CDOMStreamWriter

PartialXMLStreamReader

StaxSource

StaxStreamFilter

StaxUtils

StreamWriterContentHandler

W3CDOMStreamReader

W3CDOMStreamWriter

W3CNamespaceContext

Exceptions

DepthExceededStaxException


text:
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see https://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;

namespace Avalonia.Controls
{
    /// <summary>
    /// Specifies how text in the text box portion of the <see cref="AutoCompleteBox" />
    /// control is used to filter items specified by the <see cref="AutoCompleteBox.Items" />
    /// property for display in the drop-down.
    /// </summary>
    public enum AutoCompleteFilterMode
    {
        /// <summary>
        /// Specifies that no filter is used. All items are returned.
        /// </summary>
        None = 0,

        /// <summary>
        /// Specifies a culture-sensitive, case-insensitive filter where the
        /// returned items start with the specified text. The filter uses the
        /// <see cref="String.StartsWith(String,StringComparison)" />
        /// method, specifying
        /// <see cref="StringComparer.CurrentCultureIgnoreCase" /> as
        /// the string comparison criteria.
        /// </summary>
        StartsWith = 1,

        /// <summary>
        /// Specifies a culture-sensitive, case-sensitive filter where the
        /// returned items start with the specified text. The filter uses the
        /// <see cref="String.StartsWith(String,StringComparison)" />
        /// method, specifying
        /// <see cref="StringComparer.CurrentCulture" /> as the string
        /// comparison criteria.
        /// </summary>
        StartsWithCaseSensitive = 2,

        /// <summary>
        /// Specifies an ordinal, case-insensitive filter where the returned
        /// items start with the specified text. The filter uses the
        /// <see cref="String.StartsWith(String,StringComparison)" />
        /// method, specifying
        /// <see cref="StringComparer.OrdinalIgnoreCase" /> as the
        /// string comparison criteria.
        /// </summary>
        StartsWithOrdinal = 3,

        /// <summary>
        /// Specifies an ordinal, case-sensitive filter where the returned items
        /// start with the specified text. The filter uses the
        /// <see cref="String.StartsWith(String,StringComparison)" />
        /// method, specifying <see cref="StringComparer.Ordinal" /> as
        /// the string comparison criteria.
        /// </summary>
        StartsWithOrdinalCaseSensitive = 4,

        /// <summary>
        /// Specifies a culture-sensitive, case-insensitive filter where the
        /// returned items contain the specified text.
        /// </summary>
        Contains = 5,

        /// <summary>
        /// Specifies a culture-sensitive, case-sensitive filter where the
        /// returned items contain the specified text.
        /// </summary>
        ContainsCaseSensitive = 6,

        /// <summary>
        /// Specifies an ordinal, case-insensitive filter where the returned
        /// items contain the specified text.
        /// </summary>
        ContainsOrdinal = 7,

        /// <summary>
        /// Specifies an ordinal, case-sensitive filter where the returned items
        /// contain the specified text.
        /// </summary>
        ContainsOrdinalCaseSensitive = 8,

        /// <summary>
        /// Specifies a culture-sensitive, case-insensitive filter where the
        /// returned items equal the specified text. The filter uses the
        /// <see cref="String.Equals(String,StringComparison)" />
        /// method, specifying
        /// <see cref="StringComparer.CurrentCultureIgnoreCase" /> as
        /// the search comparison criteria.
        /// </summary>
        Equals = 9,

        /// <summary>
        /// Specifies a culture-sensitive, case-sensitive filter where the
        /// returned items equal the specified text. The filter uses the
        /// <see cref="String.Equals(String,StringComparison)" />
        /// method, specifying
        /// <see cref="StringComparer.CurrentCulture" /> as the string
        /// comparison criteria.
        /// </summary>
        EqualsCaseSensitive = 10,

        /// <summary>
        /// Specifies an ordinal, case-insensitive filter where the returned
        /// items equal the specified text. The filter uses the
        /// <see cref="String.Equals(String,StringComparison)" />
        /// method, specifying
        /// <see cref="StringComparer.OrdinalIgnoreCase" /> as the
        /// string comparison criteria.
        /// </summary>
        EqualsOrdinal = 11,

        /// <summary>
        /// Specifies an ordinal, case-sensitive filter where the returned items
        /// equal the specified text. The filter uses the
        /// <see cref="String.Equals(String,StringComparison)" />
        /// method, specifying <see cref="StringComparer.Ordinal" /> as
        /// the string comparison criteria.
        /// </summary>
        EqualsOrdinalCaseSensitive = 12,

        /// <summary>
        /// Specifies that a custom filter is used. This mode is used when the
        /// <see cref="AutoCompleteBox.TextFilter" /> or <see cref="AutoCompleteBox.ItemFilter" />
        /// properties are set.
        /// </summary>
        Custom = 13,
    }
}


text:
{{ location.city }}

{{ location.summary }}

{{ location.temperature }}°

Weather data from World Weather Online http://www.worldweatheronline.com


text:
package org.bouncycastle.x509;

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.AttCertIssuer;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.V2Form;
import org.bouncycastle.jce.PrincipalUtil;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.util.Selector;

import java.io.IOException;
import java.security.Principal;
import java.security.cert.CertSelector;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

/**
 * Carrying class for an attribute certificate issuer.
 */
public class AttributeCertificateIssuer
    implements CertSelector, Selector
{
    final ASN1Encodable  form;

    /**
     * @param issuer
     */
    AttributeCertificateIssuer(
        AttCertIssuer issuer)
    {
        form = issuer.getIssuer();
    }

    public AttributeCertificateIssuer(
        X509Principal principal)
    {
        form = new V2Form(new GeneralNames(new GeneralName(principal)));
    }

    private Object[] getNames()
    {
        GeneralNames    name;

        if (form instanceof V2Form)
        {
            name = ((V2Form)form).getIssuerName();
        }
        else
        {
            name = (GeneralNames)form;
        }

        GeneralName[]   names = name.getNames();

        List        l = new ArrayList(names.length);

        for (int i = 0; i != names.length; i++)
        {
            if (names[i].getTagNo() == GeneralName.directoryName)
            {
                try
                {
                    l.add(new X509Principal(((ASN1Encodable)names[i].getName()).toASN1Primitive().getEncoded()));
                }
                catch (IOException e)
                {
                    throw new RuntimeException("badly formed Name object");
                }
            }
        }

        return l.toArray(new Object[l.size()]);
    }

    /**
     * Return any principal objects inside the attribute certificate issuer object.
     *
     * @return an array of Principal objects (usually X509Principal)
     */
    public Principal[] getPrincipals()
    {
        Object[]    p = this.getNames();
        List        l = new ArrayList();

        for (int i = 0; i != p.length; i++)
        {
            if (p[i] instanceof Principal)
            {
                l.add(p[i]);
            }
        }

        return (Principal[])l.toArray(new Principal[l.size()]);
    }

    private boolean matchesDN(X509Principal subject, GeneralNames targets)
    {
        GeneralName[]   names = targets.getNames();

        for (int i = 0; i != names.length; i++)
        {
            GeneralName gn = names[i];

            if (gn.getTagNo() == GeneralName.directoryName)
            {
                try
                {
                    if (new X509Principal(((ASN1Encodable)gn.getName()).toASN1Primitive().getEncoded()).equals(subject))
                    {
                        return true;
                    }
                }
                catch (IOException e)
                {
                }
            }
        }

        return false;
    }

    /* (non-Javadoc)
     * @see java.security.cert.CertSelector#clone()
     */
    public Object clone()
    {
        return new AttributeCertificateIssuer(AttCertIssuer.getInstance(form));
    }

    /* (non-Javadoc)
     * @see java.security.cert.CertSelector#match(java.security.cert.Certificate)
     */
    public boolean match(Certificate cert)
    {
        if (!(cert instanceof X509Certificate))
        {
            return false;
        }

        X509Certificate x509Cert = (X509Certificate)cert;

        try
        {
            if (form instanceof V2Form)
            {
                V2Form issuer = (V2Form)form;
                if (issuer.getBaseCertificateID() != null)
                {
                    return issuer.getBaseCertificateID().getSerial().getValue().equals(x509Cert.getSerialNumber())
                        && matchesDN(PrincipalUtil.getIssuerX509Principal(x509Cert), issuer.getBaseCertificateID().getIssuer());
                }

                GeneralNames name = issuer.getIssuerName();
                if (matchesDN(PrincipalUtil.getSubjectX509Principal(x509Cert), name))
                {
                    return true;
                }
            }
            else
            {
                GeneralNames name = (GeneralNames)form;
                if (matchesDN(PrincipalUtil.getSubjectX509Principal(x509Cert), name))
                {
                    return true;
                }
            }
        }
        catch (CertificateEncodingException e)
        {
            return false;
        }

        return false;
    }

    public boolean equals(Object obj)
    {
        if (obj == this)
        {
            return true;
        }

        if (!(obj instanceof AttributeCertificateIssuer))
        {
            return false;
        }

        AttributeCertificateIssuer other = (AttributeCertificateIssuer)obj;

        return this.form.equals(other.form);
    }

    public int hashCode()
    {
        return this.form.hashCode();
    }

    public boolean match(Object obj)
    {
        if (!(obj instanceof X509Certificate))
        {
            return false;
        }

        return match((Certificate)obj);
    }
}


text:
package internal.msm.spikes.dw.client.spring;

import java.security.KeyStore;
import org.glassfish.jersey.SslConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 *
 * @author Paul Gilligan <Paul.Gilligan@moneysupermarket.com>
 */
@Component
public class DropWizardTLSConfiguration implements BeanPostProcessor{

    private static final Logger LOGGER = LoggerFactory.getLogger(DropWizardTLSConfiguration.class);

    private final SslConfigurator sslConfigurator;

    private String trustStoreType;

    private String keyStoreType;

    private String keyPassword;

    private String trustStorePassword;

    private String keyStorePassword;

    private String trustStoreFile;

    private String keyStoreFile;

    private final String securityProtocol = "TLS";

    public DropWizardTLSConfiguration() {
        this.sslConfigurator = SslConfigurator.newInstance();
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
        LOGGER.info("Update " + name);
        this.sslConfigurator.trustStoreFile(keyStoreFile);
        this.sslConfigurator.trustStorePassword(keyPassword);
        this.sslConfigurator.trustStoreType(trustStoreType);

        this.sslConfigurator.keyStoreFile(keyStoreFile);
        this.sslConfigurator.keyStorePassword(keyPassword);
        this.sslConfigurator.keyStoreType(keyStoreType);

        this.sslConfigurator.keyPassword(keyPassword);

        return bean;
    }

    public String getTrustStoreType() {
        return trustStoreType;
    }

    public void setTrustStoreType(String trustStoreType) {
        this.trustStoreType = trustStoreType;
    }

    public String getKeyStoreType() {
        return keyStoreType;
    }

    public void setKeyStoreType(String keyStoreType) {
        this.keyStoreType = keyStoreType;
    }

    public String getKeyPassword() {
        return keyPassword;
    }

    public void setKeyPassword(String keyPassword) {
        this.keyPassword = keyPassword;
    }

    public String getTrustStorePassword() {
        return trustStorePassword;
    }

    public void setTrustStorePassword(String trustStorePassword) {
        this.trustStorePassword = trustStorePassword;
    }

    public String getKeyStorePassword() {
        return keyStorePassword;
    }

    public void setKeyStorePassword(String keyStorePassword) {
        this.keyStorePassword = keyStorePassword;
    }

    public String getTrustStoreFile() {
        return trustStoreFile;
    }

    public void setTrustStoreFile(String trustStoreFile) {
        this.trustStoreFile = trustStoreFile;
    }

    public String getKeyStoreFile() {
        return keyStoreFile;
    }

    public void setKeyStoreFile(String keyStoreFile) {
        this.keyStoreFile = keyStoreFile;
    }

    @Override
    public String toString() {
        return "DropWizardTLSConfiguration{" + "trustStoreFile=" + trustStoreFile + ", keyStoreFile=" + keyStoreFile + ", securityProtocol=" + securityProtocol + '}';
    }

}


text:
#include "Control/PathController.h"
#include "Control/FeedforwardController.h"
#include "Control/LoggingController.h"
#include "Sensing/JointSensors.h"
#include "Simulation/Simulator.h"
#include "IO/XmlWorld.h"
#include "IO/XmlODE.h"
#include "IO/three.js.h"
#include <KrisLibrary/utils/stringutils.h>
#include <KrisLibrary/utils/AnyCollection.h>
#include <KrisLibrary/robotics/IKFunctions.h>
#include <fstream>
using namespace Math3D;
using namespace Klampt;

string ReadFileAsString(const char* fn)
{
  string s;
  ifstream in(fn,ios::in | ios::binary);
  //read binary string
  char buf[1025];
  while(!in.eof()) {
    in.read(buf,1024);
    int n = (int)in.gcount();
    buf[n]=0;
    s += buf;
  }
  return s;
}

typedef LoggingController MyController;
typedef PolynomialPathController MyMilestoneController;

/*
	char buf[256];
	for(size_t i=0;i<sim.robotControllers.size();i++) {
	  sprintf(buf,"robot%d_commands.log",i);
	  LoggingController<FeedforwardController>* c = dynamic_cast<LoggingController<FeedforwardController>* >(&*sim.robotControllers[i]);
	  if(!c->SaveLog(buf)) {
	    fprintf(stderr,"Error writing to %s\n",buf);
	  }
	  else
	    printf("Saved commands to %s\n",buf);
	}
*/

/*
	char buf[256];
	for(size_t i=0;i<sim.robotControllers.size();i++) {
	  sprintf(buf,"robot%d_commands.log",i);
	  LoggingController<FeedforwardController>* c = dynamic_cast<LoggingController<FeedforwardController>* >(&*sim.robotControllers[i]);
	  if(!c->LoadLog(buf)) {
	    fprintf(stderr,"Error reading commands from %s\n",buf);
	  }
	  else {
	    printf("Loaded commands from %s\n",buf);
	    c->replay = true;
	    c->replayIndex = 0;
	    c->onlyJointCommands = true;
	    //hack
	    printf("HACK: removing delays from recorded commands\n");
	    c->RemoveDelays(0.2);
	    printf("Read %d commands\n",c->trajectory.size());
	    //check if it's for the right robot
	    if(!c->trajectory.empty()) {
	      if(c->trajectory[0].second.actuators.size() != c->command.actuators.size()) {
		fprintf(stderr,"Command file %s doesn't have the right number of actuators\n",buf);
		c->replay = false;
	      }
	    }
	  }
	}
*/

bool SetupCommands(Simulator& sim,const string& fn)
{
  if(fn.empty()) return true;
  if(0==strcmp(FileExtension(fn.c_str()),"log")) {
    Assert(sim.robotControllers.size()==1);
    LoggingController* c = dynamic_cast<LoggingController*>(&*sim.robotControllers[0]);
    if(!c->LoadLog(fn.c_str())) {
      fprintf(stderr,"Error reading commands from %s\n",fn.c_str());
      return false;
    }
    else {
      printf("Loaded commands from %s\n",fn.c_str());
      c->replay = true;
      c->replayIndex = 0;
      c->onlyJointCommands = true;
      //hack
      printf("HACK: removing delays from recorded commands\n");
      c->RemoveDelays(0.2);
      printf("Read %d commands\n",c->trajectory.size());
      //check if it's for the right robot
      if(!c->trajectory.empty()) {
	if(c->trajectory[0].second.actuators.size() != c->command->actuators.size()) {
	  fprintf(stderr,"Command file %s doesn't have the right number of actuators\n",fn.c_str());
	  c->replay = false;
	}
      }
    }
  }
  else { //load milestone path
    vector<Vector> milestones;
    vector<Vector> dmilestones;
    ifstream in(fn.c_str(),ios::in);
    if(!in) return false;
    Vector x,dx;
    while(in) {
      in >> x >> dx;
      if(in) {
	cout<<x<<", "<<dx<<endl;
	milestones.push_back(x);
	dmilestones.push_back(dx);
      }
    }
    in.close();

    Assert(sim.robotControllers.size()==1);
    for(size_t i=0;i<milestones.size();i++) {
      stringstream ss;
      ss<<milestones[i]<<"\t"<<dmilestones[i];
      if(i==0) {
	if(!sim.robotControllers[0]->SendCommand("set_qv",ss.str())) {
	  fprintf(stderr,"set_qv command does not work with the robot's controller\n");
	  return false;
	}
      }
      else {
	if(!sim.robotControllers[0]->SendCommand("append_qv",ss.str())) {
	  fprintf(stderr,"append_qv command does not work with the robot's controller\n");
	  return false;
	}
      }
    }
  }
  return true;
}

enum Format { None, Raw, Base64, ThreeJS };

const char* FormatExtension(Format format)
{
  if(format == None) return "";
  else if(format == ThreeJS) return "json";
  else return "state";
}

string ReadSimState(const char* fn,Format format)
{
  string str = ReadFileAsString(fn);
  if(format == Raw) return str;
  else return FromBase64(str);
}
bool WriteSimState(Simulator& sim,const char* fn,Format format)
{
  if(format == None) return true;
  else if(format == ThreeJS) {
    sim.UpdateModel();
    AnyCollection obj;
    ThreeJSExport(sim,obj);
    ofstream out(fn,ios::out|ios::binary);
    if(!out) {
      fprintf(stderr,"Unable to open file %s for writing\n",fn);
      return false;
    }
    out<<obj<<endl;
    out.close();
    return true;
  }
  else {
    string finalState;
    sim.WriteState(finalState);
    ofstream out(fn,ios::out|ios::binary);
    if(!out) {
      fprintf(stderr,"Unable to open file %s for writing\n",fn);
      return false;
    }
    string data;
    if(format == Raw) data = finalState;
    else data = ToBase64(finalState);
    out.write(data.c_str(),data.length());
    out.close();
    return true;
  }
}

const char* OPTIONS_STRING = "Options:\n\
\t-init file: resume simulating from a given initial state. \n\
\t            Multiple initial states may be issued.\n\
\t-settle time: set the settling time (default 0). \n\
\t-end time: set the final simulation time (default inf). \n\
\t-duration time: set the total simulation time (default 10). \n\
\t-m file: command a milestone file.  Multiple commands may be issued. \n\
\t-l file: command a log file.  Multiple commands may be issued. \n\
\t-prefix p: save states to files using the prefix p. \n\
\t-log file: save log files of the low-level robot commands. \n\
\t-step s: sets the simulation time step (default 1/1000)\n\
\t-format f: state encoding format (raw, base64, three.js default base64)\n\
";

int main(int argc, char** argv)
{
  if(argc < 2) {
    printf("USAGE: SimUtil [options] [xml_files, robot_files, terrain_files, object_files]\n");
    printf(OPTIONS_STRING);
    return 0;
  }
  XmlWorld xmlWorld;
  WorldModel world;
  Simulator sim;
  vector<string> commandFiles;
  double settlingTime = 0;
  double simEndTime = Inf;
  double simDuration = 10;
  string prefix="trial";
  vector<string> initialStates;
  string logFile;
  Format format = Base64;

  for(int i=1;i<argc;i++) {
    if(argv[i][0] == '-') {
      if(0==strcmp(argv[i],"-m")) {
	commandFiles.push_back(argv[i+1]);
	i++;
      }
      else if(0==strcmp(argv[i],"-l")) {
	commandFiles.push_back(argv[i+1]);
	i++;
      }
      else if(0==strcmp(argv[i],"-settle")) {
	settlingTime = atof(argv[i+1]);
	i++;
      }
      else if(0==strcmp(argv[i],"-end")) {
	simEndTime = atof(argv[i+1]);
	i++;
      }
      else if(0==strcmp(argv[i],"-duration")) {
	simDuration = atof(argv[i+1]);
	i++;
      }
      else if(0==strcmp(argv[i],"-step")) {
	sim.simStep = atof(argv[i+1]);
	i++;
      }
      else if(0==strcmp(argv[i],"-prefix")) {
	prefix = argv[i+1];
	i++;
      }
      else if(0==strcmp(argv[i],"-init")) {
	initialStates.push_back(ReadSimState(argv[i+1],format));
	i++;
      }
      else if(0==strcmp(argv[i],"-format")) {
	if(0==strcmp(argv[i+1],"none"))
	  format = None;
	else if(0==strcmp(argv[i+1],"raw"))
	  format = Raw;
	else if(0==strcmp(argv[i+1],"base64"))
	  format = Base64;
	else if(0==strcmp(argv[i+1],"three.js"))
	  format = ThreeJS;
	i++;
      }
      else {
	fprintf(stderr,"Unknown option %s\n",argv[i]);
	printf(OPTIONS_STRING);
	return 1;
      }
    }
    else {
      const char* ext=FileExtension(argv[i]);
      if(0==strcmp(ext,"xml")) {
	if(!xmlWorld.Load(argv[i])) {
	  printf("Error loading world file %s\n",argv[i]);
	  return 1;
	}
	if(!xmlWorld.GetWorld(world)) {
	  printf("Error loading world from %s\n",argv[i]);
	  return 1;
	}
      }
      else {
	if(world.LoadElement(argv[i]) < 0) {
	  return 1;
	}
      }
    }
  }

  //initialize simulation
  printf("Initializing simulation...\n");
  sim.Init(&world);
  printf("Done\n");

  //setup controllers
  sim.robotControllers.resize(world.robots.size());
  for(size_t i=0;i<sim.robotControllers.size();i++) {
    RobotModel* robot=world.robots[i].get();
    sim.SetController(i,MakeDefaultController(robot));
    sim.controlSimulators[i].sensors.MakeDefault(robot);
  }

  //setup ODE settings, if any
  TiXmlElement* e=xmlWorld.GetElement("simulation");
  if(e) {
    printf("Reading simulation settings...\n");
    XmlSimulationSettings s(e);
    if(!s.GetSettings(sim)) {
      fprintf(stderr,"Warning, simulation settings not read correctly\n");
    }
    printf("Done\n");
  }

  //setup feedback
  //world-object
  for(size_t i=0;i<world.rigidObjects.size();i++)
    sim.EnableContactFeedback(world.RigidObjectID(i),world.TerrainID(0));
  //robot-object
  for(size_t i=0;i<world.rigidObjects.size();i++) {
    for(size_t j=0;j<world.robots[0]->links.size();j++) {
      sim.EnableContactFeedback(world.RigidObjectID(i),world.RobotLinkID(0,j));
    }
  }
  for(size_t i=0;i<world.terrains.size();i++) {
    for(size_t j=0;j<world.robots[0]->links.size();j++) {
      sim.EnableContactFeedback(world.TerrainID(i),world.RobotLinkID(0,j));
    }
  }

  if(initialStates.empty()) {
    initialStates.push_back(string());
    sim.WriteState(initialStates.back());
  }

  //allow the objects to settle and save that state
  if(settlingTime > 0) {
    for(size_t i=0;i<initialStates.size();i++) {
      if(initialStates.size() > 1) {
	if(!sim.ReadState(initialStates[i])) {
	  fprintf(stderr,"Warning, ReadState didn't work\n");
	  abort();
	}
      }

      sim.Advance(settlingTime);
      sim.WriteState(initialStates[i]);
    }
  }

  if(commandFiles.empty())
    commandFiles.resize(1);

  //run the commands
  for(size_t init=0;init<initialStates.size();init++) {
    for(size_t trial=0;trial<commandFiles.size();trial++) {
      if(initialStates.size() > 1 || trial > 0) {
	if(!sim.ReadState(initialStates[init])) {
	  fprintf(stderr,"Warning, ReadState didn't work\n");
	  abort();
	}
      }
      Real time0 = sim.time;

      printf("Loading commands...\n");
      bool res=SetupCommands(sim,commandFiles[trial]);
      if(!res) {
	fprintf(stderr,"Unable to load commands from %s\n",commandFiles[trial].c_str());
	return 1;
      }

      while(sim.time < simEndTime && sim.time < simDuration + time0 ) {
	printf("Time %g\n",sim.time);
	sim.Advance(sim.simStep);
      }

      //write the final state
      char buf[256];
      if(commandFiles.size()==1) {
	if(initialStates.size()==1) snprintf(buf,1024,"%s.%s",prefix.c_str(),FormatExtension(format));
	else snprintf(buf,1024,"%s%04d.%s",prefix.c_str(),init,FormatExtension(format));
      }
      else {
	if(initialStates.size()==1) snprintf(buf,1024,"%s%04d.%s",prefix.c_str(),trial,FormatExtension(format));
	else snprintf(buf,1024,"%s_%04d_%04d.%s",prefix.c_str(),init,trial,FormatExtension(format));
      }

      printf("Writing state at time %g to file %s\n",sim.time,buf);
      if(!WriteSimState(sim,buf,format)) {
	return 1;
      }
    }
  }
  return 0;
}


text:
package com.hubspot.jinjava.lib.tag;

import static org.assertj.core.api.Assertions.assertThat;

import com.google.common.io.Resources;
import com.hubspot.jinjava.BaseInterpretingTest;
import com.hubspot.jinjava.JinjavaConfig;
import com.hubspot.jinjava.interpret.Context.TemporaryValueClosable;
import com.hubspot.jinjava.interpret.DeferredValue;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
import com.hubspot.jinjava.mode.PreserveRawExecutionMode;
import com.hubspot.jinjava.tree.Node;
import com.hubspot.jinjava.tree.TagNode;
import com.hubspot.jinjava.tree.TreeParser;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.Before;
import org.junit.Test;

public class RawTagTest extends BaseInterpretingTest {
  Tag tag;

  @Before
  public void setup() {
    tag = new RawTag();
  }

  @Test
  public void renderPlain() {
    TagNode tagNode = fixture("plain");
    assertThat(tag.interpret(tagNode, interpreter)).isEqualTo("hello world.");
  }

  @Test
  public void renderTags() {
    List<Node> tags = fixtures("tags");
    String result = "";

    for (Node n : tags) {
      TagNode tn = (TagNode) n;
      result += tag.interpret(tn, interpreter);
    }

    assertThat(result).isEqualTo("{{ if list.123 }}foo");
  }

  @Test
  public void renderHublSnippet() {
    TagNode tagNode = fixture("hubl");
    assertThat(StringUtils.normalizeSpace(tag.interpret(tagNode, interpreter)))
      .isEqualTo(
        "
Blog Posts

 {% for content in contents %}
{{ content.name|title }}
 {% endfor %}
"
      );
  }

  @Test
  public void itDoesntProcessUnknownTagsWithinARawBlock() {
    TagNode tagNode = fixture("unknowntags");
    assertThat(StringUtils.normalizeSpace(tag.interpret(tagNode, interpreter)))
      .isEqualTo("{% footag %}{% bartag %}");
  }

  @Test
  public void itWorksWithInvalidSyntaxWithinRawBlock() {
    TagNode tagNode = fixture("invalidsyntax");
    assertThat(StringUtils.normalizeSpace(tag.interpret(tagNode, interpreter)))
      .isEqualTo("this is {invalid and wrong");

    tagNode = fixture("invalidsyntax2");
    assertThat(StringUtils.normalizeSpace(tag.interpret(tagNode, interpreter)))
      .isEqualTo("this is {{ invalid and wrong");

    tagNode = fixture("invalidsyntax3");
    assertThat(StringUtils.normalizeSpace(tag.interpret(tagNode, interpreter)))
      .isEqualTo("this is }invalid and wrong");

    tagNode = fixture("invalidsyntax4");
    assertThat(StringUtils.normalizeSpace(tag.interpret(tagNode, interpreter)))
      .isEqualTo("this is }} invalid and wrong");

    tagNode = fixture("invalidsyntax5");
    assertThat(StringUtils.normalizeSpace(tag.interpret(tagNode, interpreter)))
      .isEqualTo("this is {% invalid and wrong");
  }

  @Test
  public void itDoesntProcessJinjaCommentsWithinARawBlock() {
    TagNode tagNode = fixture("comment");
    assertThat(StringUtils.normalizeSpace(tag.interpret(tagNode, interpreter)))
      .contains("{{#each people}}");
  }

  @Test
  public void itPreservesRawTags() {
    TagNode tagNode = fixture("hubl");
    JinjavaInterpreter preserveInterpreter = new JinjavaInterpreter(
      jinjava,
      jinjava.getGlobalContextCopy(),
      JinjavaConfig
        .newBuilder()
        .withExecutionMode(PreserveRawExecutionMode.instance())
        .build()
    );
    String result = tag.interpret(tagNode, preserveInterpreter);
    try {
      assertThat(result)
        .isEqualTo(
          Resources.toString(
            Resources.getResource("tags/rawtag/hubl.jinja"),
            StandardCharsets.UTF_8
          )
        );
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Test
  public void itOverridesRawTagPreservation() {
    TagNode tagNode = fixture("hubl");
    JinjavaInterpreter preserveInterpreter = new JinjavaInterpreter(
      jinjava,
      jinjava.getGlobalContextCopy(),
      JinjavaConfig
        .newBuilder()
        .withExecutionMode(PreserveRawExecutionMode.instance())
        .build()
    );
    String result;
    try (
      TemporaryValueClosable<Boolean> c = preserveInterpreter
        .getContext()
        .withUnwrapRawOverride()
    ) {
      result = tag.interpret(tagNode, preserveInterpreter);
    }
    assertThat(StringUtils.normalizeSpace(result))
      .isEqualTo(
        "
Blog Posts

 {% for content in contents %}
{{ content.name|title }}
 {% endfor %}
"
      );
  }

  @Test
  public void ifFixesSpacingWithRawTagPreservation() {
    TagNode tagNode = fixture("nospacing");
    JinjavaInterpreter preserveInterpreter = new JinjavaInterpreter(
      jinjava,
      jinjava.getGlobalContextCopy(),
      JinjavaConfig
        .newBuilder()
        .withExecutionMode(PreserveRawExecutionMode.instance())
        .build()
    );
    String result = tag.interpret(tagNode, preserveInterpreter);
    assertThat(StringUtils.normalizeSpace(result))
      .isEqualTo("{% raw %} {%print 'foo'%} {% endraw %}");
  }

  @Test
  public void itPreservesDeferredWhilePreservingRawTags() {
    TagNode tagNode = fixture("deferred");
    JinjavaInterpreter preserveInterpreter = new JinjavaInterpreter(
      jinjava,
      jinjava.getGlobalContextCopy(),
      JinjavaConfig
        .newBuilder()
        .withExecutionMode(PreserveRawExecutionMode.instance())
        .build()
    );
    preserveInterpreter.getContext().put("deferred", DeferredValue.instance());
    interpreter.getContext().put("deferred", DeferredValue.instance());

    String preservedResult = tag.interpret(tagNode, preserveInterpreter);
    String nonPreservedResult = tag.interpret(tagNode, interpreter);
    try {
      assertThat(preservedResult)
        .isEqualTo(
          Resources
            .toString(
              Resources.getResource("tags/rawtag/deferred.jinja"),
              StandardCharsets.UTF_8
            )
            .trim()
        );
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    assertThat(nonPreservedResult).isEqualTo("{{ deferred }}");

    // Should not get evaluated because it's wrapped in a raw tag.
    String deferredRealValue = "Resolved value.";
    preserveInterpreter.getContext().put("deferred", deferredRealValue);
    interpreter.getContext().put("deferred", deferredRealValue);
    String preservedIdempotent = tag.interpret(
      (TagNode) new TreeParser(preserveInterpreter, preservedResult)
        .buildTree()
        .getChildren()
        .getFirst(),
      preserveInterpreter
    );
    String secondPass = tag.interpret(
      (TagNode) new TreeParser(interpreter, preservedResult)
        .buildTree()
        .getChildren()
        .getFirst(),
      interpreter
    );

    assertThat(preservedIdempotent).isEqualTo(preservedResult);
    assertThat(secondPass).isEqualTo("{{ deferred }}");
  }

  private TagNode fixture(String name) {
    return (TagNode) fixtures(name).getFirst();
  }

  private LinkedList<Node> fixtures(String name) {
    try {
      return new TreeParser(
        interpreter,
        Resources.toString(
          Resources.getResource(String.format("tags/rawtag/%s.jinja", name)),
          StandardCharsets.UTF_8
        )
      )
        .buildTree()
        .getChildren();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}


text:
package org.apache.flink.table.planner.plan.nodes.exec.spec;

import org.apache.flink.table.planner.plan.nodes.exec.serde.RexWindowBoundJsonDeserializer;
import org.apache.flink.table.planner.plan.nodes.exec.serde.RexWindowBoundJsonSerializer;

import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonSerialize;

import org.apache.calcite.rel.core.AggregateCall;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexWindowBound;

import java.util.List;
import java.util.Objects;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * {@link OverSpec} describes a set of over aggregates.
 *
 *
This class corresponds to {@link org.apache.calcite.rel.core.Window} rel node, different from
 * Window rel, OverSpec requires all groups should have same partition.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class OverSpec {
    public static final String FIELD_NAME_PARTITION = "partition";
    public static final String FIELD_NAME_GROUPS = "groups";
    public static final String FIELD_NAME_CONSTANTS = "constants";
    public static final String FIELD_NAME_ORIGINAL_INPUT_FIELDS = "originalInputFields";

    /** Describes the partition-by part, all groups in this over have same partition. */
    @JsonProperty(FIELD_NAME_PARTITION)
    private final PartitionSpec partition;

    /**
     * The groups in a over operator, each group has the same window specification with one or more
     * aggregate calls.
     */
    @JsonProperty(FIELD_NAME_GROUPS)
    private final List<GroupSpec> groups;

    /** List of constants that are additional inputs. */
    @JsonProperty(FIELD_NAME_CONSTANTS)
    private final List<RexLiteral> constants;

    /** The number of the over operator's input fields. */
    @JsonProperty(FIELD_NAME_ORIGINAL_INPUT_FIELDS)
    private final int originalInputFields;

    @JsonCreator
    public OverSpec(
            @JsonProperty(FIELD_NAME_PARTITION) PartitionSpec partition,
            @JsonProperty(FIELD_NAME_GROUPS) List<GroupSpec> groups,
            @JsonProperty(FIELD_NAME_CONSTANTS) List<RexLiteral> constants,
            @JsonProperty(FIELD_NAME_ORIGINAL_INPUT_FIELDS) int originalInputFields) {
        this.partition = checkNotNull(partition);
        this.groups = checkNotNull(groups);
        this.constants = checkNotNull(constants);
        this.originalInputFields = originalInputFields;
    }

    @JsonIgnore
    public PartitionSpec getPartition() {
        return partition;
    }

    @JsonIgnore
    public List<GroupSpec> getGroups() {
        return groups;
    }

    @JsonIgnore
    public List<RexLiteral> getConstants() {
        return constants;
    }

    @JsonIgnore
    public int getOriginalInputFields() {
        return originalInputFields;
    }

    /**
     * {@link GroupSpec} describes group of over aggregate calls that have the same window
     * specification.
     *
     *
The specification is defined by an upper and lower bound, and also has zero or more
     * order-by columns.
     *
     *
This class corresponds to {@link org.apache.calcite.rel.core.Window.Group}, but different
     * from Group, the partition spec is defined in OverSpec.
     */
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class GroupSpec {
        public static final String FIELD_NAME_SORT_SPEC = "orderBy";
        public static final String FIELD_NAME_IS_ROWS = "isRows";
        public static final String FIELD_NAME_LOWER_BOUND = "lowerBound";
        public static final String FIELD_NAME_UPPER_BOUND = "upperBound";
        public static final String FIELD_NAME_AGG_CALLS = "aggCalls";

        /** Describes the order-by part. */
        @JsonProperty(FIELD_NAME_SORT_SPEC)
        private final SortSpec sort;

        /** If true, the group is in row clause, else the group is in range clause. */
        @JsonProperty(FIELD_NAME_IS_ROWS)
        private final boolean isRows;

        /** The lower bound of the window. */
        @JsonProperty(FIELD_NAME_LOWER_BOUND)
        @JsonSerialize(using = RexWindowBoundJsonSerializer.class)
        @JsonDeserialize(using = RexWindowBoundJsonDeserializer.class)
        private final RexWindowBound lowerBound;

        /** The upper bound of the window. */
        @JsonProperty(FIELD_NAME_UPPER_BOUND)
        @JsonSerialize(using = RexWindowBoundJsonSerializer.class)
        @JsonDeserialize(using = RexWindowBoundJsonDeserializer.class)
        private final RexWindowBound upperBound;

        /** The agg functions set. */
        @JsonProperty(FIELD_NAME_AGG_CALLS)
        private final List<AggregateCall> aggCalls;

        @JsonCreator
        public GroupSpec(
                @JsonProperty(FIELD_NAME_SORT_SPEC) SortSpec sort,
                @JsonProperty(FIELD_NAME_IS_ROWS) boolean isRows,
                @JsonProperty(FIELD_NAME_LOWER_BOUND) RexWindowBound lowerBound,
                @JsonProperty(FIELD_NAME_UPPER_BOUND) RexWindowBound upperBound,
                @JsonProperty(FIELD_NAME_AGG_CALLS) List<AggregateCall> aggCalls) {
            this.sort = checkNotNull(sort);
            this.isRows = isRows;
            this.lowerBound = checkNotNull(lowerBound);
            this.upperBound = checkNotNull(upperBound);
            this.aggCalls = checkNotNull(aggCalls);
        }

        @JsonIgnore
        public SortSpec getSort() {
            return sort;
        }

        @JsonIgnore
        public boolean isRows() {
            return isRows;
        }

        @JsonIgnore
        public RexWindowBound getLowerBound() {
            return lowerBound;
        }

        @JsonIgnore
        public RexWindowBound getUpperBound() {
            return upperBound;
        }

        @JsonIgnore
        public List<AggregateCall> getAggCalls() {
            return aggCalls;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            GroupSpec groupSpec = (GroupSpec) o;
            return isRows == groupSpec.isRows
                    && sort.equals(groupSpec.sort)
                    && lowerBound.equals(groupSpec.lowerBound)
                    && upperBound.equals(groupSpec.upperBound)
                    && aggCalls.equals(groupSpec.aggCalls);
        }

        @Override
        public int hashCode() {
            return Objects.hash(sort, isRows, lowerBound, upperBound, aggCalls);
        }

        @Override
        public String toString() {
            return "Group{"
                    + "sort="
                    + sort
                    + ", isRows="
                    + isRows
                    + ", lowerBound="
                    + lowerBound
                    + ", upperBound="
                    + upperBound
                    + ", aggCalls="
                    + aggCalls
                    + '}';
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        OverSpec overSpec = (OverSpec) o;
        return originalInputFields == overSpec.originalInputFields
                && partition.equals(overSpec.partition)
                && groups.equals(overSpec.groups)
                && constants.equals(overSpec.constants);
    }

    @Override
    public int hashCode() {
        return Objects.hash(partition, groups, constants, originalInputFields);
    }

    @Override
    public String toString() {
        return "Over{"
                + "partition="
                + partition
                + ", groups="
                + groups
                + ", constants="
                + constants
                + ", originalInputFields="
                + originalInputFields
                + '}';
    }
}


text:
@implementation SELDemo

-(void)printttttt{
    NSLog(@"I'm class SELDemo");
}

@end


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Lassen PLOKI</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/black.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Lassen "Ploki"

Kurssille verkkosovelluskehitys LTP7026

Tällä sivulla tulee olemaan tietoa eri asioista mitä olen suorittanut kurssin aikana

						Tähän mennessä olen asentanut Windowsille ympäristön OpenShiftiä varten.

 Lemppari protokollat !

selaa alaspäin nähdäksesi mieluisista protokollistani

 FTP - File Transfer Protocol

 FTP protkolla on tiedonsiirto protokolla joka hyödyntää TCP-protokollaa. FTP toimii c2s eli client to server periaatteella. \n
							Kun siirretään tiedostoja, yleensä se tapahtuu niin että client ottaa yhteyden serveriin. FTP:n tavoitteena on helpottaa tiedostojen
							siirtämistä etänä useille käyttäjille kerrallaan.

 FTP - File Transfer Protocol

							Pelkkä FTP yhteyden käyttäminen ei ole suotavaa tietoturvallisuutta vaativissa
							ympäristöissä sillä FTP yhteys ei ole niin turvallinen, sillä esimerkiksi salasana lähetetään salaamattomina. Tähän tulisi mielummin käyttää SFTP yhteyttä (SSH File Transfer Protocol). FTP-palvelimet ovat hyviä palvelimia ylläpitämään sivustoja ja pieniä tiedostopalvelimia. FTP on todella helppo asentaa palvelimelle ja ei vie palvelimen resursseja juuri ollenkaan (muuta kuin datatilaa) FTP käyttää portteja 21 ja SFTP 22.

 HTTP - HyperText Transfer Protocol

							HTTP protokolla on kehitetty selainten ja WWW-palvelinten tiedonsiirtoon. Yksinkertaisuudessaan asiakasohjelma avaa TCP-yhteyden pavelimelle ja lähettää pyynnön ja palvelin vastaa tähän sopivalla tavalla (html tai binäärimuodossa). \n

							HTTP-siirtotapahtuma koostuu kahdesta HTTP-viestistä: HTTP request ja HTTP response viestistä. Request -pyyntö sisältää pyyntörivin, http-otsakkeet sekä tarvittavan datan. Response -pyyntö taas sisältää tilarivin (status line), http-otsakkeet ja datan.

							HTTP-protokolla käyttää porttia 80.

 IMAP - Internet Message Access Protocol

							IMAP on protokolla jonka avulla käyttäjät voivat hakea säkhöpostiviestejä postipalvelimelta TCP/IP yhteyden yli. IMAP eroaa POP protokollasta niin että POP hakee sähköpostiviestit asiakkaan tiedostohakemistoon, kun taas IMAP pitää sähköpostit palvelimella ja käyttäjä vain hakee ne väliaikaisesti luettavaksi. \n

							IMAP yleensä kuuntelee porttinumeroa 143 ja IMAP over SSL 993.


text:
/**
 * @file
 *   This file includes the declarations of the settings functions from the Qorvo library.
 *
 */

#ifndef SETTINGS_QORVO_H_
#define SETTINGS_QORVO_H_

#include <stdbool.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

void qorvoSettingsInit(void);

otError qorvoSettingsGet(uint16_t aKey, int aIndex, uint8_t *aValue, uint16_t *aValueLength);

otError qorvoSettingsAdd(uint16_t aKey, bool aIndex0, const uint8_t *aValue, uint16_t aValueLength);

otError qorvoSettingsDelete(uint16_t aKey, int aIndex);

void qorvoSettingsWipe(void);

#ifdef __cplusplus
}
#endif

#endif // SETTINGS_QORVO_H_


text:
int main(int argc, char *argv[]) {

    @autoreleasepool {
        int retVal = UIApplicationMain(argc, argv, nil, nil);
        return retVal;
    }
}


text:
package com.ams.security.services;

import com.baldy.commons.security.models.Account;

/**
 * @author mbmartinez
 */
public interface RegistrationService {

    Account register(String username, String password);

}


text:
<!doctype html>

<meta charset="utf-8">
<title>Wanderpol's shoveling</title>
<meta name="description" content="A minimal Jekyll theme for your blog by designer Michael Rose.">
<meta name="keywords" content="Jekyll, theme, responsive, blog, template">

<meta name="twitter:title" content="Wanderpol's shoveling">
<meta name="twitter:description" content="A minimal Jekyll theme for your blog by designer Michael Rose.">

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="/images/sample-image-1.jpg">

<meta property="og:locale" content="ko_KR">
<meta property="og:type" content="article">
<meta property="og:title" content="Wanderpol's shoveling">
<meta property="og:description" content="A minimal Jekyll theme for your blog by designer Michael Rose.">
<meta property="og:url" content="/">
<meta property="og:site_name" content="Wanderpol's shoveling">

<link rel="canonical" href="/">
<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Wanderpol's shoveling Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700%7CPT+Serif:400,700,400italic' rel='stylesheet' type='text/css'>

<link rel="shortcut icon" href="/favicon.ico">

<link rel="shortcut icon" href="/favicon.png">

<link rel="apple-touch-icon-precomposed" href="/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/images/apple-touch-icon-144x144-precomposed.png">

		Wanderpol's shoveling

About

Sample Posts

Theme Setup

Made Mistakes

    Photo Credit: WeGraphics

inuk jeon

Describe your self.

 Email

 Facebook

 Github

Recent Posts

Author Override

A post to test author overrides using a data file.

Syntax Highlighting Post

Demo post displaying the various ways of highlighting code in Markdown.

Sample Link Post

Post with Large Feature Image and Text

Custom written post descriptions are the way to go... if you're not lazy.

A Post with Images

Examples and code for displaying images in posts.

© 2015 inuk jeon. Powered by Jekyll using the Minimal Mistakes theme.


text:
package com.delight.lifeline.UI;

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class LLLocationUpdater implements LocationListener {

	private static final String TAG = "LLLocationWatcher";
	private Context mContext;

	private GetAddressTask currentAddresstask = null;
	LocationManager mLocationManager;

	public static interface LLLocationUpdaterCallBack
	{
		void updateLocationAddress(String address);
	}

	private LLLocationUpdaterCallBack mCallback;

	public LLLocationUpdater(Context context ,LLLocationUpdaterCallBack callBack)
	{
		mContext = context;
		mCallback = callBack;
	    mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

	}

	@Override
	public void onLocationChanged(Location location) {

	    Log.d(TAG, "onLocationChanged longi = "+location.getLongitude() +"latitude = "+location.getLatitude());

		mLocationManager.removeUpdates(this);
		currentAddresstask.cancel(true);
		currentAddresstask = (new GetAddressTask(mContext));
		currentAddresstask.execute(getLastLocation());

	}

  private Location getLastLocation()
  {
	 Location loc1 = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
	 Location loc2 = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

	 if(loc1 == null)
	 {
		 return loc2;
	 }
	 else if(loc2 == null)
	 {
		 return loc1;
	 }
	 long timeDelta = loc2.getTime() - loc1.getTime();
	 boolean isSignificantlyNewer = timeDelta > (2*60*1000);

	 if(isSignificantlyNewer)
		 return loc2;
	 else
		 return loc1;

  }

  public void stop()
  {
		mLocationManager.removeUpdates(this);
		if(currentAddresstask != null)
		{
		  currentAddresstask.cancel(true);
		}
  }

	public void start()
	{
		Location lastLocation = getLastLocation();
		if(lastLocation != null)
		{
			currentAddresstask = (new GetAddressTask(mContext));
			currentAddresstask.execute(getLastLocation());
		}

		try
		{
			if(mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
			{
				mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
			}
			else
			{
				mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
			}
		}
		catch(Exception ex)
		{

		}
	}

	protected class GetAddressTask extends AsyncTask<Location, Void, String> {

        Context localContext;

        public GetAddressTask(Context context) {
            super();
            localContext = context;
        }

        @Override
        protected String doInBackground(Location... params) {

            Location location = params[0];
            String addressText = "";
    		if(Geocoder.isPresent())
    		{
    			Log.d(TAG, "geocoder present");
    			Geocoder coder = new Geocoder(mContext);
    			try {
    				List<Address> addrList = coder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
    				if(addrList != null && !addrList.isEmpty())
    				{
    					Address address = addrList.get(0);

    					 addressText = addressText + ((address.getMaxAddressLineIndex() > 0) ? address.getAddressLine(0):"") +
    	                            address.getLocality() ;
    				}

    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    		return addressText;

        }

        @Override
        protected void onPostExecute(String address) {
        	mCallback.updateLocationAddress(address);

        }
    }

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

}


text:
<?php

namespace Mailgun\Api\Suppression;

use Mailgun\Api\HttpApi;
use Mailgun\Api\Pagination;
use Mailgun\Assert;
use Mailgun\Model\Suppression\Unsubscribe\CreateResponse;
use Mailgun\Model\Suppression\Unsubscribe\DeleteResponse;
use Mailgun\Model\Suppression\Unsubscribe\IndexResponse;
use Mailgun\Model\Suppression\Unsubscribe\ShowResponse;

/**
 * @see https://documentation.mailgun.com/api-suppressions.html#unsubscribes
 *
 * @author Sean Johnson <sean@mailgun.com>
 */
class Unsubscribe extends HttpApi
{
    use Pagination;

    /**
     * @param string $domain Domain to get unsubscribes for
     * @param int    $limit  optional
     *
     * @return IndexResponse
     */
    public function index($domain, $limit = 100)
    {
        Assert::stringNotEmpty($domain);
        Assert::range($limit, 1, 10000, 'Limit parameter must be between 1 and 10000');

        $params = [
            'limit' => $limit,
        ];

        $response = $this->httpGet(sprintf('/v3/%s/unsubscribes', $domain), $params);

        return $this->hydrateResponse($response, IndexResponse::class);
    }

    /**
     * @param string $domain  Domain to show unsubscribe for
     * @param string $address Unsubscribe address
     *
     * @return ShowResponse
     */
    public function show($domain, $address)
    {
        Assert::stringNotEmpty($domain);
        Assert::stringNotEmpty($address);

        $response = $this->httpGet(sprintf('/v3/%s/unsubscribes/%s', $domain, $address));

        return $this->hydrateResponse($response, ShowResponse::class);
    }

    /**
     * @param string $domain  Domain to create unsubscribe for
     * @param string $address Unsubscribe address
     * @param array  $params  optional
     *
     * @return CreateResponse
     */
    public function create($domain, $address, array $params = [])
    {
        Assert::stringNotEmpty($domain);
        Assert::stringNotEmpty($address);

        $params['address'] = $address;

        $response = $this->httpPost(sprintf('/v3/%s/unsubscribes', $domain), $params);

        return $this->hydrateResponse($response, CreateResponse::class);
    }

    /**
     * @param string $domain  Domain to delete unsubscribe for
     * @param string $address Unsubscribe address
     *
     * @return DeleteResponse
     */
    public function delete($domain, $address)
    {
        Assert::stringNotEmpty($domain);
        Assert::stringNotEmpty($address);

        $response = $this->httpDelete(sprintf('/v3/%s/unsubscribes/%s', $domain, $address));

        return $this->hydrateResponse($response, DeleteResponse::class);
    }

    /**
     * @param string $domain Domain to delete all unsubscribes for
     *
     * @return DeleteResponse
     */
    public function deleteAll($domain)
    {
        Assert::stringNotEmpty($domain);

        $response = $this->httpDelete(sprintf('/v3/%s/unsubscribes', $domain));

        return $this->hydrateResponse($response, DeleteResponse::class);
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.CompositeShape2.html">

Redirecting to type.CompositeShape2.html...


text:
use crate::{Version, VersionReq};
use core::fmt;
use serde::de::{Deserialize, Deserializer, Error, Visitor};
use serde::ser::{Serialize, Serializer};

impl Serialize for Version {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.collect_str(self)
    }
}

impl Serialize for VersionReq {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for Version {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct VersionVisitor;

        impl<'de> Visitor<'de> for VersionVisitor {
            type Value = Version;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("semver version")
            }

            fn visit_str<E>(self, string: &str) -> Result<Self::Value, E>
            where
                E: Error,
            {
                string.parse().map_err(Error::custom)
            }
        }

        deserializer.deserialize_str(VersionVisitor)
    }
}

impl<'de> Deserialize<'de> for VersionReq {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct VersionReqVisitor;

        impl<'de> Visitor<'de> for VersionReqVisitor {
            type Value = VersionReq;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("semver version")
            }

            fn visit_str<E>(self, string: &str) -> Result<Self::Value, E>
            where
                E: Error,
            {
                string.parse().map_err(Error::custom)
            }
        }

        deserializer.deserialize_str(VersionReqVisitor)
    }
}


text:
package com.opera.core.systems;

import com.opera.core.systems.testing.OperaDriverTestCase;

import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebElement;

public class StaleElementsSamePageTest extends OperaDriverTestCase {

  public WebElement test;

  @Before
  public void beforeEach() {
    driver.navigate().to(pages.test);
    test = driver.findElement(By.id("header"));
    driver.navigate().to(pages.test);
  }

  @Test(expected = StaleElementReferenceException.class)
  public void testGetAttribute() {
    test.getAttribute("foo");
  }

  @Test(expected = StaleElementReferenceException.class)
  public void testGetText() {
    test.getText();
  }

  @Test(expected = StaleElementReferenceException.class)
  public void testIsDisplayed() {
    test.isDisplayed();
  }

  @Test(expected = StaleElementReferenceException.class)
  public void testIsEnabled() {
    test.isEnabled();
  }

  @Test(expected = StaleElementReferenceException.class)
  public void testIsSelected() {
    test.isSelected();
  }

  @Test(expected = StaleElementReferenceException.class)
  public void testClear() {
    test.clear();
  }

  @Test(expected = StaleElementReferenceException.class)
  public void testGetLocation() {
    test.getLocation();
  }

  @Test(expected = StaleElementReferenceException.class)
  public void testGetSize() {
    test.getSize();
  }

  @Test(expected = StaleElementReferenceException.class)
  public void testTagName() {
    test.getTagName();
  }

}


text:
VertexArrayObject::VertexArrayObject() :
   name(0)
{
   glGenVertexArrays(1, &name);
}

VertexArrayObject::VertexArrayObject(VertexArrayObject && other) :
   name(other.name)
{
   other.name = 0;
}

VertexArrayObject::~VertexArrayObject() {
   glDeleteVertexArrays(1, &name);
}

void VertexArrayObject::bind() const {
   glBindVertexArray(name);
}

void VertexArrayObject::disableVertexAttributeArray(unsigned int index) const {
   glDisableVertexAttribArray(index);
}

void VertexArrayObject::enableVertexAttributeArray(unsigned int index) const {
   glEnableVertexAttribArray(index);
}

VertexArrayObject & VertexArrayObject::operator =(VertexArrayObject && other) {
   std::swap(name, other.name);
   return *this;
}

void VertexArrayObject::unbind() {
   glBindVertexArray(0);
}

void VertexArrayObject::vertexAttributePointer(unsigned int index, int size, Type type, bool normalized, int stride, int offset) const {
   glVertexAttribPointer(index, size, type, normalized, stride, reinterpret_cast<void*>(offset));
}


text:
package com.forum.web.parse;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import com.forum.web.atom.AtomEntry;
import com.forum.web.atom.AtomFeed;
import com.forum.web.atom.Author;
import com.forum.web.atom.Contributor;

public class AtomParser extends Parser {

	public static final int ATOM_CONTENT_MAX_LEN = 10000;
	public static final int ATOM_LANG_MAX_LEN = 20;
	public static final int ATOM_NAME_MAX_LEN = 50;
	public static final int ATOM_STR_MAX_LEN = 1000;

	// XML input factory for streamReaders
	private XMLInputFactory factory = XMLInputFactory.newInstance();

	// Creates a new Rss reader that can aggregate several RssFeeds.
	public AtomParser() {
	}

	// Method for getting the data from a URL
	@SuppressWarnings("unchecked")
	public Stream parseLink(InputStream input) {

		// the Channel that will be returned
		AtomFeed feed = null;

		// represents the items that will be included in this channel
		Set<AtomEntry> feedEntries = new HashSet<AtomEntry>();

		// a stack to represent the dom
		Stack<HashMap<String, Object>> dom = new Stack<HashMap<String, Object>>();

		// a wrapper object for when popping things off the stack
		HashMap<String, Object> top = null;

		try {

			// File file = new File("testAtom.xml");
			// InputStream input = new FileInputStream(file);

			// System.out.println("reading file testRss.xml");

			// set up XML stream reader from the URL
			XMLStreamReader reader = factory.createXMLStreamReader(input);

			while (reader.hasNext()) {
				String ns = reader.getNamespaceURI();
				reader.next();
				if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {

					// get the xml tag name
					String currentElement = reader.getLocalName();
					switch (currentElement) {

					case "feed":
						System.out.println("starting feed");
						dom.push(new HashMap<String, Object>());
						break;

					case "entry":
						dom.push(new HashMap<String, Object>());
						break;

					case "author":
						top = dom.pop();
						if (!top.containsKey("authors")) {
							top.put("authors", new HashSet<Author>());
						}
						dom.push(top);
						dom.push(new HashMap<String, Object>());
						break;

					case "contributor":
						top = dom.pop();
						if (!top.containsKey("contributors")) {
							top.put("contributors", new HashSet<String>());
						}
						dom.push(top);
						dom.push(new HashMap<String, Object>());
						break;

					case "source":
						dom.push(new HashMap<String, Object>());
						break;

					// used by Feed and entry
					case "title":
						top = dom.pop();
						top.put("title", reader.getElementText());
						dom.push(top);
						top = null;
						break;

					// used by Feed and entry
					case "logo":
						top = dom.pop();
						top.put("logo", reader.getElementText());
						dom.push(top);
						top = null;
						break;

					// used by Feed and entry
					case "icon":
						top = dom.pop();
						top.put("icon", reader.getElementText());
						dom.push(top);
						top = null;
						break;

					// used by feed and entry
					case "link":
						String currentLink = reader.getAttributeValue(ns, "href");
						top = dom.pop();
						top.put("link", currentLink);
						dom.push(top);
						top = null;
						break;

					// used by feed and entry
					case "category":
						String cat = reader.getAttributeValue(ns, "term").toLowerCase();
						top = dom.pop();
						if (!top.containsKey("categories")) {
							top.put("categories", new ArrayList<String>());
						}
						List<String> categories = (List<String>) top.get("categories");
						categories.add(cat);
						dom.push(top);
						top = null;
						break;

					// used by entry
					case "summary":
						top = dom.pop();
						top.put("summary", reader.getElementText());
						dom.push(top);
						top = null;
						break;

					// used by entry
					case "content":
						top = dom.pop();
						top.put("content", reader.getElementText());
						dom.push(top);
						top = null;
						break;

					// unique to a channel
					case "rights":
						top = dom.pop();
						top.put("rights", reader.getElementText());
						dom.push(top);
						top = null;
						break;

					// used by feed, entry
					case "updated":
						top = dom.pop();
						top.put("updated", Parser.parseDate(reader.getElementText()));
						dom.push(top);
						top = null;
						break;

					// unique to a feed
					case "generator":
						top = dom.pop();
						top.put("generator", reader.getElementText());
						dom.push(top);
						top = null;
						break;

					// used by feed, entry
					case "id":
						top = dom.pop();
						top.put("id", reader.getElementText());
						dom.push(top);
						top = null;
						break;

					case "name":
						top = dom.pop();
						top.put("name", reader.getElementText());
						dom.push(top);
						top = null;
						break;

					case "email":
						top = dom.pop();
						top.put("email", reader.getElementText());
						dom.push(top);
						top = null;
						break;

					// used by entry
					case "published":
						top = dom.pop();
						top.put("published", Parser.parseDate(reader.getElementText()));
						dom.push(top);
						top = null;
						break;

					// used by feed
					case "subtitle":
						top = dom.pop();
						top.put("subtitle", reader.getElementText());
						dom.push(top);
						top = null;
						break;

					}

					// the entry/feed is finished, we need to use what we've
					// gathered and make an object out of it
				} else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {

					// get what type of element is ending
					String endElement = reader.getLocalName();

					// create an object depending on what it is
					switch (endElement) {

					// the channel is closed, create an RssChannel out of its
					// sub-elements
					case "feed":
						top = dom.pop();

						// if the channel has the minimum required elements, get
						// to work!
						if (top.containsKey("title") && top.containsKey("id")
								&& top.containsKey("updated")) {

							// created builder from core required elements
							feed = new AtomFeed((String) top.get("title"),
									(String) top.get("id"),
									(long) top.get("updated"));

							// add recommended elements as they exist
							// if the feed map has an author key, it should
							// point to an ArrayList of author names (Strings)
							if (top.containsKey("authors")) {
								feed.addAuthors((Set<Author>) top.get("authors"));
							}

							if (top.containsKey("contributors")) {
								feed.setContributors((Set<Contributor>) top.get("contributors"));
							}

							if (top.containsKey("link")) {
								feed.setLink((String) top.get("link"));
							}

							if (top.containsKey("categories")) {
								feed.setCategories((List<String>) top.get("categories"));
							}

							if (top.containsKey("rights")) {
								feed.setRights((String) top.get("copyright"));
							}

							if (top.containsKey("generator")) {
								feed.setGenerator((String) top.get("generator"));
							}

							if (top.containsKey("logo")) {
								feed.setLogo((String) top.get("logo"));
							}

							if (top.containsKey("icon")) {
								feed.setIcon((String) top.get("icon"));
							}
							if (top.containsKey("subtitle")) {
								feed.setSubtitle((String) top.get("subtitle"));
							}

							feed.addEntries(feedEntries);

						}
						// top = null;
						break;

					// an item has closed, create an RssItem out of it's
					// sub-elements
					case "entry":
						top = dom.pop();
						AtomEntry entry;

						// check if a required field is missing
						if (top.containsKey("title") && top.containsKey("id") && top.containsKey("updated")) {
							entry = new AtomEntry((String) top.get("title"),
									(String) top.get("id"),
									(long) top.get("updated"));

							// add optional fields if they exist
							if (top.containsKey("authors")) {
								entry.setAuthors((Set<Author>) top.get("authors"));
							}

							if (top.containsKey("content")) {
								entry.setContent((String) top.get("content"));
							}

							if (top.containsKey("link")) {
								entry.setLink((String) top.get("link"));
							}

							if (top.containsKey("summary")) {
								entry.setSummary((String) top.get("summary"));
							}

							if (top.containsKey("categories")) {
								entry.setCategories((List<String>) top.get("categories"));
							}

							if (top.containsKey("contributors")) {
								entry.setContributors((Set<Contributor>) top.get("contributors"));
							}

							if (top.containsKey("published")) {
								entry.setPublished((long) top.get("published"));
							}

							if (top.containsKey("source")) {
								entry.setSource((AtomFeed) top.get("source"));
							}

							if (top.containsKey("rights")) {
								entry.setRights((String) top.get("rights"));
							}

							feedEntries.add(entry);

						} else {
							System.out.println("bad entry");
						}
						top = null;
						break;

					// create an image object from previous data and put it into
					// its supertag's hashmap
					case "author":
						top = dom.pop();
						Author author;

						// if the required field exists...
						if (top.containsKey("name")) {
							author = new Author((String) top.get("name"));

							if (top.containsKey("email")) {
								author.setEmail((String) top.get("email"));
							}

							if (top.containsKey("uri")) {
								author.setUri((String) top.get("uri"));
							}

							// put it back onto the dom into its super's hashmap
							top = dom.pop();
							Set<Author> authors = (Set<Author>) top.get("authors");
							authors.add(author);
							top.put("authors", authors);
							dom.push(top);
							top = null;
						}
						break;

					// a textInput has closed. Create a TextInput object and add
					// it to the dom in its super's Object hashmap
					case "contributor":
						top = dom.pop();
						Contributor contributor;

						// if the required field exists...
						if (top.containsKey("name")) {
							contributor = new Contributor((String) top.get("name"));

							if (top.containsKey("email")) {
								contributor.setEmail((String) top.get("email"));
							}

							if (top.containsKey("uri")) {
								contributor.setUri((String) top.get("uri"));
							}

							// put it back onto the dom into its super's hashmap
							top = dom.pop();
							Set<Contributor> contributors = (Set<Contributor>) top.get("contributors");
							contributors.add(contributor);
							top.put("contributors", contributors);
							dom.push(top);
							top = null;
						}
						break;

					// and enclosure has closed. create an object and add it to
					// its super element's hashmap
					case "source":
						top = dom.pop();
						AtomFeed source;

						if (top.containsKey("title")
								&& top.containsKey("link")
								&& top.containsKey("updated")) {
							source = new AtomFeed(
									(String) top.get("title"),
									(String) top.get("link"), Parser.parseDate((String) top
											.get("updated")));

							// put it back onto the dom into its super's hashmap
							top = dom.pop();
							top.put("source", source);
							dom.push(top);
							top = null;
						}
						break;

					}
				}

			}

		} catch (XMLStreamException e) {
			System.out.print("Error when parsing xml: ");
			System.out.println(e);
			System.exit(1);

		}

		// print out diagnostics for debugging
//		if (feed != null) {
//			System.out.println(feed.toString());
//			System.out.println("Items in channel:");
//			for (AtomEntry entry : feed.getEntries()) {
//				System.out.println(entry.toString());
//			}
//			System.out.println("Feed's entry count: "
//					+ feed.getEntries().size());
//			System.out.println("parsing complete.");
//
//		} else {
//			System.out
//					.println("parsing failed. Feed returned is a null object");
//		}

		return (Stream) feed;

	}

}


text:
'use strict';

import { overlayElement } from './overlay';

const reHtml = /[&<>]/g;
const htmlEntities = {
  '&': '&',
  '<': '<',
  '>': '>',
};

export function setAttributes(element, id, args) {
  element.setAttribute('data-l10n-id', id);
  if (args) {
    element.setAttribute('data-l10n-args', JSON.stringify(args));
  }
}

export function getAttributes(element) {
  return {
    id: element.getAttribute('data-l10n-id'),
    args: JSON.parse(element.getAttribute('data-l10n-args'))
  };
}

function getTranslatables(element) {
  const nodes = Array.from(element.querySelectorAll('[data-l10n-id]'));

  if (typeof element.hasAttribute === 'function' &&
      element.hasAttribute('data-l10n-id')) {
    nodes.push(element);
  }

  return nodes;
}

export function translateMutations(view, langs, mutations) {
  const targets = new Set();

  for (let mutation of mutations) {
    switch (mutation.type) {
      case 'attributes':
        targets.add(mutation.target);
        break;
      case 'childList':
        for (let addedNode of mutation.addedNodes) {
          if (addedNode.nodeType === addedNode.ELEMENT_NODE) {
            if (addedNode.childElementCount) {
              getTranslatables(addedNode).forEach(targets.add.bind(targets));
            } else {
              if (addedNode.hasAttribute('data-l10n-id')) {
                targets.add(addedNode);
              }
            }
          }
        }
        break;
    }
  }

  if (targets.size === 0) {
    return;
  }

  translateElements(view, langs, Array.from(targets));
}

export function translateFragment(view, langs, frag) {
  return translateElements(view, langs, getTranslatables(frag));
}

function getElementsTranslation(view, langs, elems) {
  const keys = elems.map(elem => {
    const id = elem.getAttribute('data-l10n-id');
    const args = elem.getAttribute('data-l10n-args');
    return args ? [
      id,
      JSON.parse(args.replace(reHtml, match => htmlEntities[match]))
    ] : id;
  });

  return view._resolveEntities(langs, keys);
}

function translateElements(view, langs, elements) {
  return getElementsTranslation(view, langs, elements).then(
    translations => applyTranslations(view, elements, translations));
}

function applyTranslations(view, elems, translations) {
  view._disconnect();
  for (let i = 0; i < elems.length; i++) {
    overlayElement(elems[i], translations[i]);
  }
  view._observe();
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Michelia 2(no. 6): 113 (1880)

#### Original name
Leptostroma vulgare Fr., 1823

### Remarks
null


text:
using System;
using System.Text;

namespace DataBoss.Diagnostics
{
	public class QuerySample
	{
		public QuerySample(RequestInfo request, byte[] sql) {
			this.Request = request;
			this.Query = Encoding.Unicode.GetString(sql);
		}
		public readonly RequestInfo Request;
		public TimeSpan Elapsed => TimeSpan.FromMilliseconds(Request.ElapsedMilliseconds);
		public readonly string Query;
		public string ActiveStatement => Request.StatementEndOffset == -1
			? Query.Substring(Request.StatementStartOffset / 2)
			: Query.Substring(Request.StatementStartOffset / 2, (Request.StatementEndOffset - Request.StatementStartOffset) / 2 + 1);
	}
}


text:
package noop.model;

import noop.graph.ModelVisitor;

/**
 * @author alexeagle@google.com (Alex Eagle)
 */
public class AnonymousBlock extends Block<AnonymousBlock> {

  public AnonymousBlock() {
    super("[anonymous]");
  }

  @Override
  public void accept(ModelVisitor v) {
    v.visit(this);
    super.accept(v);
  }
}