text:
![Feature Image](images/FeatureImage.gif)

Add a map on your site with every place that you have visited! [Demo](http://www.vinaygaba.com/traveller/demo.html)

---

Introduction
-----

My motivation behind creating Traveller was to create a [map for my website](http://www.vinaygaba.com/traveller/demo.html) that showcases the places that I have visited. I soon realized that there might be more people(developers) who would want to have a similar page on their site so I decided to put this up on Github.

As of now, it is a simple html page but going forward, I will be working on converting this into a React component so that it can be easily added to any web app.

I will try to be as elaborate as possible in giving instructions about how one might use this and customize it to suit their needs.

The blue markers represent the cities that I have lived in and the green markers represent the places I have travelled to.

Usage
------
The code for the webpage is the [index.html](index.html) file.

First, you need to get a key to be able to use the Google Maps Javascript API. If you do not have one, go to the following [link](https://developers.google.com/maps/documentation/javascript/) and click on the "Get a Key" button on the top right corner. Once you have the key, find the following line in the index.html page and replace the placeholder with your key.
```
<script src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_MAP_API_KEY&callback=initMap" async defer></script>
```

The html page parses a JSON file in order to know which points need to be populated on the map. The format of the JSON string needs to be as follows:

```JSON
[
  {
    "name":"Name of place",
    "lat":"Latitude",
    "lon":"Longitude",
    "purpose":"lived/travelled"
  },
  {
    "name":"Name of place",
    "lat":"Latitude",
    "lon":"Longitude",
    "purpose":"lived/travelled"
  },
  .
  .
  .
]
```
Right now I use two different markers to represent whether you lived in a city or were just travelling. If you do not like this, it would be pretty simple to remove this by making changes in the styles.css file. More about this in the Customizations section.

Example JSON files can be found in [data](data/) folder.
You can either save the JSON file in the same server or host the json file on a service like [myjson](http://myjson.com)

To specify which JSON file to use, find the ```$.getJSON(pathToJSONFile,function(..))``` method call in the html page and replace the jsonPath with the path to your JSON file.

And this is it! This is the only step that is required in order to see the populated world map that you see in the above screenshot.

Note: I understand that manually adding the locations can be a pain in the butt, especially for people who have travelled a lot. This will change soon as I am exploring alternate ways to do this(Facebook/Foursquare Checkins). I am also open to suggestions from you guys so feel free to use the Issue tracker to give me feedback.

Customizations
-----

I have added a few map styles that I personally liked in [mapstyles.js](js/mapstyles.js). To use them, import the js file in your html page(Already added in index.html page) and replace the palceholder text in the following line with one of the possibly map styles:

```
map.set('styles',NAME_OF_STYLE);

//Example
map.set('style',prestoMap);

```

Here is a list of the possible map styles that you can add by default.

###### prestoMap

![prestoMap](images/prestoMap.png)

###### google

![google](images/google.png)

###### cladme

![cladme](images/cladme.png)

###### cleanerMidnight

![cleanerMidnight](images/cleanerMidnight.png)

###### midnightCommander

![midnightCommander](images/midnightCommander.png)

###### shadesOfGray

![shadesOfGray](images/shadesOfGray.png)

You can very easily add more styles to the [mapstyles.js](js/mapstyles.js) file by going to [Snazzy Maps](https://snazzymaps.com/) and copy pasting the code for any of the map styles that you might like from the site.

To Do
-----
This is very early stages for this project and I definitely plan to make it more useful. I would love to get more people involved and so here are a list of things that I would appreciate getting some help on:

- Convert it into a React component
- Enter place names instead of lat/lng values int the json file. Will probably need to use the Geocoding API. (Under development. Check [link](index-geocode.html))
- Add more information when you hover over a marker. Something like an image from the trip could be useful. Or a side panel that loads when you click on a marker which contains all the images from the trip.

Inspiration
-------
Traveller was inspired by [Conquer.earth](https://conquer.earth) which was developed by Dustin Curtis. I wanted Traveller to be something that I can host on my own site.

Credits
-----------------
Author: Vinay Gaba (vinaygaba@gmail.com)

License
-------

    Copyright 2016 Vinay Gaba

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
author: makishvili
comments: true
date: 2009-10-02 08:54:43+00:00
layout: post
slug: priroda-civilizovannosti
title: Природа цивилизованности
wordpress_id: 1170
categories:
- life
tags:
- Качество жизни
- Наблюдения
- Образование
- Психология
---

Я считаю себя человеком социальным, образованным и защищенным от естественных врагов. Но так ли это?
Моя "социальность" и "образованность" — понятия относительные для текущей эпохи, но спорность их невелика — документ о высшем образовании у меня есть и "социальность" могу подтвердить 30-тью годами успешного сознательного общения с себе подобными. Я социален и образован.

Но вот с чувством защищенности похуже. Пожив четыре дня на диком пляже, оно ушло на второй день. Это было неожиданно.<!-- more -->

Жизнь в социуме людей дает какую-то уверенность, что меня "кто-то охраняет", что есть какие-то законы и органы наблюдения за их исполнением. Что есть милиция, которая придёт на помощь, когда моих сил не хватит, чтобы справиться с агрессивным соседом.

Но стоит выйти на моторной лодке в море, через 15 минут высадиться на диком пляже, который выдается в открытое море мысом, где с палатками стоят подобные мне цивилизованные и образованные люди, чтобы на второй день понять, что никто кроме меня самого здесь не защитит ни меня, ни мою семью.

На этом удаленном от цивилизации пляже возникают большие сомнения, что цивилизованность - природное свойство человека. По той причине, что цивилизованность, как тонкий слой пота, очень быстро смывается соленой водой чувства бесконтрольности: "Только вчера он был улыбчивым неплохим парнем, а сегодня у него сжатые кулаки и на лице непонятно за что появившаяся угроза". И как обухом по голове приходит понимание, что я и моя семья семья сейчас _здесь_, а законы, милиция и цивилизация остались _там_ — недостижимо далеко от нас - всего в паре километров за горой. И там (там!) сейчас празднично бурлит курортная жизнь, по вечерней  набережной прогуливаются нарядно одетые люди, а здесь на тебя смотрит выпивший человек и ему нет преград, кроме тебя самого.

Так что, социальная защищенность — это миф. А цивилизованность человека скорее обусловлена законами общества, сдерживающими природную агрессивность человека. И если человек себя сам удерживает в рамках социальных законов, удерживает несмотря ни на что, тогда он цивилизован. А если спускает себя с цепи, то... примеров в жизни достаточно — это и мать, орущая на ребенка; и сосед, обливающий мочой пол в лифте.

А если я про природу своей цивилизованности вдруг забуду, то мне легко напомнят об этом книга [Уильяма Голдинга](http://slovari.yandex.ru/dict/krugosvet/article/0/0b/1003034.htm) "Повелитель мух" , художественный фильм ["Das Experiment"](http://www.kinokopilka.ru/movies/2202-eksperiment) и TED-презентация Филиппа Зимбардо, который был основателем Стэнфордского тюремного эксперимента в 1971 году

**Включить русские субтитры:** View subtitles -> Russian

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.apache.camel</groupId>
    <artifactId>examples</artifactId>
    <version>2.20.0-SNAPSHOT</version>
  </parent>

  <artifactId>camel-example-rest-producer</artifactId>
  <name>Camel :: Example :: Rest Producer</name>
  <description>An example showing how to use Camel Rest to call a REST service</description>

  <properties>
    <category>Rest</category>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <spring.boot-version>${spring-boot-version}</spring.boot-version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <!-- Spring Boot BOM -->
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>${spring.boot-version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <!-- Camel BOM -->
      <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-spring-boot-dependencies</artifactId>
        <version>${project.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>

    <!-- Spring Boot -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-undertow</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-actuator</artifactId>
    </dependency>

    <!-- Camel -->
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-spring-boot-starter</artifactId>
    </dependency>

    <!-- support swagger api-doc -->
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-swagger-java-starter</artifactId>
    </dependency>

    <!-- use http4 as rest producer -->
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-http4-starter</artifactId>
    </dependency>

    <!-- test -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-test-spring</artifactId>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>${spring-boot-version}</version>
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>jdk9-build</id>
      <activation>
        <jdk>9</jdk>
      </activation>
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
              <argLine>--add-modules java.xml.bind --add-opens java.base/java.lang=ALL-UNNAMED</argLine>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
</project>


text:
package mock

import (
	"errors"

	"github.com/micromdm/mdm"
	"golang.org/x/net/context"
)

type Checkin struct {
	AuthenticateInvoked bool
	AuthenticateFunc    CheckinFunc

	TokenUpdateInvoked bool
	TokenUpdateFunc    CheckinFunc

	CheckOutInvoked bool
	CheckoutFunc    CheckinFunc
}

type CheckinFunc func(ctx context.Context, cmd mdm.CheckinCommand) error

func (svc *Checkin) Authenticate(ctx context.Context, cmd mdm.CheckinCommand) error {
	svc.AuthenticateInvoked = true
	return svc.AuthenticateFunc(ctx, cmd)
}

func (svc *Checkin) TokenUpdate(ctx context.Context, cmd mdm.CheckinCommand) error {
	svc.TokenUpdateInvoked = true
	return svc.TokenUpdateFunc(ctx, cmd)
}

func (svc *Checkin) CheckOut(ctx context.Context, cmd mdm.CheckinCommand) error {
	svc.CheckOutInvoked = true
	return svc.CheckoutFunc(ctx, cmd)
}

func FailCheckin(context.Context, mdm.CheckinCommand) error {
	return errors.New("checkin failed")
}

func SucceedCheckin(context.Context, mdm.CheckinCommand) error {
	return nil
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>coreServlet</servlet-name>
        <servlet-class>
            com.roger.kxmoment.servlet.CoreServlet
        </servlet-class>
    </servlet>

    <!-- url-pattern中配置的/coreServlet用于指定该Servlet的访问路径 -->
    <servlet-mapping>
        <servlet-name>coreServlet</servlet-name>
        <url-pattern>/coreServlet</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PublishConfigData" serverName="choregraphy">
    <serverData>
      <paths name="choregraphy">
        <serverdata>
          <mappings>
            <mapping deploy="/" local="$PROJECT_DIR$/dist" web="/" />
          </mappings>
        </serverdata>
      </paths>
    </serverData>
  </component>
</project>


text:
#ifdef HAVE_CONFIG_H
#include "../../../../ext_config.h"
#endif

#include <php.h>
#include "../../../../php_ext.h"
#include "../../../../ext.h"

#include <Zend/zend_exceptions.h>

#include "kernel/main.h"

/**
 * Base exception interface for barcode objects
 */
ZEPHIR_INIT_CLASS(ZendFramework_Barcode_Object_Exception_ExceptionInterface) {

	ZEPHIR_REGISTER_INTERFACE(Zend\\Barcode\\Object\\Exception, ExceptionInterface, zendframework, barcode_object_exception_exceptioninterface, NULL);

	zend_class_implements(zendframework_barcode_object_exception_exceptioninterface_ce TSRMLS_CC, 1, zendframework_barcode_exception_exceptioninterface_ce);
	return SUCCESS;

}


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var aurelia_dependency_injection_1 = require('aurelia-dependency-injection');
var material_design_1 = require('../designs/material-design');
var Web = (function () {
    function Web(design) {
        this.design = design;
        this.type = 'web';
        this.isAvailable = true;
    }
    Web.prototype.start = function () {
        var _this = this;
        return Promise.resolve().then(function () { return _this; });
    };
    Web = __decorate([
        aurelia_dependency_injection_1.inject(material_design_1.MaterialDesign)
    ], Web);
    return Web;
}());
exports.Web = Web;


text:
/*
 * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * See https://github.com/openiddict/openiddict-core for more information concerning
 * the license and the contributors participating to this project.
 */

using System.Diagnostics;
using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Primitives;
using AspNet.Security.OpenIdConnect.Server;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OpenIddict.Core;

namespace OpenIddict
{
    public partial class OpenIddictProvider<TApplication, TAuthorization, TScope, TToken> : OpenIdConnectServerProvider
        where TApplication : class where TAuthorization : class where TScope : class where TToken : class
    {
        public override async Task ValidateTokenRequest([NotNull] ValidateTokenRequestContext context)
        {
            var applications = context.HttpContext.RequestServices.GetRequiredService<OpenIddictApplicationManager<TApplication>>();
            var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<OpenIddictProvider<TApplication, TAuthorization, TScope, TToken>>>();
            var options = context.HttpContext.RequestServices.GetRequiredService<IOptions<OpenIddictOptions>>();

            // Reject token requests that don't specify a supported grant type.
            if (!options.Value.GrantTypes.Contains(context.Request.GrantType))
            {
                logger.LogError("The token request was rejected because the '{Grant}' " +
                                "grant is not supported.", context.Request.GrantType);

                context.Reject(
                    error: OpenIdConnectConstants.Errors.UnsupportedGrantType,
                    description: "The specified grant_type is not supported by this authorization server.");

                return;
            }

            // Reject token requests that specify scope=offline_access if the refresh token flow is not enabled.
            if (context.Request.HasScope(OpenIdConnectConstants.Scopes.OfflineAccess) &&
               !options.Value.GrantTypes.Contains(OpenIdConnectConstants.GrantTypes.RefreshToken))
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidRequest,
                    description: "The 'offline_access' scope is not allowed.");

                return;
            }

            // Optimization: the OpenID Connect server middleware automatically rejects grant_type=authorization_code
            // requests missing the redirect_uri parameter if one was specified in the initial authorization request.
            // Since OpenIddict doesn't allow redirect_uri-less authorization requests, an earlier check can be made here,
            // which saves the OpenID Connect server middleware from having to deserialize the authorization code ticket.
            // See http://openid.net/specs/openid-connect-core-1_0.html#TokenRequestValidation for more information.
            if (context.Request.IsAuthorizationCodeGrantType() && string.IsNullOrEmpty(context.Request.RedirectUri))
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidRequest,
                    description: "The mandatory 'redirect_uri' parameter was missing.");

                return;
            }

            // Note: the OpenID Connect server middleware allows returning a refresh token with grant_type=client_credentials,
            // though it's usually not recommended by the OAuth2 specification. To encourage developers to make a new
            // grant_type=client_credentials request instead of using refresh tokens, OpenIddict uses a stricter policy
            // that rejects grant_type=client_credentials requests containing the 'offline_access' scope.
            // See https://tools.ietf.org/html/rfc6749#section-4.4.3 for more information.
            if (context.Request.IsClientCredentialsGrantType() &&
                context.Request.HasScope(OpenIdConnectConstants.Scopes.OfflineAccess))
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidRequest,
                    description: "The 'offline_access' scope is not allowed when using grant_type=client_credentials.");

                return;
            }

            // Optimization: the OpenID Connect server middleware automatically rejects grant_type=client_credentials
            // requests when validation is skipped but an earlier check is made here to avoid making unnecessary
            // database roundtrips to retrieve the client application corresponding to the client_id.
            if (context.Request.IsClientCredentialsGrantType() && (string.IsNullOrEmpty(context.Request.ClientId) ||
                                                                   string.IsNullOrEmpty(context.Request.ClientSecret)))
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidRequest,
                    description: "Client applications must be authenticated to use the client credentials grant.");

                return;
            }

            // At this stage, skip client authentication if the client identifier is missing
            // or reject the token request if client identification is set as required.
            // Note: the OpenID Connect server middleware will automatically ensure that
            // the calling application cannot use an authorization code or a refresh token
            // if it's not the intended audience, even if client authentication was skipped.
            if (string.IsNullOrEmpty(context.ClientId))
            {
                // Reject the request if client identification is mandatory.
                if (options.Value.RequireClientIdentification)
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidRequest,
                        description: "The mandatory 'client_id' parameter was missing.");

                    return;
                }

                logger.LogDebug("The token request validation process was partially skipped " +
                                "because the 'client_id' parameter was missing or empty.");

                context.Skip();

                return;
            }

            // Retrieve the application details corresponding to the requested client_id.
            var application = await applications.FindByClientIdAsync(context.ClientId, context.HttpContext.RequestAborted);
            if (application == null)
            {
                logger.LogError("The token request was rejected because the client " +
                                "application was not found: '{ClientId}'.", context.ClientId);

                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidClient,
                    description: "Application not found in the database: ensure that your client_id is correct.");

                return;
            }

            if (await applications.IsPublicAsync(application, context.HttpContext.RequestAborted))
            {
                // Note: public applications are not allowed to use the client credentials grant.
                if (context.Request.IsClientCredentialsGrantType())
                {
                    logger.LogError("The token request was rejected because the public client application '{ClientId}' " +
                                    "was not allowed to use the client credentials grant.", context.Request.ClientId);

                    context.Reject(
                        error: OpenIdConnectConstants.Errors.UnauthorizedClient,
                        description: "Public clients are not allowed to use the client credentials grant.");

                    return;
                }

                // Reject tokens requests containing a client_secret when the client is a public application.
                if (!string.IsNullOrEmpty(context.ClientSecret))
                {
                    logger.LogError("The token request was rejected because the public application '{ClientId}' " +
                                    "was not allowed to send a client secret.", context.ClientId);

                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidRequest,
                        description: "Public clients are not allowed to send a client_secret.");

                    return;
                }

                logger.LogInformation("The token request validation process was not fully validated because " +
                                      "the client '{ClientId}' was a public application.", context.ClientId);

                // If client authentication cannot be enforced, call context.Skip() to inform
                // the OpenID Connect server middleware that the caller cannot be fully trusted.
                context.Skip();

                return;
            }

            // Confidential applications MUST authenticate
            // to protect them from impersonation attacks.
            if (string.IsNullOrEmpty(context.ClientSecret))
            {
                logger.LogError("The token request was rejected because the confidential application " +
                                "'{ClientId}' didn't specify a client secret.", context.ClientId);

                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidClient,
                    description: "Missing credentials: ensure that you specified a client_secret.");

                return;
            }

            if (!await applications.ValidateClientSecretAsync(application, context.ClientSecret, context.HttpContext.RequestAborted))
            {
                logger.LogError("The token request was rejected because the confidential application " +
                                "'{ClientId}' didn't specify valid client credentials.", context.ClientId);

                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidClient,
                    description: "Invalid credentials: ensure that you specified a correct client_secret.");

                return;
            }

            context.Validate();
        }

        public override async Task HandleTokenRequest([NotNull] HandleTokenRequestContext context)
        {
            var options = context.HttpContext.RequestServices.GetRequiredService<IOptions<OpenIddictOptions>>();
            var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<OpenIddictProvider<TApplication, TAuthorization, TScope, TToken>>>();
            var tokens = context.HttpContext.RequestServices.GetRequiredService<OpenIddictTokenManager<TToken>>();

            if (!options.Value.DisableTokenRevocation && (context.Request.IsAuthorizationCodeGrantType() ||
                                                          context.Request.IsRefreshTokenGrantType()))
            {
                Debug.Assert(context.Ticket != null, "The authentication ticket shouldn't be null.");

                // Extract the token identifier from the authentication ticket.
                var identifier = context.Ticket.GetTicketId();
                Debug.Assert(!string.IsNullOrEmpty(identifier),
                    "The authentication ticket should contain a ticket identifier.");

                if (context.Request.IsAuthorizationCodeGrantType())
                {
                    // Retrieve the token from the database and ensure it is still valid.
                    var token = await tokens.FindByIdAsync(identifier, context.HttpContext.RequestAborted);
                    if (token == null)
                    {
                        logger.LogError("The token request was rejected because the authorization code was revoked.");

                        context.Reject(
                            error: OpenIdConnectConstants.Errors.InvalidGrant,
                            description: "The authorization code is no longer valid.");

                        return;
                    }

                    // Revoke the authorization code to prevent token reuse.
                    await tokens.RevokeAsync(token, context.HttpContext.RequestAborted);
                }

                else if (context.Request.IsRefreshTokenGrantType())
                {
                    // Retrieve the token from the database and ensure it is still valid.
                    var token = await tokens.FindByIdAsync(identifier, context.HttpContext.RequestAborted);
                    if (token == null)
                    {
                        logger.LogError("The token request was rejected because the refresh token was revoked.");

                        context.Reject(
                            error: OpenIdConnectConstants.Errors.InvalidGrant,
                            description: "The refresh token is no longer valid.");

                        return;
                    }

                    // When sliding expiration is enabled, immediately
                    // revoke the refresh token to prevent future reuse.
                    // See https://tools.ietf.org/html/rfc6749#section-6.
                    if (context.Options.UseSlidingExpiration)
                    {
                        await tokens.RevokeAsync(token, context.HttpContext.RequestAborted);
                    }
                }
            }

            // Invoke the rest of the pipeline to allow
            // the user code to handle the token request.
            context.SkipToNextMiddleware();
        }
    }
}


text:
USE master
GO

CREATE PROC usp_DeleteCacheDatabase
AS
    DROP DATABASE CacheDatabase
    GO
GO

USE master
GO

EXEC usp_DeleteCacheDatabase;


text:
#include "RF24Network_config.h"
#include "RF24.h"
#include "RF24Network.h"

uint16_t RF24NetworkHeader::next_id = 1;

uint64_t pipe_address( uint16_t node, uint8_t pipe );
bool is_valid_address( uint16_t node );

/******************************************************************/

RF24Network::RF24Network( RF24& _radio ): radio(_radio), next_frame(frame_queue)
{
}

/******************************************************************/

void RF24Network::begin(uint8_t _channel, uint16_t _node_address )
{
  if (! is_valid_address(_node_address) )
    return;

  node_address = _node_address;

  // Set up the radio the way we want it to look
  radio.setChannel(_channel);
  radio.setDataRate(RF24_1MBPS);
  radio.setCRCLength(RF24_CRC_16);

  // Setup our address helper cache
  setup_address();

  // Open up all listening pipes
  int i = 6;
  while (i--)
    radio.openReadingPipe(i,pipe_address(_node_address,i));
  radio.startListening();

  // Spew debugging state about the radio
  radio.printDetails();
}

/******************************************************************/

void RF24Network::update(void)
{
  // if there is data ready
  uint8_t pipe_num;
  while ( radio.available(&pipe_num) )
  {
    // Dump the payloads until we've gotten everything
    boolean done = false;
    while (!done)
    {
      // Fetch the payload, and see if this was the last one.
      done = radio.read( frame_buffer, sizeof(frame_buffer) );

      // Read the beginning of the frame as the header
      const RF24NetworkHeader& header = * reinterpret_cast<RF24NetworkHeader*>(frame_buffer);

      IF_SERIAL_DEBUG(printf_P(PSTR("%lu: MAC Received on %u %s\n\r"),millis(),pipe_num,header.toString()));
      IF_SERIAL_DEBUG(const uint16_t* i = reinterpret_cast<const uint16_t*>(frame_buffer + sizeof(RF24NetworkHeader));printf_P(PSTR("%lu: NET message %04x\n\r"),millis(),*i));

      // Throw it away if it's not a valid address
      if ( !is_valid_address(header.to_node) )
	continue;

      // Is this for us?
      if ( header.to_node == node_address )
	// Add it to the buffer of frames for us
	enqueue();
      else
	// Relay it
	write(header.to_node);

      // NOT NEEDED anymore.  Now all reading pipes are open to start.
#if 0
      // If this was for us, from one of our children, but on our listening
      // pipe, it could mean that we are not listening to them.  If so, open up
      // and listen to their talking pipe

      if ( header.to_node == node_address && pipe_num == 0 && is_descendant(header.from_node) )
      {
	uint8_t pipe = pipe_to_descendant(header.from_node);
	radio.openReadingPipe(pipe,pipe_address(node_address,pipe));

	// Also need to open pipe 1 so the system can get the full 5-byte address of the pipe.
	radio.openReadingPipe(1,pipe_address(node_address,1));
      }
#endif
    }
  }
}

/******************************************************************/

bool RF24Network::enqueue(void)
{
  bool result = false;

  IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Enqueue @%x "),millis(),next_frame-frame_queue));

  // Copy the current frame into the frame queue
  if ( next_frame < frame_queue + sizeof(frame_queue) )
  {
    memcpy(next_frame,frame_buffer, frame_size );
    next_frame += frame_size;

    result = true;
    IF_SERIAL_DEBUG(printf_P(PSTR("ok\n\r")));
  }
  else
  {
    IF_SERIAL_DEBUG(printf_P(PSTR("failed\n\r")));
  }

  return result;
}

/******************************************************************/

bool RF24Network::available(void)
{
  // Are there frames on the queue for us?
  return (next_frame > frame_queue);
}

/******************************************************************/

uint16_t RF24Network::parent() const
{
  if ( node_address == 0 )
    return -1;
  else
    return parent_node;
}

/******************************************************************/

void RF24Network::peek(RF24NetworkHeader& header)
{
  if ( available() )
  {
    // Copy the next available frame from the queue into the provided buffer
    memcpy(&header,next_frame-frame_size,sizeof(RF24NetworkHeader));
  }
}

/******************************************************************/

size_t RF24Network::read(RF24NetworkHeader& header,void* message, size_t maxlen)
{
  size_t bufsize = 0;

  if ( available() )
  {
    // Move the pointer back one in the queue
    next_frame -= frame_size;
    uint8_t* frame = next_frame;

    // How much buffer size should we actually copy?
    bufsize = min(maxlen,frame_size-sizeof(RF24NetworkHeader));

    // Copy the next available frame from the queue into the provided buffer
    memcpy(&header,frame,sizeof(RF24NetworkHeader));
    memcpy(message,frame+sizeof(RF24NetworkHeader),bufsize);

    IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Received %s\n\r"),millis(),header.toString()));
  }

  return bufsize;
}

/******************************************************************/

bool RF24Network::write(RF24NetworkHeader& header,const void* message, size_t len)
{
  // Fill out the header
  header.from_node = node_address;

  // Build the full frame to send
  memcpy(frame_buffer,&header,sizeof(RF24NetworkHeader));
  if (len)
    memcpy(frame_buffer + sizeof(RF24NetworkHeader),message,min(frame_size-sizeof(RF24NetworkHeader),len));

  IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Sending %s\n\r"),millis(),header.toString()));
  if (len)
  {
    IF_SERIAL_DEBUG(const uint16_t* i = reinterpret_cast<const uint16_t*>(message);printf_P(PSTR("%lu: NET message %04x\n\r"),millis(),*i));
  }

  // If the user is trying to send it to himself
  if ( header.to_node == node_address )
    // Just queue it in the received queue
    return enqueue();
  else
    // Otherwise send it out over the air
    return write(header.to_node);
}

/******************************************************************/

bool RF24Network::write(uint16_t to_node)
{
  bool ok = false;

  // Throw it away if it's not a valid address
  if ( !is_valid_address(to_node) )
    return false;

  // First, stop listening so we can talk.
  //radio.stopListening();

  // Where do we send this?  By default, to our parent
  uint16_t send_node = parent_node;
  // On which pipe
  uint8_t send_pipe = parent_pipe;

  // If the node is a direct child,
  if ( is_direct_child(to_node) )
  {
    // Send directly
    send_node = to_node;

    // To its listening pipe
    send_pipe = 0;
  }
  // If the node is a child of a child
  // talk on our child's listening pipe,
  // and let the direct child relay it.
  else if ( is_descendant(to_node) )
  {
    send_node = direct_child_route_to(to_node);
    send_pipe = 0;
  }

  IF_SERIAL_DEBUG(printf_P(PSTR("%lu: MAC Sending to 0%o via 0%o on pipe %x\n\r"),millis(),to_node,send_node,send_pipe));

  // First, stop listening so we can talk
  radio.stopListening();

  // Put the frame on the pipe
  ok = write_to_pipe( send_node, send_pipe );

      // NOT NEEDED anymore.  Now all reading pipes are open to start.
#if 0
  // If we are talking on our talking pipe, it's possible that no one is listening.
  // If this fails, try sending it on our parent's listening pipe.  That will wake
  // it up, and next time it will listen to us.

  if ( !ok && send_node == parent_node )
    ok = write_to_pipe( parent_node, 0 );
#endif

  // Now, continue listening
  radio.startListening();

  return ok;
}

/******************************************************************/

bool RF24Network::write_to_pipe( uint16_t node, uint8_t pipe )
{
  bool ok = false;

  uint64_t out_pipe = pipe_address( node, pipe );

  // Open the correct pipe for writing.
  radio.openWritingPipe(out_pipe);

  // Retry a few times
  short attempts = 5;
  do
  {
    ok = radio.write( frame_buffer, frame_size );
  }
  while ( !ok && --attempts );

  IF_SERIAL_DEBUG(printf_P(PSTR("%lu: MAC Sent on %lx %S\n\r"),millis(),(uint32_t)out_pipe,ok?PSTR("ok"):PSTR("failed")));

  return ok;
}

/******************************************************************/

const char* RF24NetworkHeader::toString(void) const
{
  static char buffer[45];
  snprintf(buffer,sizeof(buffer),"id %04x from 0%o to 0%o type %c",id,from_node,to_node,type);
  return buffer;
}

/******************************************************************/

bool RF24Network::is_direct_child( uint16_t node )
{
  bool result = false;

  // A direct child of ours has the same low numbers as us, and only
  // one higher number.
  //
  // e.g. node 0234 is a direct child of 034, and node 01234 is a
  // descendant but not a direct child

  // First, is it even a descendant?
  if ( is_descendant(node) )
  {
    // Does it only have ONE more level than us?
    uint16_t child_node_mask = ( ~ node_mask ) << 3;
    result = ( node & child_node_mask ) == 0 ;
  }

  return result;
}

/******************************************************************/

bool RF24Network::is_descendant( uint16_t node )
{
  return ( node & node_mask ) == node_address;
}

/******************************************************************/

void RF24Network::setup_address(void)
{
  // First, establish the node_mask
  uint16_t node_mask_check = 0xFFFF;
  while ( node_address & node_mask_check )
    node_mask_check <<= 3;

  node_mask = ~ node_mask_check;

  // parent mask is the next level down
  uint16_t parent_mask = node_mask >> 3;

  // parent node is the part IN the mask
  parent_node = node_address & parent_mask;

  // parent pipe is the part OUT of the mask
  uint16_t i = node_address;
  uint16_t m = parent_mask;
  while (m)
  {
    i >>= 3;
    m >>= 3;
  }
  parent_pipe = i;

#ifdef SERIAL_DEBUG
  printf_P(PSTR("setup_address node=0%o mask=0%o parent=0%o pipe=0%o\n\r"),node_address,node_mask,parent_node,parent_pipe);
#endif
}

/******************************************************************/

uint16_t RF24Network::direct_child_route_to( uint16_t node )
{
  // Presumes that this is in fact a child!!

  uint16_t child_mask = ( node_mask << 3 ) | 0B111;
  return node & child_mask ;
}

/******************************************************************/

uint8_t RF24Network::pipe_to_descendant( uint16_t node )
{
  uint16_t i = node;
  uint16_t m = node_mask;

  while (m)
  {
    i >>= 3;
    m >>= 3;
  }

  return i & 0B111;
}

/******************************************************************/

bool is_valid_address( uint16_t node )
{
  bool result = true;

  while(node)
  {
    uint8_t digit = node & 0B111;
    if (digit < 1 || digit > 5)
    {
      result = false;
      printf_P(PSTR("*** WARNING *** Invalid address 0%o\n\r"),node);
      break;
    }
    node >>= 3;
  }

  return result;
}

/******************************************************************/

uint64_t pipe_address( uint16_t node, uint8_t pipe )
{
  static uint8_t pipe_segment[] = { 0x3c, 0x5a, 0x69, 0x96, 0xa5, 0xc3 };

  uint64_t result;
  uint8_t* out = reinterpret_cast<uint8_t*>(&result);

  out[0] = pipe_segment[pipe];

  uint8_t w;
  short i = 4;
  short shift = 12;
  while(i--)
  {
    w = ( node >> shift ) & 0xF ;
    w |= ~w << 4;
    out[i+1] = w;

    shift -= 4;
  }

  IF_SERIAL_DEBUG(uint32_t* top = reinterpret_cast<uint32_t*>(out+1);printf_P(PSTR("%lu: NET Pipe %i on node 0%o has address %lx%x\n\r"),millis(),pipe,node,*top,*out));

  return result;
}

// vim:ai:cin:sts=2 sw=2 ft=cpp


text:
package com.nepxion.thunder.console.workspace;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;

import javax.swing.Box;
import javax.swing.JPanel;

import org.apache.commons.lang3.StringUtils;

import com.nepxion.swing.action.JSecurityAction;
import com.nepxion.swing.button.ButtonManager;
import com.nepxion.swing.button.JClassicButton;
import com.nepxion.swing.element.ElementNode;
import com.nepxion.swing.exception.ExceptionTracer;
import com.nepxion.swing.handle.HandleManager;
import com.nepxion.swing.layout.filed.FiledLayout;
import com.nepxion.swing.scrollpane.JBasicScrollPane;
import com.nepxion.swing.searchable.JSearchableContainer;
import com.nepxion.swing.searchable.JSearchableFactory;
import com.nepxion.swing.textarea.JBasicTextArea;
import com.nepxion.thunder.common.constant.ThunderConstant;
import com.nepxion.thunder.common.entity.ApplicationEntity;
import com.nepxion.thunder.console.controller.PropertyController;
import com.nepxion.thunder.console.icon.ConsoleIconFactory;
import com.nepxion.thunder.console.locale.ConsoleLocale;
import com.nepxion.thunder.console.workspace.common.ButtonSpace;
import com.nepxion.thunder.console.workspace.config.ConfigWorkspace;

public class RemoteConfigControlWorkspace extends ConfigWorkspace {
    private static final long serialVersionUID = 1L;

    private JPanel configContainer;
    private JBasicTextArea propertyTextArea;

    public RemoteConfigControlWorkspace() {
        super();
    }

    @Override
    protected ButtonSpace createButtonSpace() {
        ButtonSpace buttonSpace = super.createButtonSpace();

        JClassicButton savePropertyButton = new JClassicButton(createSavePropertyAction());

        buttonSpace.add(Box.createHorizontalStrut(5));
        buttonSpace.add(savePropertyButton);
        buttonSpace.updateLayout();

        return buttonSpace;
    }

    protected JSecurityAction createSavePropertyAction() {
        JSecurityAction action = new JSecurityAction(ButtonManager.getHtmlText(ConsoleLocale.getString("save_config_pane")), ConsoleIconFactory.getSwingIcon("stereo/control_go_24.png"), ConsoleLocale.getString("save_config_pane")) {
            private static final long serialVersionUID = 1L;

            public void execute(ActionEvent e) {
                if (propertyTextArea == null) {
                    return;
                }

                String property = propertyTextArea.getText();
                try {
                    PropertyController.modifyProperty(applicationEntity, property);
                } catch (Exception ex) {
                    ExceptionTracer.traceException(HandleManager.getFrame(RemoteConfigControlWorkspace.this), ConsoleLocale.getString("save_property_exception"), ex);
                }
            }
        };

        return action;
    }

    @Override
    protected JPanel createConfigContainer() {
        if (configContainer == null) {
            JPanel layoutPane = new JPanel();
            layoutPane.setLayout(new FiledLayout(FiledLayout.COLUMN, FiledLayout.FULL, 5));
            layoutPane.add(createTitleLabel());
            layoutPane.add(createSeparator());

            JSearchableContainer container = new JSearchableContainer();
            container.add(new JBasicScrollPane(createPropertyTextArea()));

            JSearchableFactory.installSearchableBar(propertyTextArea, container, true);

            configContainer = new JPanel();
            configContainer.setBorder(createTitledBorder(ConsoleLocale.getString("remote_config")));
            configContainer.setLayout(new BorderLayout());
            configContainer.add(layoutPane, BorderLayout.NORTH);
            configContainer.add(container, BorderLayout.CENTER);
        }

        return configContainer;
    }

    private JBasicTextArea createPropertyTextArea() {
        if (propertyTextArea == null) {
            propertyTextArea = new JBasicTextArea();
        }

        return propertyTextArea;
    }

    @Override
    protected String createCategory() {
        return ThunderConstant.CONFIGURATION_ELEMENT_NAME;
    }

    @Override
    protected void refreshConfigContainer() {
        loadConfig();
    }

    @Override
    protected void configTreeNodeSelection(ElementNode elementNode) {
        String application = elementNode.getText();
        String group = ((ElementNode) elementNode.getParent()).getText();

        applicationEntity = new ApplicationEntity();
        applicationEntity.setApplication(application);
        applicationEntity.setGroup(group);

        loadConfig();
    }

    private void loadConfig() {
        if (configContainer == null || configContainer.getParent() == null) {
            return;
        }

        String property = null;
        try {
            property = PropertyController.getProperty(applicationEntity);
        } catch (Exception e) {
            ExceptionTracer.traceException(HandleManager.getFrame(RemoteConfigControlWorkspace.this), ConsoleLocale.getString("load_property_exception"), e);
        }

        if (StringUtils.isNotEmpty(property)) {
            propertyTextArea.setText(property.trim());
            propertyTextArea.setCaretPosition(0);
        } else {
            propertyTextArea.setText(null);
        }
    }
}


text:
package com.twitter.sdk.android.core.internal.network;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;

import okhttp3.Interceptor;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;

@RunWith(RobolectricTestRunner.class)
public class GuestAuthNetworkInterceptorTest {
    static final String TEST_URL = "https://api.twitter.com";

    @Mock
    Interceptor.Chain mockChain;
    Request request;
    GuestAuthNetworkInterceptor interceptor;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);

        request = new Request.Builder().url(TEST_URL).build();
        interceptor = new GuestAuthNetworkInterceptor();
    }

    @Test
    public void testIntercept_with403() throws Exception {
        final Response response = new Response.Builder()
                .protocol(Protocol.HTTP_1_1)
                .request(request)
                .code(403)
                .message("Forbidden")
                .build();

        when(mockChain.request()).thenReturn(request);
        when(mockChain.proceed(request)).thenReturn(response);

        final Response modifiedResponse = interceptor.intercept(mockChain);

        assertFalse(response == modifiedResponse);
        assertEquals(401, modifiedResponse.code());
    }

    @Test
    public void testIntercept_with400() throws Exception {
        final Response response = new Response.Builder()
                .protocol(Protocol.HTTP_1_1)
                .request(request)
                .message("Bad Request")
                .code(400)
                .build();

        when(mockChain.request()).thenReturn(request);
        when(mockChain.proceed(request)).thenReturn(response);

        final Response unmodifiedResponse = interceptor.intercept(mockChain);

        assertTrue(response == unmodifiedResponse);
        assertEquals(400, unmodifiedResponse.code());
    }
}


text:
package com.bluemedora.api;

import com.bluemedora.exceptions.ExitException;
import com.vmware.ops.api.client.Client;
import com.vmware.ops.api.client.exceptions.AuthException;
import com.vmware.ops.api.model.common.PageInfo;
import com.vmware.ops.api.model.resource.ResourceDto;
import com.vmware.ops.api.model.resource.ResourceQuery;

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

public class SuiteApi
{
    public static void testApiConnectionInfo(ApiConnectionInfo apiConnectionInfo) throws ExitException
    {
        Client client = getClient(apiConnectionInfo.getHost(), apiConnectionInfo.getUsername(), apiConnectionInfo.getPassword());

        System.out.println("Testing vRealize Suite API connection...");

        try {
            client.resourcesClient().getResources(new ResourceQuery(), new PageInfo());
        } catch (AuthException e) {
            throw new ExitException("Invalid username or password.");
        } catch (Exception e) {
            throw new ExitException("Invalid hostname.");
        }

        System.out.println("\nConnection successful.\n");
    }

    private static Client getClient(String vRealizeHostname, String vRealizeAdminUser, String vRealizePassword)
    {
        return Client.ClientConfig.builder().basicAuth(vRealizeAdminUser, vRealizePassword).useJson()
                .serverUrl("https://" + vRealizeHostname + "/suite-api/")
                .verify("false")
                .ignoreHostName(true)
                .build()
                .newClient();
    }

    public static void deleteResource(ApiConnectionInfo apiConnectionInfo, ResourceDto resourceToDelete) throws ExitException
    {
        Client client = getClient(apiConnectionInfo.getHost(), apiConnectionInfo.getUsername(), apiConnectionInfo.getPassword());
        String resourceName = resourceToDelete.getResourceKey().getName();
        try {
            System.out.println("Attempting to trigger resource deletion for <" + resourceName + ">...");
            client.resourcesClient().deleteResource(resourceToDelete.getIdentifier());
            System.out.println("...Successfully triggered deletion of resource <" + resourceName + ">");
        } catch (AuthException e) {
            throw new ExitException("Invalid username or password.");
        } catch (Exception e) {
            throw new ExitException("Invalid resource.");
        }
    }

    public static List<ResourceDto> getMatchingResources(ApiConnectionInfo apiConnectionInfo, String resourceToDelete) throws ExitException
    {
        Client client = getClient(apiConnectionInfo.getHost(), apiConnectionInfo.getUsername(), apiConnectionInfo.getPassword());
        ResourceQuery nameQuery = new ResourceQuery();
        nameQuery.setName(new String[]{resourceToDelete});

        List<ResourceDto> matchingResources = client.resourcesClient().getResources(nameQuery, new PageInfo()).getResourceList();
        if (matchingResources == null || matchingResources.size() < 1) {
            throw new ExitException("No resource found with name <" + resourceToDelete + ">");
        }

        return matchingResources;
    }

    public static void recursivelyDeleteDescendants(ApiConnectionInfo apiConnectionInfo, ResourceDto resourceDtoToDelete) throws ExitException
    {
        Client client = getClient(apiConnectionInfo.getHost(), apiConnectionInfo.getUsername(), apiConnectionInfo.getPassword());

        PageInfo pageInfo = new PageInfo(0, 5000, 5000);
        ResourceDto.ResourceRelationDto resourceDtoToDeleteDescendants;
        List<ResourceDto> children = new ArrayList<ResourceDto>();
        do {

            resourceDtoToDeleteDescendants = client.resourcesClient().getChildren(resourceDtoToDelete.getIdentifier(), pageInfo);
            children.addAll(resourceDtoToDeleteDescendants.getResourceList());
            pageInfo.setPage(pageInfo.getPage() + 1);
        } while (resourceDtoToDeleteDescendants.getResourceList().size() == 5000);

        for (ResourceDto child : children) {
            recursivelyDeleteDescendants(apiConnectionInfo, child);
        }

        deleteResource(apiConnectionInfo, resourceDtoToDelete);
    }
}


text:
package mboxparser

import (
	"testing"
)

func TestHeader(t *testing.T) {
	header := make(Header)

	testHeader := "qwertyuiop"
	header.Set("x-mBox-header", testHeader)

	retval := header.Get("x-mbox-HeadeR")
	if retval != testHeader {
		t.Fatalf("Header Set/Get is invalid %s(expected: %s)", retval, testHeader)
	}

	header.Del("x-MBOX-HeadeR")

	retval = header.Get("x-mbox-HeadeR")
	if retval != "" {
		t.Fatalf("Header Set/Get is invalid %s(expected: %s)", retval, "")
	}
}


text:
package com.intellij.uiDesigner.compiler;

import com.intellij.uiDesigner.lw.LwComponent;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.commons.GeneratorAdapter;
import org.jetbrains.org.objectweb.asm.commons.Method;

import javax.swing.*;

public class ScrollPaneLayoutCodeGenerator extends LayoutCodeGenerator {
  private final Type myScrollPaneType = Type.getType(JScrollPane.class);
  private final Method mySetViewportViewMethod = Method.getMethod("void setViewportView(java.awt.Component)");

  @Override
  public void generateComponentLayout(final LwComponent lwComponent,
                                      final GeneratorAdapter generator,
                                      final int componentLocal,
                                      final int parentLocal,
                                      final String formClassName) {
    generator.loadLocal(parentLocal);
    generator.loadLocal(componentLocal);
    generator.invokeVirtual(myScrollPaneType, mySetViewportViewMethod);
  }
}


text:
<?php declare(strict_types=1);

namespace Room11\Jeeves\Plugins;

// interface does not have option constants :-(
use Amp\Artax\Client as HttpClient;
use Amp\Artax\Request as HttpRequest;
use Amp\Artax\Response as HttpResponse;
use Amp\Promise;
use Room11\Jeeves\Chat\Command;
use Room11\Jeeves\System\PluginCommandEndpoint;
use Room11\StackChat\Client\Client as ChatClient;
use function Amp\resolve;

class HttpRequester extends BasePlugin
{
    private const FLAGS = ['chrome', 'firefox', 'googlebot', 'nofollow'];

    private const USER_AGENTS = [
        'chrome'    => 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
        'firefox'   => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1',
        'googlebot' => 'Googlebot/2.1 (+http://www.googlebot.com/bot.html)',
    ];

    private $chatClient;

    private $httpClient;

    public function __construct(ChatClient $chatClient, HttpClient $httpClient)
    {
        $this->chatClient = $chatClient;
        $this->httpClient = $httpClient;
    }

    private function getResult(HttpRequest $request, Command $command)
    {
        try {
            /** @var HttpResponse $response */
            $response = yield $this->httpClient->request($request, $this->getClientOptions($command));

            return $this->chatClient->postMessage($command, $this->formatResult($response));
        } catch (\Throwable $e) {
            return $this->chatClient->postMessage($command, $e->getMessage());
        }
    }

    private function getClientOptions(Command $command)
    {
        $options = [];

        foreach($command->getParameters() as $parameter) {
            if (!in_array($parameter, self::FLAGS, true)) {
                continue;
            }

            if ($parameter === 'nofollow') {
                $options[HttpClient::OP_FOLLOW_LOCATION] = false;
                continue;
            }

            $options[HttpClient::OP_DEFAULT_USER_AGENT] = self::USER_AGENTS[$parameter];
        }

        return $options;
    }

    private function getRequestUrl(Command $command): string
    {
        $parameters = $command->getParameters();

        return end($parameters);
    }

    private function getPostBody(Command $command): string
    {
        $parameters = $command->getParameters();

        if (count($parameters) < 2) {
            throw new \RuntimeException('Usage: `!!post [options] postdata url`');
        }

        return $parameters[count($parameters) - 2];
    }

    private function formatResult(HttpResponse $response): string
    {
        $lines = [
            sprintf('%s %s', $this->getProtocol($response), $this->getStatus($response)),
        ];

        $lines = array_merge($lines, array_map(function ($key, $value) {
            return sprintf("%s: %s", $key, implode(';', $value));
        }, array_keys($response->getAllHeaders()), $response->getAllHeaders()));

        return sprintf('    %s', implode("\r\n    ", $lines));
    }

    private function getProtocol(HttpResponse $response): string
    {
        return 'HTTP/' . $response->getProtocol();
    }

    private function getStatus(HttpResponse $response): string
    {
        return sprintf('%s %s', $response->getStatus(), $response->getReason());
    }

    public function get(Command $command): Promise
    {
        $request = (new HttpRequest)
            ->setUri($this->getRequestUrl($command));

        return resolve($this->getResult($request, $command));
    }

    public function post(Command $command): Promise
    {
        $request = (new HttpRequest)
            ->setMethod('POST')
            ->setUri($this->getRequestUrl($command))
            ->setBody($this->getPostBody($command));

        return resolve($this->getResult($request, $command));
    }

    public function head(Command $command): Promise
    {
        $request = (new HttpRequest)
            ->setMethod('HEAD')
            ->setUri($this->getRequestUrl($command));

        return resolve($this->getResult($request, $command));
    }

    public function getDescription(): string
    {
        return 'Sends HTTP requests and displays the headers of the response';
    }

    /**
     * @return PluginCommandEndpoint[]
     */
    public function getCommandEndpoints(): array
    {
        return [
            new PluginCommandEndpoint('GET', [$this, 'get'], 'get', 'Sends HTTP GET request and displays the headers of the response'),
            new PluginCommandEndpoint('POST', [$this, 'post'], 'post', 'Sends HTTP POST request and displays the headers of the response'),
            new PluginCommandEndpoint('HEAD', [$this, 'head'], 'head', 'Sends HTTP HEAD request and displays the headers of the response'),
        ];
    }
}


text:
namespace Sass {
	using namespace std;

  struct Backtrace;

  struct Error {
    enum Type { read, write, syntax, evaluation };

    Type type;
    string path;
    size_t line;
    string message;

    Error(Type type, string path, size_t line, string message);

  };

  void error(string msg, string path, size_t line);
  void error(string msg, string path, size_t line, Backtrace* bt);

}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.16 at 03:24:22 PM EEST
//

package org.ecloudmanager.tmrk.cloudapi.model;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for VirtualMachineReferenceType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="VirtualMachineReferenceType">
 *   <complexContent>
 *     <extension base="{}ReferenceType">
 *       <sequence>
 *         <element name="Status" type="{}VirtualMachineStatus" minOccurs="0"/>
 *         <element name="ProcessorCount" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="Memory" type="{}ResourceUnitType" minOccurs="0"/>
 *         <element name="Storage" type="{}ResourceUnitType" minOccurs="0"/>
 *         <element name="OperatingSystem" type="{}ReferenceType" minOccurs="0"/>
 *         <element name="PoweredOn" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *         <element name="ToolsStatus" type="{}ToolsStatus" minOccurs="0"/>
 *         <element name="Nics" type="{}NicsType" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VirtualMachineReferenceType", propOrder = {
    "status",
    "processorCount",
    "memory",
    "storage",
    "operatingSystem",
    "poweredOn",
    "toolsStatus",
    "nics"
})
public class VirtualMachineReferenceType
    extends ReferenceType
{

    /**
     *
     */
    private static final long serialVersionUID = -95815330292074922L;
    @XmlElementRef(name = "Status", type = JAXBElement.class, required = false)
    protected JAXBElement<VirtualMachineStatus> status;
    @XmlElementRef(name = "ProcessorCount", type = JAXBElement.class, required = false)
    protected JAXBElement<Integer> processorCount;
    @XmlElementRef(name = "Memory", type = JAXBElement.class, required = false)
    protected JAXBElement<ResourceUnitType> memory;
    @XmlElementRef(name = "Storage", type = JAXBElement.class, required = false)
    protected JAXBElement<ResourceUnitType> storage;
    @XmlElementRef(name = "OperatingSystem", type = JAXBElement.class, required = false)
    protected JAXBElement<ReferenceType> operatingSystem;
    @XmlElementRef(name = "PoweredOn", type = JAXBElement.class, required = false)
    protected JAXBElement<Boolean> poweredOn;
    @XmlElementRef(name = "ToolsStatus", type = JAXBElement.class, required = false)
    protected JAXBElement<ToolsStatus> toolsStatus;
    @XmlElementRef(name = "Nics", type = JAXBElement.class, required = false)
    protected JAXBElement<NicsType> nics;

    /**
     * Gets the value of the status property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link VirtualMachineStatus }{@code >}
     *
     */
    public JAXBElement<VirtualMachineStatus> getStatus() {
        return status;
    }

    /**
     * Sets the value of the status property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link VirtualMachineStatus }{@code >}
     *
     */
    public void setStatus(JAXBElement<VirtualMachineStatus> value) {
        this.status = value;
    }

    /**
     * Gets the value of the processorCount property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link Integer }{@code >}
     *
     */
    public JAXBElement<Integer> getProcessorCount() {
        return processorCount;
    }

    /**
     * Sets the value of the processorCount property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link Integer }{@code >}
     *
     */
    public void setProcessorCount(JAXBElement<Integer> value) {
        this.processorCount = value;
    }

    /**
     * Gets the value of the memory property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link ResourceUnitType }{@code >}
     *
     */
    public JAXBElement<ResourceUnitType> getMemory() {
        return memory;
    }

    /**
     * Sets the value of the memory property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link ResourceUnitType }{@code >}
     *
     */
    public void setMemory(JAXBElement<ResourceUnitType> value) {
        this.memory = value;
    }

    /**
     * Gets the value of the storage property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link ResourceUnitType }{@code >}
     *
     */
    public JAXBElement<ResourceUnitType> getStorage() {
        return storage;
    }

    /**
     * Sets the value of the storage property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link ResourceUnitType }{@code >}
     *
     */
    public void setStorage(JAXBElement<ResourceUnitType> value) {
        this.storage = value;
    }

    /**
     * Gets the value of the operatingSystem property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link ReferenceType }{@code >}
     *
     */
    public JAXBElement<ReferenceType> getOperatingSystem() {
        return operatingSystem;
    }

    /**
     * Sets the value of the operatingSystem property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link ReferenceType }{@code >}
     *
     */
    public void setOperatingSystem(JAXBElement<ReferenceType> value) {
        this.operatingSystem = value;
    }

    /**
     * Gets the value of the poweredOn property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link Boolean }{@code >}
     *
     */
    public JAXBElement<Boolean> getPoweredOn() {
        return poweredOn;
    }

    /**
     * Sets the value of the poweredOn property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link Boolean }{@code >}
     *
     */
    public void setPoweredOn(JAXBElement<Boolean> value) {
        this.poweredOn = value;
    }

    /**
     * Gets the value of the toolsStatus property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link ToolsStatus }{@code >}
     *
     */
    public JAXBElement<ToolsStatus> getToolsStatus() {
        return toolsStatus;
    }

    /**
     * Sets the value of the toolsStatus property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link ToolsStatus }{@code >}
     *
     */
    public void setToolsStatus(JAXBElement<ToolsStatus> value) {
        this.toolsStatus = value;
    }

    /**
     * Gets the value of the nics property.
     *
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link NicsType }{@code >}
     *
     */
    public JAXBElement<NicsType> getNics() {
        return nics;
    }

    /**
     * Sets the value of the nics property.
     *
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link NicsType }{@code >}
     *
     */
    public void setNics(JAXBElement<NicsType> value) {
        this.nics = value;
    }

}


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>
Uses of Package net.sf.extjwnl.dictionary.file (extJWNL 1.6.2 API)
</TITLE>

<META NAME="date" CONTENT="2011-09-26">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
net.sf.extjwnl.dictionary.file

Packages that use net.sf.extjwnl.dictionary.file

net.sf.extjwnl.dictionary
Classes for accessing dictionary information.

net.sf.extjwnl.dictionary.file
Classes for accessing files that contain dictionary information.

net.sf.extjwnl.dictionary.file_manager
Classes used by FileBackedDictionary to interface with the filesystem.

net.sf.extjwnl.princeton.file
Implementations of DictionaryFile used by the various classes of Dictionary to access
dictionary files using the naming convention used in Princeton's release of WordNet.

Classes in net.sf.extjwnl.dictionary.file used by net.sf.extjwnl.dictionary

DictionaryFileType

          Enumerates different types of dictionary files.

Classes in net.sf.extjwnl.dictionary.file used by net.sf.extjwnl.dictionary.file

DictionaryCatalog

          A container for the files associated with a catalog (the index, data, and exception
 files associated with a POS).

DictionaryFile

          Represents a single dictionary file.

DictionaryFileType

          Enumerates different types of dictionary files.

Classes in net.sf.extjwnl.dictionary.file used by net.sf.extjwnl.dictionary.file_manager

DictionaryFileType

          Enumerates different types of dictionary files.

RandomAccessDictionaryFile

          DictionaryFile that reads lines from a random-access text file.

Classes in net.sf.extjwnl.dictionary.file used by net.sf.extjwnl.princeton.file

AbstractDictionaryFile

          Abstract implementation of DictionaryFile.

DictionaryFile

          Represents a single dictionary file.

DictionaryFileFactory

          A dictionary file factory.

DictionaryFileType

          Enumerates different types of dictionary files.

ObjectDictionaryFile

          DictionaryFile that reads and writes serialized objects.

RandomAccessDictionaryFile

          DictionaryFile that reads lines from a random-access text file.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2011. All Rights Reserved.


text:
package org.jetbrains.jps.incremental.artifacts.instructions;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;

public class CopyToDirectoryInstructionCreator extends ArtifactCompilerInstructionCreatorBase {
  private final String myOutputPath;

  public CopyToDirectoryInstructionCreator(ArtifactInstructionsBuilderImpl builder, String outputPath) {
    super(builder);
    myOutputPath = outputPath;
  }

  @Override
  protected DestinationInfo createFileDestination(@NotNull String outputFileName) {
    return new ExplodedDestinationInfo(myOutputPath + "/" + outputFileName);
  }

  @Override
  protected ExplodedDestinationInfo createDirectoryDestination() {
    return new ExplodedDestinationInfo(myOutputPath);
  }

  @Override
  protected void onAdded(ArtifactRootDescriptor descriptor) {
  }

  @Override
  public CopyToDirectoryInstructionCreator subFolder(@NotNull String directoryName) {
    return new CopyToDirectoryInstructionCreator(myInstructionsBuilder, myOutputPath + "/" + directoryName);
  }

  @Override
  public ArtifactCompilerInstructionCreator archive(@NotNull String archiveFileName) {
    String jarOutputPath = myOutputPath + "/" + archiveFileName;
    final ExplodedDestinationInfo destination = new ExplodedDestinationInfo(jarOutputPath);
    final JarInfo jarInfo = new JarInfo(destination);
    if (!myInstructionsBuilder.registerJarFile(jarInfo, jarOutputPath)) {
      return new SkipAllInstructionCreator(myInstructionsBuilder);
    }
    return new PackIntoArchiveInstructionCreator(myInstructionsBuilder, jarInfo, "", destination);
  }

  @Nullable
  @Override
  public File getTargetDirectory() {
    return new File(myOutputPath);
  }
}


text:
/*
	Port.cpp
	(c)2005 Palestar, Richard Lyle
*/

#define INTERFACECONTEXTPORT_DLL
#include "stdafx.h"

#include "Port.h"
#include "PortView.h"
#include "ChildFrame.h"
#include "Resource.h"

#include "Gui3d/InterfaceContext.h"

//----------------------------------------------------------------------------

IMPLEMENT_FACTORY( InterfaceContextPort, Port );
REGISTER_FACTORY_KEY(  InterfaceContextPort, 3979389470128564958 );

BEGIN_PROPERTY_LIST( InterfaceContextPort, Port );
	ADD_CLASSKEY_PROPERTY( m_DocumentClass, Document );
	ADD_PROPERTY( m_StartingScene );
	ADD_PROPERTY( m_SceneId );
	ADD_PROPERTY( m_Scenes );
	ADD_PROPERTY( m_Style );
	ADD_PROPERTY( m_Cursor );
END_PROPERTY_LIST();

InterfaceContextPort::InterfaceContextPort() : Port()
{
	m_StartingScene = 0;
	m_DocumentClass = CLASS_KEY( Document );
}

//-------------------------------------------------------------------------------

const int VERSION_051299 = 1;
const int VERSION_102599 = 102599;
const int VERSION_031300 = 31300;

bool InterfaceContextPort::read( const InStream & input )
{
	if (! Port::read( input ) )
	{
		int version;
		input >> version;

		switch( version )
		{
		case VERSION_031300:
			input >> m_DocumentClass;
			input >> m_StartingScene;
			input >> m_SceneId;
			input >> m_Scenes;
			input >> m_Style;
			input >> m_Cursor;
			return true;
		case VERSION_102599:
			input >> m_DocumentClass;
			input >> m_StartingScene;
			input >> m_SceneId;
			input >> m_Scenes;
			return true;
		case VERSION_051299:
			input >> m_StartingScene;
			input >> m_SceneId;
			input >> m_Scenes;
			m_DocumentClass = CLASS_KEY( Document );
			return true;
		}

		return false;
	}

	return true;
}

//----------------------------------------------------------------------------

void InterfaceContextPort::dependencies( DependentArray & dep )
{
	Port::dependencies( dep );

	for(int i=0;i<m_Scenes.size();i++)
		dep.push( m_Scenes[i] );

	dep.push( m_Style );
	dep.push( m_Cursor );
}

Resource::Ref InterfaceContextPort::createResource()
{
	InterfaceContext * pInterface = new InterfaceContext;
	ASSERT( pInterface );

	pInterface->setDocumentClass( m_DocumentClass );
	pInterface->setWindowStyle( WindowStyle::Link( portResource( m_Style ) ) );
	pInterface->setCursor( Material::Link( Port::portResource( m_Cursor ) ) );

	for(int i=0;i<m_Scenes.size();i++)
	{
		if (! pInterface->addScene( m_SceneId[i], Scene::Link( portResource( m_Scenes[i] ) ),
			m_StartingScene == i ? true : false ) )
		{
			report( CharString().format("Failed to add scene %s", (const char *)m_Scenes[i]) );
		}
	}

	return pInterface;
}

CFrameWnd * InterfaceContextPort::createView()
{
	static CMultiDocTemplate docTemplate( IDR_PORT, NULL,
		RUNTIME_CLASS(CChildFrame), RUNTIME_CLASS(CPortView) );

    CChildFrame *pFrame = dynamic_cast<CChildFrame *>( docTemplate.CreateNewFrame( this, NULL ) );
	ASSERT( pFrame );

	docTemplate.InitialUpdateFrame(pFrame, this);

	return( pFrame );
}

bool InterfaceContextPort::importFile( const char * fileName )
{
	return true;	// return true of successful import, false on failure
}

void InterfaceContextPort::shellOpen() const
{
	MessageBox( NULL, _T("shellOpen() is not valid for this port"), NULL, MB_OK);
}

//-------------------------------------------------------------------------------
// EOF


text:
/* You can add styles that are specific to your story here, based on class names that you assigned using the ClassName component. */

.Storyline__Item--opening p:first-child:first-letter {
  font-size: 200%;
}

.GamePage--cottage .Current-location {
  background-color: #cc9857;
}

.GamePage--river .Current-location {
  background-color: #7abde4;
}

.GamePage--woods .Current-location {
  background-color: #325016;
}

.GamePage--grandmasHouse .Current-location {
  background-color: #613f0c;
}


text:
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using SerializationUtilities.SerializationGraph;
using Utilities.Json;

namespace SerializationUtilities
{
	public class JSONSerializer : BaseSerializer
	{
		private const string TYPES_FIELD = "types";
		private const string ROOT_FIELD = "root";
		private const string REFERENCES_FIELD = "references";

		public enum EnumRepresentationMode : byte
		{
			Explicit,
			Numeric
		}

		public bool AllowIdentation = true;
		public EnumRepresentationMode EnumRepresentation = EnumRepresentationMode.Explicit;

		public JSONSerializer()
		{
			FormatSelector.AddFormatter(typeof(Enum), true, new EnumGraphFormatter { parent = this });
			FormatSelector.AddFormatter(typeof(DateTime),false, new DateTimeFormatter());
			FormatSelector.AddFormatter(typeof(Guid),false,new GUIDFormatter());
		}

		#region Serialization

		public JsonObject SerializeToJson(object graph)
		{
			Graph serGraph = ComputeGraph(graph);
			return ToJson(serGraph);
		}

		protected override void SerializeDataGraph(Stream serializationStream, Graph graph)
		{
			JsonObject json = ToJson(graph);

			var w = new StreamWriter(serializationStream);
			json.Write(w, 0, AllowIdentation);
			w.Flush();
		}

		private JsonObject ToJson(Graph graph)
		{
			JsonObject json = new JsonObject();

			//Collect types
			var types = CollectAssemblyData(graph);

			json[ROOT_FIELD] = ToJson(graph.Root);

			var nodes = graph.GetReferences().Select(NodeToJson).Cast<JsonToken>();
			if (nodes.Any())
				json[REFERENCES_FIELD] = new JsonArray(nodes);

			json[TYPES_FIELD] = types;

			return json;
		}

		private JsonToken CollectAssemblyData(Graph graph)
		{
			var array = new JsonArray();
			foreach (var typeEntry in graph.GetRegistedTypes())
			{
				var entry = new JsonObject();
				entry["TypeId"] = new JsonNumber(typeEntry.TypeId);
				entry["ClassName"] = new JsonString(typeEntry.ClassType.AssemblyQualifiedName);
				array.Add(entry);
			}
			return array;
		}

		private JsonToken ToJson(IGraphNode node)
		{
			if (node == null)
				return null;

			switch (node.DataType)
			{
				case SerializedDataType.Boolean:
					return new JsonBool((bool)((IPrimitiveGraphNode)node).Value);
				case SerializedDataType.Number:
					return new JsonNumber((node as IPrimitiveGraphNode).Value);
				case SerializedDataType.String:
					return new JsonString((node as IStringGraphNode).Value);
				case SerializedDataType.DataSequence:
					return new JsonArray((node as ISequenceGraphNode).Select(n => ToJson(n)));
				case SerializedDataType.Type:
					return new JsonString("class@"+(node as ITypeGraphNode).TypeId);
			}

			IObjectGraphNode objNode = node as IObjectGraphNode;
			if (objNode.IsReferedMultipleTimes)
			{
				return new JsonString("refId@" + objNode.RefId.ToString());
			}

			return NodeToJson(objNode);
		}

		private JsonObject NodeToJson(IObjectGraphNode node)
		{
			JsonObject json = new JsonObject();

			if (node.IsReferedMultipleTimes)
			{
				if (node.RefId >= 0)
					json["refId"] = new JsonNumber(node.RefId);
			}

			if (node.ObjectType != null)
			{
				json["classId"] = new JsonNumber(node.ObjectType.TypeId);
			}

			using (var it = node.GetEnumerator())
			{
				while (it.MoveNext())
				{
					json[it.Current.FieldName] = ToJson(it.Current.FieldNode);
				}
			}

			return json;
		}

		#endregion

		#region Deserialization

		public T DeserializeFromJson<T>(JsonObject json)
		{
			return (T)DeserializeFromJson(json, typeof(T));
		}

		public object DeserializeFromJson(JsonObject json, Type returnType)
		{

			if (!json.ContainsField(ROOT_FIELD))
			{
				var baseJson = new JsonObject();
				baseJson[ROOT_FIELD] = json;
				json = baseJson;
			}

			var graph = new Graph(FormatSelector, Context);
			if (!json.ContainsField(TYPES_FIELD))
			{
				var obj = (JsonObject) json[ROOT_FIELD];
				if (obj.ContainsField("classId"))
					graph.RegistTypeEntry(returnType, (byte)((JsonNumber)obj["classId"]).Value);
			}

			DeserializeDataGraphFromJson(json,graph);
			return graph.DeserializeObject(returnType);
		}

		protected override void DeserializeDataGraph(Stream serializationStream, Graph serGraph)
		{
			JsonObject json = JsonParser.Parse(serializationStream) as JsonObject;
			if (json == null)
				throw new Exception("Unable to deserialize"); //TODO get a better exception

			DeserializeDataGraphFromJson(json,serGraph);
		}

		private void DeserializeDataGraphFromJson(JsonObject json, Graph serGraph)
		{
			if (json == null)
				throw new Exception("Unable to deserialize"); //TODO get a better exception

			if (json.ContainsField(TYPES_FIELD))
			{
				JsonArray types = json[TYPES_FIELD] as JsonArray;
				foreach (var t in types)
				{
					var typeEntry = t as JsonObject;
					if (typeEntry == null)
						throw new Exception("Unable to deserialize"); //TODO get a better exception

					byte typeId = (byte)(typeEntry["TypeId"] as JsonNumber);

					Type loadedType = Type.GetType((typeEntry["ClassName"] as JsonString).String);
					serGraph.RegistTypeEntry(loadedType, typeId);
				}
			}

			if (json.ContainsField(REFERENCES_FIELD))
			{
				JsonArray refs = json[REFERENCES_FIELD] as JsonArray;
				foreach (var e in refs)
				{
					var refEntry = e as JsonObject;
					if (refEntry == null)
						throw new Exception("Unable to deserialize"); //TODO get a better exception

					JsonToObjectNode(refEntry, serGraph);
				}
			}

			serGraph.Root = ReadNode(json[ROOT_FIELD] as JsonToken, serGraph);
		}

		private IObjectGraphNode JsonToObjectNode(JsonObject json, Graph parentGraph)
		{
			IObjectGraphNode node;

			if(json.ContainsField("refId"))
			{
				node = parentGraph.GetObjectDataForRefId((int)(json["refId"] as JsonNumber));
			}
			else
				node = parentGraph.CreateObjectData();

			foreach (var field in json)
			{
				if (field.Key == "refId")
					continue;

				if (field.Key == "classId")
				{
					var id = (byte)(field.Value as JsonNumber);
					node.ObjectType = parentGraph.GetTypeEntry(id);
				}
				else
				{

					node[field.Key] = ReadNode(field.Value, parentGraph);
				}
			}

			return node;
		}

		private IGraphNode ReadNode(JsonToken json, Graph parentGraph)
		{
			if (json == null)
				return null;

			if (json is JsonString)
			{
				string val = ((JsonString)json).String;
				if (val.StartsWith("refId@"))
				{
					int id = int.Parse(val.Substring(6));
					return parentGraph.GetObjectDataForRefId(id);
				}

				if (val.StartsWith("class@"))
				{
					byte id = byte.Parse(val.Substring(6));
					return parentGraph.GetTypeEntry(id);
				}

				return parentGraph.BuildStringNode(val);
			}

			if (json is JsonNumber)
				return parentGraph.BuildPrimitiveNode((json as JsonNumber).Value);

			if (json is JsonBool)
				return parentGraph.BuildPrimitiveNode((json as JsonBool).Value);

			if (json is JsonArray)
			{
				ISequenceGraphNode node = parentGraph.BuildSequenceNode();
				foreach (JsonToken t in ((JsonArray)json))
				{
					var elem = ReadNode(t, parentGraph);
					node.Add(elem);
				}
				return node;
			}

			return JsonToObjectNode(json as JsonObject, parentGraph);
		}

		#endregion

		private class EnumGraphFormatter : IGraphFormatter
		{
			public JSONSerializer parent;

			public IGraphNode ObjectToGraphNode(object value, Graph serializationGraph)
			{
				Enum enumValue = (Enum)value;
				if (parent.EnumRepresentation == EnumRepresentationMode.Numeric)
					return serializationGraph.BuildPrimitiveNode((ValueType)Convert.ChangeType(enumValue, enumValue.GetType()));
				return serializationGraph.BuildStringNode(enumValue.ToString().Replace(", ", "|"));
			}

			public object GraphNodeToObject(IGraphNode node, Type objectType)
			{
				if (node.DataType == SerializedDataType.Number)
					return Convert.ChangeType((node as IPrimitiveGraphNode).Value, objectType);
				if (node.DataType != SerializedDataType.String)
					throw new Exception("invalid enum type");	//TODO better exception

				var str = (node as IStringGraphNode).Value;
				str = str.Replace("|", ",");
				return Enum.Parse(objectType, str, true);
			}
		}

		private class DateTimeFormatter : IGraphFormatter
		{
			private static readonly string[] TIME_FORMATS = {
				@"d/M/yyyy@H:m:s.fffffff",
				@"d/M/yyyy@H:m:s",
				@"d/M/yyyy@H:m",
				@"d/M/yyyy",
			};

			public IGraphNode ObjectToGraphNode(object value, Graph serializationGraph)
			{
				DateTime time = (DateTime) value;
				time = time.ToUniversalTime();
				string format = @"d/M/yyyy";
				if (time.Hour > 0 || time.Minute > 0 || time.Second > 0 || time.Millisecond > 0)
				{
					format += @"@H:m";
					if (time.Second > 0 || time.Millisecond > 0)
					{
						format += @":s";
						if (time.Millisecond > 0)
							format += @".fffffff";
					}
				}
				string timestamp = time.ToString(format);
				return serializationGraph.BuildStringNode(timestamp);
			}

			public object GraphNodeToObject(IGraphNode node, Type objectType)
			{
				var timestamp = (IStringGraphNode) node;
				DateTime t = DateTime.ParseExact(timestamp.Value, TIME_FORMATS, null, DateTimeStyles.None);
				return DateTime.SpecifyKind(t, DateTimeKind.Utc);
			}
		}

		private class GUIDFormatter: IGraphFormatter
		{
			public IGraphNode ObjectToGraphNode(object value, Graph serializationGraph)
			{
				return serializationGraph.BuildStringNode(((Guid) value).ToString("D"));
			}

			public object GraphNodeToObject(IGraphNode node, Type objectType)
			{
				var str = ((IStringGraphNode) node).Value;
				return new Guid(str);
			}
		}
	}
}


text:
var convert = require('./convert'),
    func = convert('defaultsAll', require('../defaults'));

func.placeholder = require('./placeholder');
module.exports = func;


text:
import { join } from 'node:path';
import merge from 'lodash.merge';
import intel from 'intel';
import defaultConfig from './defaults.js';
import {
  savePngWithoutResize,
  savePng,
  saveJpg
} from '../support/images/index.js';
const SCREENSHOT_DIR = 'screenshots';
const log = intel.getLogger('browsertime.screenshot');
class ScreenshotManager {
  constructor(storageManager, options) {
    this.storageManager = storageManager;
    this.config = merge({}, defaultConfig, options.screenshotParams);
    this.options = options;
    this.savedScreenshots = [];
  }

  async save(name, data, url, index) {
    let jimp;
    try {
      jimp = await import('jimp');
    } catch {
      jimp = undefined;
    }

    if (!jimp) {
      if (this.config.type === 'jpg') {
        log.info(
          'Missing sharp dependency so you can only save images as png at viewport size'
        );
      }
      const pathAndName = await savePngWithoutResize(
        name,
        data,
        url,
        this.storageManager,
        join(SCREENSHOT_DIR, `${index}`),
        this.options
      );
      this.savedScreenshots.push(
        pathAndName.replace(this.storageManager.directory + '/', '')
      );
    }
    if (this.config.type === 'png') {
      const pathAndName = await savePng(
        name,
        data,
        url,
        this.storageManager,
        this.config,
        join(SCREENSHOT_DIR, `${index}`),
        this.options
      );
      this.savedScreenshots.push(
        pathAndName.replace(this.storageManager.directory + '/', '')
      );
    } else {
      const pathAndName = await saveJpg(
        name,
        data,
        url,
        this.storageManager,
        this.config,
        join(SCREENSHOT_DIR, `${index}`),
        this.options
      );
      this.savedScreenshots.push(
        pathAndName.replace(this.storageManager.directory + '/', '')
      );
    }
  }

  getSaved() {
    return this.savedScreenshots;
  }
}

export default ScreenshotManager;


text:
<!DOCTYPE HTML>

<title>Home</title>

<link href="{{ asset('/home1/css/bootstrap.css') }}" rel='stylesheet' type='text/css' />
<link rel="stylesheet" type="text/css" href="{{ asset('/home1/css/shoplist.css') }}">
<link href="{{ asset('/css/font-awesome/css/font-awesome.min.css') }}" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="{{ asset('/upAvatar/head/cropper.min.css') }}">
<link href="{{ asset('/upAvatar/head/sitelogo.css') }}" rel="stylesheet">

<link type="text/css" href="{{ asset('/css/forget.css') }}" rel="stylesheet" />

<link href="{{ asset('/css/iCheck/skins/flat/green.css') }}" rel="stylesheet">

<link href="{{ asset('/home1/css/style.css') }}" rel='stylesheet' type='text/css' />
<link href="{{ asset('/home1/css/cost.css') }}" rel='stylesheet' type='text/css' />
<link rel="stylesheet" type="text/css" href="{{ asset('/iCheck/skins/flat/grey.css') }}">

<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">

</script>

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

    @yield('content')

关于

关于我们

广告合作

友情链接

招聘

联系方式

新浪微博

电子邮件

旗下网站

Laravel中文网

Ghost中国

赞助商

又拍云

京ICP备11008151号

京公网安备11010802014853

    @yield('js')


text:
title: "A Plan for Microsoft SQL Server"
date: 2018-01-03
author: Matt Wrock
tags: windows, packaging
category: windows
classes: body-article
---

This content has moved to the Chef blog!

Click Here!


text:
class Avatar < ActiveRecord::Base
  include DynamicImage::Model
  has_one :user
end


text:
package org.springframework.cloud.sleuth.instrument.zuul;

import org.apache.http.Header;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Tracer;

import static org.assertj.core.api.BDDAssertions.then;

/**
 * @author Marcin Grzejszczak
 */
@RunWith(MockitoJUnitRunner.class)
public class ApacheHttpClientRibbonRequestCustomizerTests {

	@Mock Tracer tracer;
	@InjectMocks ApacheHttpClientRibbonRequestCustomizer customizer;
	Span span = Span.builder().name("name").spanId(1L).traceId(2L).parent(3L)
			.processId("processId").build();

	@Test
	public void should_accept_customizer_when_apache_http_client_is_passed() throws Exception {
		then(this.customizer.accepts(String.class)).isFalse();
		then(this.customizer.accepts(RequestBuilder.class)).isTrue();
	}

	@Test
	public void should_set_not_sampled_on_the_context_when_there_is_no_span() throws Exception {
		RequestBuilder requestBuilder = RequestBuilder.create("GET");

		this.customizer.inject(null, this.customizer.toSpanTextMap(requestBuilder));

		HttpUriRequest request = requestBuilder.build();
		Header header = request.getFirstHeader(Span.SAMPLED_NAME);
		then(header.getName()).isEqualTo(Span.SAMPLED_NAME);
		then(header.getValue()).isEqualTo(Span.SPAN_NOT_SAMPLED);
	}

	@Test
	public void should_set_tracing_headers_on_the_context_when_there_is_a_span() throws Exception {
		RequestBuilder requestBuilder = RequestBuilder.create("GET");

		this.customizer.inject(this.span, this.customizer.toSpanTextMap(requestBuilder));

		HttpUriRequest request = requestBuilder.build();
		thenThereIsAHeaderWithNameAndValue(request, Span.SPAN_ID_NAME, "0000000000000001");
		thenThereIsAHeaderWithNameAndValue(request, Span.TRACE_ID_NAME, "0000000000000002");
		thenThereIsAHeaderWithNameAndValue(request, Span.PARENT_ID_NAME, "0000000000000003");
		thenThereIsAHeaderWithNameAndValue(request, Span.PROCESS_ID_NAME, "processId");
	}

	private void thenThereIsAHeaderWithNameAndValue(HttpUriRequest request, String name, String value) {
		Header header = request.getFirstHeader(name);
		then(header.getName()).isEqualTo(name);
		then(header.getValue()).isEqualTo(value);
	}
}


text:
import {FloorDiv} from '../kernel_names';
import {GradConfig} from '../kernel_registry';
import {assertAndGetBroadcastShape, getReductionAxes} from '../ops/broadcast_util';
import {cast} from '../ops/cast';
import {div} from '../ops/div';
import {mul} from '../ops/mul';
import {neg} from '../ops/neg';
import {reshape} from '../ops/reshape';
import {square} from '../ops/square';
import {sum} from '../ops/sum';
import {Tensor} from '../tensor';

export const floorDivGradConfig: GradConfig = {
  kernelName: FloorDiv,
  inputsToSave: ['a', 'b'],
  gradFunc: (dy: Tensor, saved: Tensor[]) => {
    const [a, b] = saved;
    const outShape = assertAndGetBroadcastShape(a.shape, b.shape);

    const derA = () => {
      const res = div(dy, cast(b, 'float32'));
      const reduceAxes = getReductionAxes(a.shape, outShape);
      if (reduceAxes.length > 0) {
        return reshape(sum(res, reduceAxes), a.shape);
      }
      return res;
    };
    const derB = () => {
      let res = mul(dy, cast(a, 'float32'));
      const reduceAxes = getReductionAxes(b.shape, outShape);
      if (reduceAxes.length > 0) {
        res = reshape(sum(res, reduceAxes), b.shape);
      }
      const tmp = square(b);
      return neg(div(res, cast(tmp, 'float32')));
    };
    return {a: derA, b: derB};
  }
};


text:
import * as Action from 'common/actions';
import { project, fileBuffer } from 'common/stores';
import { Writer } from 'common/connection';

export const readProjectFiles = (payload) => project.load(payload);

export const updateProject = () => Writer.readProjectFiles();

export const createFile = (file) => {
    updateProject();
    readFile(file);
}

export const readFile = (file) => {
    fileBuffer.addToBuffer(file);
    Action.viewCode(file.path);
}

export const deleteFile = (file) => {
    fileBuffer.close(file.path);
    updateProject();
};


text:
all: build

CSI_SPEC := spec.md
CSI_PROTO := csi.proto
## Build go language bindings
CSI_A := csi.a
CSI_GO := lib/go/csi/csi.pb.go
CSI_PKG := lib/go/csi

# This is the target for building the temporary CSI protobuf file.
#
# The temporary file is not versioned, and thus will always be
# built on GitHub Actions.
$(CSI_PROTO).tmp: $(CSI_SPEC) Makefile
	echo "// Code generated by make; DO NOT EDIT." > "$@"
	cat $< | sed -n -e '/```protobuf$$/,/^```$$/ p' | sed '/^```/d' >> "$@"

# This is the target for building the CSI protobuf file.
#
# This target depends on its temp file, which is not versioned.
# Therefore when built on GitHub Actions the temp file will always
# be built and trigger this target. On GitHub Actions the temp file
# is compared with the real file, and if they differ the build
# will fail.
#
# Locally the temp file is simply copied over the real file.
$(CSI_PROTO): $(CSI_PROTO).tmp
ifeq (true,$(GITHUB_ACTIONS))
	diff "$@" "$?"
else
	diff "$@" "$?" > /dev/null 2>&1 || cp -f "$?" "$@"
endif

build: check

# If this is not running on GitHub Actions then for sake of convenience
# go ahead and update the language bindings as well.
ifneq (true,$(GITHUB_ACTIONS))
build: build_cpp build_go
endif

build_cpp:
	$(MAKE) -C lib/cxx

# The file exists, but could be out-of-date.
$(CSI_GO): $(CSI_PROTO)
	$(MAKE) -C lib/go csi/csi.pb.go

$(CSI_A): $(CSI_GO)
	go mod download
	go install ./$(CSI_PKG)
	go build -o "$@" ./$(CSI_PKG)

build_go: $(CSI_A)

clean:
	rm $(CSI_A)
	$(MAKE) -C lib/go $@

clobber: clean
	$(MAKE) -C lib/go $@
	rm -f $(CSI_PROTO) $(CSI_PROTO).tmp

# check generated files for violation of standards
check: $(CSI_PROTO)
	awk '{ if (length > 72) print NR, $$0 }' $? | diff - /dev/null

.PHONY: clean clobber check


text:
<!--remove-start-->
# LED - Blink

Run with:
```bash
node eg/led-blink.js
```
<!--remove-end-->

```javascript
var five = require("johnny-five");
var board = new five.Board();

board.on("ready", function() {

  // Create a standard `led` component instance
  var led = new five.Led(13);

  // "blink" the led in 500ms on-off phase periods
  led.blink(500);
});

```

## Breadboard/Illustration

![docs/breadboard/led-blink.png](breadboard/led-blink.png)

<!--remove-start-->
## License
Copyright (c) 2012, 2013, 2014 Rick Waldron <waldron.rick@gmail.com>
Licensed under the MIT license.
Copyright (c) 2014, 2015 The Johnny-Five Contributors
Licensed under the MIT license.
<!--remove-end-->