text:
using pegleg.cs.Unicode;
using pegleg.cs.Unicode.Criteria;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace pegleg.cs.Parsing {
  public class MatchingContext {
    private readonly string _consumable;
    private readonly SourceRange[] _parts;
    private readonly MatchingResultCache _cache;
    private int _index;
    private int _sourceIndex;
    private int _sourceLine;
    private int _sourceLineIndex;
    private int _part;
    private int _partEnd;

    public MatchingContext(string source)
      : this(source, new SourceRange[] { new SourceRange(0, source.Length, 1, 0) })
    { }

    public MatchingContext(string source, SourceRange[] parts) {
      if(null == source) throw Xception.Because.ArgumentNull(() => source);
      if(null == parts) throw Xception.Because.ArgumentNull(() => parts);

      _consumable = source;
      _parts = parts;
      _cache = new MatchingResultCache(source.Length + 1);
      _index = 0;
      _part = 0;
      _partEnd = _parts[_part].Length;
      _sourceIndex = _parts[_part].Index;
      _sourceLine = _parts[_part].Line;
      _sourceLineIndex = _parts[_part].LineIndex;
    }

    private MatchingContext(MatchingContext prototype) {
      _consumable = prototype._consumable;
      _parts = prototype._parts;
      _cache = prototype._cache;
      _index = prototype._index;
      _part = prototype._part;
      _partEnd = prototype._partEnd;
      _sourceIndex = prototype._sourceIndex;
      _sourceLine = prototype._sourceLine;
      _sourceLineIndex = prototype._sourceLineIndex;
    }

    /// <remarks>
    /// Useful for inspection in the debugger.
    /// </remarks>
    protected string Unconsumed { get { return _consumable.Substring(_index); } }

    public int Index { get { return _index; } }

    public int SourceIndex { get { return _sourceIndex; } }

    public int SourceLine { get { return _sourceLine; } }

    public int SourceLineIndex { get { return _sourceLineIndex; } }

    private void Consume(int length) {
      for(; length != 0; length--) {
        var c = _consumable[_index];

        _index++;
        _sourceIndex++;

        // If we have reached the end of the current part then our source location
        // is the beginning of the next part
        if(_index == _partEnd && _consumable.Length > _index) {
          var newPart = _parts[++_part];

          _partEnd = _partEnd + newPart.Length;
          _sourceIndex = newPart.Index;
          _sourceLine = newPart.Line;
          _sourceLineIndex = newPart.LineIndex;
        } else {
          if('\n' == c) {
            _sourceLine++;
            _sourceLineIndex = 0;
          } else {
            _sourceLineIndex++;
          }
        }
      }
    }

    public string Substring(int index, int length) {
      return _consumable.Substring(index, length);
    }

    public bool ConsumesMatching(string literal) {
      if(null == literal) throw Xception.Because.ArgumentNull(() => literal);

      var len = literal.Length;
      if(len > _consumable.Length - _index)
        return false;

      if(0 == string.Compare(_consumable, _index, literal, 0, len)) {
        Consume(len);
        return true;
      } else {
        return false;
      }
    }

    public bool ConsumesMatching(Regex regex) {
      if(null == regex) throw Xception.Because.ArgumentNull(() => regex);

      var match = regex.Match(_consumable, _index);
      if(match.Success && match.Index == _index) {
        Consume(match.Length);
        return true;
      }

      return false;
    }

    public bool ConsumesMatching(Regex regex, out Match match) {
      if(null == regex) throw Xception.Because.ArgumentNull(() => regex);

      match = regex.Match(_consumable, _index);
      if(match.Success && match.Index == _index) {
        Consume(match.Length);
        return true;
      } else {
        match = null;
        return false;
      }
    }

    public bool ConsumesGraphemeCriteria(IGraphemeCriteria criteria, out int length) {
      if(AtEndOfInput) {
        length = 0;
        return false;
      }

      var category = UnicodeUtils.GetGraphemeInfo(_consumable, _index, out length);

      if(criteria.SatisfiedBy(_consumable, _index, length, category)) {
        Consume(length);
        return true;
      } else {
        return false;
      }
    }

    public bool ConsumesCodePointCriteria(ICodePointCriteria criteria, out int length) {
      if(AtEndOfInput) {
        length = 0;
        return false;
      }

      var codePoint = UnicodeUtils.GetCodePoint(_consumable, _index, out length);

      if(criteria.SatisfiedBy(codePoint)) {
        Consume(length);
        return true;
      } else {
        return false;
      }
    }

    public bool ConsumesAnyCharacter(out char c) {
      if(AtEndOfInput) {
        c = (char)0;
        return false;
      } else {
        c = _consumable[_index];
        Consume(1);
        return true;
      }
    }

    public bool AtEndOfInput { get { return _consumable.Length == _index; } }

    public MatchingContext Clone() {
      return new MatchingContext(this);
    }

    public void Assimilate(MatchingContext clone) {
      _index = clone._index;
      _part = clone._part;
      _partEnd = clone._partEnd;
      _sourceIndex = clone._sourceIndex;
      _sourceLine = clone._sourceLine;
      _sourceLineIndex = clone._sourceLineIndex;
    }

    public MatchingResultBuilder<TProduct> GetMatchBuilderFor<TProduct>(IParsingExpression<TProduct> expression) {
      return new MatchingResultBuilder<TProduct>(this, expression);
    }

    public bool ConsumesCachedResultFor<TProduct>(IParsingExpression<TProduct> expression, out IMatchingResult<TProduct> cachedResult) {
      if(!_cache.HasResult(_index, expression, out cachedResult))
        return false;

      Consume(cachedResult.Length);
      return true;
    }

    public void CacheResultFor<TProduct>(IParsingExpression<TProduct> expression, IMatchingResult<TProduct> result) {
      _cache.Store(_index - result.Length, expression, result);
    }
  }
}


text:
import { parseUrl } from '../url';
import { HttpError } from './types';

// TODO: remove when code is refactored (#9651)

Object.defineProperty(HttpError.prototype, 'statusCode', {
  get: function statusCode(this: HttpError) {
    return this.response?.statusCode;
  },
});

Object.defineProperty(HttpError.prototype, 'body', {
  get: function body(this: HttpError): unknown {
    return this.response?.body;
  },
  set: function body(this: HttpError, value: unknown): void {
    if (this.response) {
      this.response.body = value;
    }
  },
});

Object.defineProperty(HttpError.prototype, 'headers', {
  get: function headers(this: HttpError) {
    return this.response?.headers;
  },
});

Object.defineProperty(HttpError.prototype, 'url', {
  get: function url(this: HttpError) {
    return this.response?.url;
  },
});

Object.defineProperty(HttpError.prototype, 'host', {
  get: function url(this: HttpError) {
    const { host } = parseUrl(this.response?.url) ?? {};
    return host;
  },
});

export type GotLegacyError<E = unknown, T = unknown> = HttpError & {
  statusCode?: number;
  body: {
    message?: string;
    errors?: E[];
  };
  headers?: Record<string, T>;
};

redpajama_set_name: RedPajamaGithub


text:
### Grunt Compass Bootstrap Example

*If you're on the fast track and don't need any help, feel free to clone the repo.*

  ```javascript
  > npm install // downloads all packages
  > grunt watch // will automate sass build
  ```

Above you will find a boilerplate to help you establish the basic foundations of a "Nodejs" site. I have provided several technologies such as grunt which will help you quickly perform repetive tasks. Lets get started by cloning the repo.

  ``` javascript
  > git clone git@github.com:yungVitto/compass-bootstrap-grunt-example.git
  ```

Now that you have cloned this repo, it's time to set up your node_modules.

  ``` javascript
  > npm install // run from project dir
  ```

At this point, all dependecies are being downloaded and installed for your project. If you want to dive right in, by all means

  ``` javascript
  > node server.js
  > grunt watch // watches sass files
  ```

**Does Grunt have your attention? It should!**

Let's set the scene. You're working on a project and hours of tedious and repetitive work lays before you. For example:

![alt text](https://raw.github.com/yungVitto/compass-bootstrap-grunt-example/master/readme.fw.png "Sass Example")

Grunt is particularly useful when you want to automate tasks like the one above. Check out my Grunt config for more details:

  ```javascript
  grunt: grunt.initConfig({

    compass: {
      dist: {
        options: {
          outputStyle: 'compressed',
          sassDir: 'compass',
          specify: 'compass/main.scss',
          cssDir: 'build/css'
        }
      }
    },

    watch: {
      sass: {
        files: ['compass/sass/**/*.scss', '!compass/sass/vendor/**/*.scss'],
        tasks: ['compass:dist']
      }
    }

    grunt.loadNpmTasks('grunt-shell');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-compass');
    grunt.loadNpmTasks('grunt-contrib-watch');

  });
  ```


text:
// DlgASN1PSEPINPrompt.cpp: Implementierungsdatei
//

#include "stdafx.h"
#include "CrypToolApp.h"
#include "DlgASN1PSEPINPrompt.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// Dialogfeld CDlgASN1PSEPINPrompt

CDlgASN1PSEPINPrompt::CDlgASN1PSEPINPrompt(CWnd* pParent /*=NULL*/)
	: CDialog(CDlgASN1PSEPINPrompt::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDlgASN1PSEPINPrompt)
	m_PIN = _T("");
	//}}AFX_DATA_INIT
}

void CDlgASN1PSEPINPrompt::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDlgASN1PSEPINPrompt)
	DDX_Text(pDX, IDC_EDIT1, m_PIN);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CDlgASN1PSEPINPrompt, CDialog)
	//{{AFX_MSG_MAP(CDlgASN1PSEPINPrompt)
		// HINWEIS: Der Klassen-Assistent fügt hier Zuordnungsmakros für Nachrichten ein
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// Behandlungsroutinen für Nachrichten CDlgASN1PSEPINPrompt


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.uima.jcas (Apache UIMA Java SDK 2.8.1 User-Level API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.apache.uima.jcas

Interfaces

JCas

JFSIndexRepository

Classes

JCasRegistry


text:
package com.b2international.snowowl.snomed.api.rest.request;

import java.util.Map;

import com.b2international.snowowl.core.ServiceProvider;
import com.b2international.snowowl.core.events.Request;

/**
 * @since 4.5
 */
public interface RequestResolver<C extends ServiceProvider> {

	Request<C, ?> resolve(String action, Map<String, Object> source);

}


text:
import React from 'react'

var AUTH_HOST = require('../../../../DEV_CONFIG.json').host

export class SignupForm extends React.Component<void, Props, void> {
  render(){
    return(

        {this.props.nav ? "" :
Fill out the form below to create an account
}
        <form method="POST" className="form-signin">
          <fieldset>

                  <input onChange={this.props.onChange} id="email" name="email" type="email"
                      className="form-control input-lg"  placeholder="E-Mail"
                      required/>

                  <input onChange={this.props.onChange} id="password" name="password" type="password"
                      className="form-control input-lg" placeholder="Password"
                      required/>

                  <input onChange={this.props.onChange} id="confirmpassword" name="confirmpassword" type="password"
                      className="form-control input-lg" placeholder="Confirm Password"
                      required/>

          </fieldset>

                <button onClick={this.props.onSubmit.bind(null,(AUTH_HOST + "signup/auth"))} className="btn btn-block btn-lg btn-success">
                  Create Account
                </button>

                <button id="signupSwitch" className="btn btn-block" onClick={this.props.formChange}>
                  Already have an account?
                </button>

        </form>

    )
  }
}

export default (SignupForm)


text:
<?php
/**
 * Created by PhpStorm.
 * User: Nabeel
 * Date: 2015-10-20
 * Time: 8:28 PM
 */

namespace app\components;

use app\models\Job;
use ShortCirquit\LinkoScopeApi\iApiHandler;

class AsyncApiHandler implements iApiHandler
{
    function refreshLink($id)
    {
        $job = new Job();
        $job->type = 'refresh_link';
        $job->arguments = json_encode(['id' => $id]);
        $job->save();
    }

    function refreshComment($id)
    {
        $job = new Job();
        $job->type = 'refresh_comment';
        $job->arguments = json_encode(['id' => $id]);
        $job->save();
    }
}


text:
package example.repo;

import example.model.Customer1249;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface Customer1249Repository extends CrudRepository<Customer1249, Long> {

	List<Customer1249> findByLastName(String lastName);
}


text:
Migration from older versions
=============================

3.3.0 ->
--------

json4s 3.3 basically should be source code compatible with 3.2.x. Since json4s 3.3.0, We've started using [MiMa](https://github.com/typesafehub/migration-manager) for binary compatibility verification not to repeat the bin compatibility issue described [here](https://github.com/json4s/json4s/issues/225).

The behavior of `.toOption` on JValue has changed. Now both `JNothing` and `JNull` return None.
For the old behavior you can use `toSome` which will only turn a `JNothing` into a None.

All the merged pull requests:
https://github.com/json4s/json4s/pulls?q=is%3Apr+is%3Aclosed+milestone%3A3.3

3.0.0 ->
--------

JField is no longer a JValue. This means more type safety since it is no longer possible
to create invalid JSON where JFields are added directly into JArrays for instance. The most
noticeable consequence of this change are that map, transform, find and filter come in
two versions:

```scala
def map(f: JValue => JValue): JValue
def mapField(f: JField => JField): JValue
def transform(f: PartialFunction[JValue, JValue]): JValue
def transformField(f: PartialFunction[JField, JField]): JValue
def find(p: JValue => Boolean): Option[JValue]
def findField(p: JField => Boolean): Option[JField]
//...
```

Use *Field functions to traverse fields in the JSON, and use the functions without 'Field'
in the name to traverse values in the JSON.

2.2 ->
------

Path expressions were changed after version 2.2. Previous versions returned JField, which
unnecessarily complicated the use of the expressions. If you have used path expressions
with pattern matching like:

```scala
val JField("bar", JInt(x)) = json \ "foo" \ "bar"
```

it is now required to change that to:

```scala
val JInt(x) = json \ "foo" \ "bar"
```


text:
require('es6-promise').polyfill();

var request = require('request');
var url = require('url');

module.exports = function(username, password, hostname) {
  var uri = url.resolve(hostname, '/rest/api/content/search');
  return {
    simpleSearch: function(cql) {
      return new Promise(function(resolve, reject) {
        request({
          method: 'GET',
          uri: uri,
          json: true,
          qs: {
            limit: 5,
            cql : cql
          },
          auth: {
            'user': username,
            'pass': password,
            'sendImmediately': true
          },
        }, function( err, response, results) {
          if (err) { return reject(err); }
          //Check for right status code
          if(response.statusCode !== 200) {
            var bod = JSON.stringify(response.body);
            return reject('Invalid Status Code Returned: ' + response.statusCode + ' - ' + response.body.message);
          }

          if (!results) { return reject("empty result object"); }
          return resolve(results);
        });
      });
    }
  };
};


text:
package org.teavm.idea.jps;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Collection;
import java.util.List;
import org.teavm.callgraph.CallGraph;
import org.teavm.diagnostics.Problem;
import org.teavm.diagnostics.ProblemProvider;
import org.teavm.idea.jps.model.TeaVMBuildResult;
import org.teavm.idea.jps.model.TeaVMBuildStrategy;
import org.teavm.idea.jps.remote.TeaVMRemoteBuildCallback;
import org.teavm.idea.jps.remote.TeaVMRemoteBuildRequest;
import org.teavm.idea.jps.remote.TeaVMRemoteBuildResponse;
import org.teavm.idea.jps.remote.TeaVMRemoteBuildService;
import org.teavm.tooling.TeaVMTargetType;
import org.teavm.vm.TeaVMPhase;
import org.teavm.vm.TeaVMProgressFeedback;
import org.teavm.vm.TeaVMProgressListener;

public class RemoteBuildStrategy implements TeaVMBuildStrategy {
    private TeaVMRemoteBuildRequest request;
    private TeaVMRemoteBuildService buildService;
    private TeaVMProgressListener progressListener;

    public RemoteBuildStrategy(TeaVMRemoteBuildService buildService) {
        this.buildService = buildService;
    }

    @Override
    public void init() {
        request = new TeaVMRemoteBuildRequest();
    }

    @Override
    public void addSourcesDirectory(String directory) {
        request.sourceDirectories.add(directory);
    }

    @Override
    public void addSourcesJar(String jarFile) {
        request.sourceJarFiles.add(jarFile);
    }

    @Override
    public void setClassPathEntries(List<String> entries) {
        request.classPath.addAll(entries);
    }

    @Override
    public void setTargetType(TeaVMTargetType targetType) {
        request.targetType = targetType;
    }

    @Override
    public void setMainClass(String mainClass) {
        request.mainClass = mainClass;
    }

    @Override
    public void setTargetDirectory(String targetDirectory) {
        request.targetDirectory = targetDirectory;
    }

    @Override
    public void setSourceMapsFileGenerated(boolean sourceMapsFileGenerated) {
        request.sourceMapsFileGenerated = sourceMapsFileGenerated;
    }

    @Override
    public void setDebugInformationGenerated(boolean debugInformationGenerated) {
        request.debugInformationGenerated = debugInformationGenerated;
    }

    @Override
    public void setSourceFilesCopied(boolean sourceFilesCopied) {
        request.sourceFilesCopied = sourceFilesCopied;
    }

    @Override
    public void setProgressListener(TeaVMProgressListener progressListener) {
        this.progressListener = progressListener;
    }

    @Override
    public TeaVMBuildResult build() {
        TeaVMRemoteBuildResponse response;
        try {
            response = buildService.build(request, new CallbackImpl(progressListener));
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return new TeaVMBuildResult() {
            private ProblemProvider problems = new ProblemProvider() {
                @Override
                public List<Problem> getProblems() {
                    return response.problems;
                }

                @Override
                public List<Problem> getSevereProblems() {
                    return response.severeProblems;
                }
            };

            @Override
            public CallGraph getCallGraph() {
                return response.callGraph;
            }

            @Override
            public boolean isErrorOccurred() {
                return response.errorOccurred;
            }

            @Override
            public ProblemProvider getProblems() {
                return problems;
            }

            @Override
            public Collection<String> getUsedResources() {
                return response.usedResources;
            }

            @Override
            public Collection<String> getClasses() {
                return response.classes;
            }
        };
    }

    static class CallbackImpl extends UnicastRemoteObject implements TeaVMRemoteBuildCallback {
        private TeaVMProgressListener listener;

        public CallbackImpl(TeaVMProgressListener listener) throws RemoteException {
            super();
            this.listener = listener;
        }

        @Override
        public TeaVMProgressFeedback phaseStarted(TeaVMPhase phase, int count) throws RemoteException {
            return listener.phaseStarted(phase, count);
        }

        @Override
        public TeaVMProgressFeedback progressReached(int progress) throws RemoteException {
            return listener.progressReached(progress);
        }
    }
}


text:
"""
WSGI config for statdev project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
import confy
from django.core.wsgi import get_wsgi_application
import os

confy.read_environment_file(".env")

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "statdev.settings")
application = get_wsgi_application()


text:
package org.homeautomation.doormanager.api;

import org.homeautomation.doormanager.api.dto.DeviceJSON;
import org.homeautomation.doormanager.api.dto.UserInfo;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * This is the API which is used to control and manage device type functionality
 */
@SuppressWarnings("NonJaxWsWebServices")
@API(name = "doormanager", version = "1.0.0", context = "/doormanager", tags = "doormanager")
@DeviceType(value = "doormanager")
public interface DoorManagerService {

    /**
     * @param deviceId  unique identifier for given device type instance
     * @param state     change status of sensor: on/off
     */
    @Path("device/{deviceId}/change-status")
    @POST
    @Feature(code = "change-status", name = "Change status of door lock: lock/unlock",
            description = "Change status of door lock: lock/unlock")
    Response changeStatusOfDoorLockSafe(@PathParam("deviceId") String deviceId,
                                               @QueryParam("state") String state,
                                               @Context HttpServletResponse response);

    /**
     * Retrieve Sensor data for the given time period
     * @param deviceId unique identifier for given device type instance
     * @param from  starting time
     * @param to    ending time
     * @return  response with List<SensorRecord> object which includes sensor data which is requested
     */
    @Path("device/stats/{deviceId}")
    @GET
    @Consumes("application/json")
    @Produces("application/json")
    @Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/stats"})
    Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
                            @QueryParam("to") long to, @QueryParam("sensorType") String sensorType);

    /**
     * Remove device type instance using device id
     * @param deviceId  unique identifier for given device type instance
     */
    @Path("/device/{device_id}")
    @DELETE
    @Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/removeDevice"})
    Response removeDevice(@PathParam("device_id") String deviceId);

    /**
     * Update device instance name
     * @param deviceId  unique identifier for given device type instance
     * @param name      new name for the device type instance
     */
    @Path("/device/{device_id}")
    @PUT
    @Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/updateDevice"})
    Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);

    /**
     * To get device information
     * @param deviceId  unique identifier for given device type instance
     * @return Device object which carries all information related to a managed device
     */
    @Path("/device/{device_id}")
    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/updateDevice"})
    Response getDevice(@PathParam("device_id") String deviceId);

    /**
     * Get all device type instance which belongs to user
     * @return  Array of devices which includes device's information
     */
    @Path("/devices")
    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/devices"})
    Response getAllDevices();

    /**
     * To download device type agent source code as zip file
     * @param deviceName   name for the device type instance
     * @param sketchType   folder name where device type agent was installed into server
     * @return  Agent source code as zip file
     */
    @Path("/device/download")
    @GET
    @Produces("application/zip")
    @Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/download"})
    Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType);

    @Path("device/assign-user/{deviceId}")
    @POST
    @Feature(code = "assign-user", name = "Assign new user to lock",
            description = "Add new access card to user to control the lock ")
    Response assignUserToLock(@QueryParam("cardNumber") String cardNumber,
                                     @QueryParam("userName") String userName,
                                     @QueryParam("emailAddress") String emailAddress,
                                     @PathParam("deviceId") String deviceId);

    /**
     * @param userInfo user information which are required to test given user is authorized to open requested door
     * @return if user is authorized open the the door allow to open it
     */
    @POST
    @Path("/device/is-user-authorized")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    Response isUserAuthorized(final UserInfo userInfo);
}


text:
package main

import (
	"io"
	"os"

	"github.com/gorilla/websocket"
	"github.com/mattn/go-colorable"

	"github.com/lxc/lxd/shared/logger"
)

// Windows doesn't process ANSI sequences natively, so we wrap
// os.Stdout for improved user experience for Windows client
type WrappedWriteCloser struct {
	io.Closer
	wrapper io.Writer
}

func (wwc *WrappedWriteCloser) Write(p []byte) (int, error) {
	return wwc.wrapper.Write(p)
}

func (c *execCmd) getStdout() io.WriteCloser {
	return &WrappedWriteCloser{os.Stdout, colorable.NewColorableStdout()}
}

func (c *execCmd) getTERM() (string, bool) {
	return "dumb", true
}

func (c *execCmd) controlSocketHandler(control *websocket.Conn) {
	// TODO: figure out what the equivalent of signal.SIGWINCH is on
	// windows and use that; for now if you resize your terminal it just
	// won't work quite correctly.
	err := c.sendTermSize(control)
	if err != nil {
		logger.Debugf("error setting term size %s", err)
	}
}


text:
namespace MassTransit
{
    using System;
    using Configuration;

    public static class DynamoDbSagaRepositoryRegistrationExtensions
    {
        /// <summary>
        /// Adds a DynamoDb saga repository to the registration
        /// </summary>
        /// <param name="configurator"></param>
        /// <param name="configure"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static ISagaRegistrationConfigurator<T> DynamoDbRepository<T>(this ISagaRegistrationConfigurator<T> configurator,
            Action<IDynamoDbSagaRepositoryConfigurator<T>> configure = null)
            where T : class, ISagaVersion
        {
            var repositoryConfigurator = new DynamoDbSagaRepositoryConfigurator<T>();

            configure?.Invoke(repositoryConfigurator);

            repositoryConfigurator.Validate().ThrowIfContainsFailure("The DynamoDb saga repository configuration is invalid:");

            configurator.Repository(x => repositoryConfigurator.Register(x));

            return configurator;
        }

        /// <summary>
        /// Use the DynamoDb saga repository for sagas configured by type (without a specific generic call to AddSaga/AddSagaStateMachine)
        /// </summary>
        /// <param name="configurator"></param>
        /// <param name="configure"></param>
        public static void SetDynamoDbSagaRepositoryProvider(this IRegistrationConfigurator configurator, Action<IDynamoDbSagaRepositoryConfigurator> configure)
        {
            configurator.SetSagaRepositoryProvider(new DynamoDbSagaRepositoryRegistrationProvider(configure));
        }
    }
}


text:
<?php

namespace Ankur\Plugins\Ank_Google_Map;
/**
 * Class Admin
 * @package Ankur\Plugins\Ank_Google_Map
 */
class Admin
{

    /**
     * Unique plugin option page slug
     */
    const PLUGIN_SLUG = 'agm_settings';

    /**
     * Utility class instance
     * @var Util
     */
    private $util;

    /**
     * Settings class instance
     * @var Settings
     */
    private $settings;

    public function __construct()
    {
        // Add settings link to plugin list page
        add_filter('plugin_action_links_' . plugin_basename(AGM_BASE_FILE), array($this, 'add_plugin_actions_links'), 10, 2);

        // Add settings link under settings menu
        add_action('admin_menu', array($this, 'add_link_to_settings_menu'));

        // Be multilingual
        add_action('plugins_loaded', array($this, 'load_text_domain'));

        // Init class
        $this->util = new Util();
        $this->settings = new Settings();
    }

    /**
     * Adds a 'Settings' link for this plugin on plugin listing page
     *
     * @param $links
     * @return array  Links array
     */
    public function add_plugin_actions_links($links)
    {
        if (current_user_can('manage_options')) {
            $url = add_query_arg('page', self::PLUGIN_SLUG, 'options-general.php');
            array_unshift(
                $links,
                sprintf('%s', $url, __('Settings'))
            );
        }

        return $links;
    }

    public function add_link_to_settings_menu()
    {
        $page_hook_suffix = add_submenu_page(
            'options-general.php',
            'Google Map', // page title
            'Google Map', // menu text
            'manage_options',
            self::PLUGIN_SLUG,
            array($this->settings, 'load_option_page')
        );

        add_action('admin_print_scripts-' . $page_hook_suffix, array($this, 'add_admin_assets'));
    }

    public function load_text_domain()
    {
        load_plugin_textdomain('ank-google-map', false, dirname(plugin_basename(AGM_BASE_FILE)) . '/languages/');
    }

    /**
     * Returns dynamic javascript options to be used by admin js
     * @return array
     */
    private function get_js_options()
    {
        $db = get_option('ank_google_map');

        return array(
            'map' => array(
                'lat' => esc_attr($db['map_Lat']),
                'lng' => esc_attr($db['map_Lng']),
                'zoom' => absint($db['map_zoom']),
                'style' => absint($db['map_style']),
            ),
            'marker' => array(
                'color' => $this->util->get_marker_url($db['marker_color']),
                'file' => empty($db['marker_file']) ? false : esc_url($db['marker_file'])
            ),
            'styles' => $this->util->get_styles()
        );
    }

    public function add_admin_assets()
    {
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');
        wp_enqueue_media();

        $is_min = (defined('WP_DEBUG') && WP_DEBUG == true) ? '' : '.min';
        $db = get_option('ank_google_map');
        wp_enqueue_style('agm-admin-css', plugins_url('/assets/option-page' . $is_min . '.css', AGM_BASE_FILE), array(), AGM_PLUGIN_VERSION, 'all');

        $api_key = empty($db['api_key']) ? '' : '&key=' . esc_js($db['api_key']);
        wp_enqueue_script('agm-google-map', 'https://maps.googleapis.com/maps/api/js?v=' . AGM_API_VER . '&libraries=places' . $api_key, array(), null, true);
        wp_enqueue_script('agm-admin-js', plugins_url("/assets/option-page" . $is_min . ".js", AGM_BASE_FILE), array('jquery', 'agm-google-map'), AGM_PLUGIN_VERSION, true);

        // WP inbuilt hack to print js options object just before this script
        wp_localize_script('agm-admin-js', '_agmOpt', $this->get_js_options());
    }
}


text:
<?php

final class DifferentialReviewersCommitMessageField
  extends DifferentialCommitMessageField {

  const FIELDKEY = 'reviewerPHIDs';

  public function getFieldName() {
    return pht('Reviewers');
  }

  public function getFieldOrder() {
    return 4000;
  }

  public function getFieldAliases() {
    return array(
      'Reviewer',
    );
  }

  public function parseFieldValue($value) {
    $results = $this->parseObjectList(
      $value,
      array(
        PhabricatorPeopleUserPHIDType::TYPECONST,
        PhabricatorProjectProjectPHIDType::TYPECONST,
        PhabricatorOwnersPackagePHIDType::TYPECONST,
      ),
      false,
      array('!'));

    return $this->flattenReviewers($results);
  }

  public function readFieldValueFromConduit($value) {
    return $this->readStringListFieldValueFromConduit($value);
  }

  public function readFieldValueFromObject(DifferentialRevision $revision) {
    if (!$revision->getPHID()) {
      return array();
    }

    $status_blocking = DifferentialReviewerStatus::STATUS_BLOCKING;

    $results = array();
    foreach ($revision->getReviewerStatus() as $reviewer) {
      if ($reviewer->getStatus() == $status_blocking) {
        $suffixes = array('!' => '!');
      } else {
        $suffixes = array();
      }

      $results[] = array(
        'phid' => $reviewer->getReviewerPHID(),
        'suffixes' => $suffixes,
      );
    }

    return $this->flattenReviewers($results);
  }

  public function renderFieldValue($value) {
    $value = $this->inflateReviewers($value);

    $phid_list = array();
    $suffix_map = array();
    foreach ($value as $reviewer) {
      $phid = $reviewer['phid'];
      $phid_list[] = $phid;
      if (isset($reviewer['suffixes']['!'])) {
        $suffix_map[$phid] = '!';
      }
    }

    return $this->renderHandleList($phid_list, $suffix_map);
  }

  public function getFieldTransactions($value) {
    $value = $this->inflateReviewers($value);

    $reviewer_list = array();
    foreach ($value as $reviewer) {
      $phid = $reviewer['phid'];
      if (isset($reviewer['suffixes']['!'])) {
        $reviewer_list[] = 'blocking('.$phid.')';
      } else {
        $reviewer_list[] = $phid;
      }
    }

    $xaction_key = DifferentialRevisionReviewersTransaction::EDITKEY;
    $xaction_type = "{$xaction_key}.set";

    return array(
      array(
        'type' => $xaction_type,
        'value' => $reviewer_list,
      ),
    );
  }

  private function flattenReviewers(array $values) {
    // NOTE: For now, `arc` relies on this field returning only scalars, so we
    // need to reduce the results into scalars. See T10981.
    $result = array();

    foreach ($values as $value) {
      $result[] = $value['phid'].implode('', array_keys($value['suffixes']));
    }

    return $result;
  }

  private function inflateReviewers(array $values) {
    $result = array();

    foreach ($values as $value) {
      if (substr($value, -1) == '!') {
        $value = substr($value, 0, -1);
        $suffixes = array('!' => '!');
      } else {
        $suffixes = array();
      }

      $result[] = array(
        'phid' => $value,
        'suffixes' => $suffixes,
      );
    }

    return $result;
  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using DataSources.Exceptions;
using DataSources.Query;

namespace DataSources.DataSource
{
    /// <summary>
    /// Handles the rendering of a SQL string from data.
    /// </summary>
    internal static class MySqlRender
    {
        /// <summary>
        /// Comma separator for query sets.
        /// </summary>
        private const string _COMMA = ",";

        /// <summary>
        /// Formats a fieldname.
        /// </summary>
        private static string Field(string pTable, string pField)
        {
            // does field contain an expression
            if (pField.Contains('(') && pField.Contains(')'))
            {
                return pField;
            }
            // other types of expressions
            if (pField.ToUpper().Contains(" AS ") || pField.ToUpper().Contains(" WITH "))
            {
                return pField;
            }

            return string.Format("`{0}`.`{1}`", pTable, pField);
        }

        /// <summary>
        /// MySQL date format
        /// </summary>
        public static string Date(DateTime pDate)
        {
            return pDate.ToString("yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>
        /// List of fields
        /// </summary>
        public static string Fields(string pTable, Fields pFields)
        {
            return pFields.Count == 0
                ? string.Format("`{0}`.*", pTable)
                : string.Join(_COMMA, from field in pFields.Values
                                      select Field(pTable, field.Name));
        }

        /// <summary>
        /// List of fields for group by
        /// </summary>
        public static string Groups(string pTable, iFields pFields)
        {
            Fields fields = (Fields)pFields;
            return string.Join(_COMMA, from field in fields.Values
                                       select Field(pTable, field.Name));
        }

        /// <summary>
        /// Renders the JOIN for a query.
        /// </summary>
        public static string Join(Joinable pJoin)
        {
            if (pJoin.Type == eJOIN.NONE)
            {
                throw new ModelException("JOIN type not set for query.");
            }

            string type = pJoin.Type.ToString().Replace("_", " ");
            string on = ((Conditions)pJoin.Where).Root.Render();

            IEnumerable<string> tables = pJoin.JoinTables.Select(pJoinTable => string.Format("`{0}`",pJoinTable.Table));

            return string.Format("{0} JOIN ({1}) ON {2}", type, string.Join(_COMMA, tables), on);
        }

        /// <summary>
        /// Order clause
        /// </summary>
        public static string Order(QueryBuilder pQuery)
        {
            return string.Join(_COMMA,
                from orderBy in pQuery.Order select string.Format("{0} {1}", orderBy.Value, orderBy.Key));
        }

        /// <summary>
        /// Field assignments
        /// </summary>
        public static string Set(iFields pFields)
        {
            Fields fields = (Fields)pFields;

            return string.Join(_COMMA, from field in fields.Values
                                       select string.Format("`{0}`={1}", field.Name, field.Value));
        }

        /// <summary>
        /// Creates a SET statement for creating local variables.
        /// </summary>
        public static string Variables(iParameters pVariables)
        {
            Parameters vars = (Parameters)pVariables;
            if (vars.Count == 0)
            {
                return "";
            }
            IEnumerable<string> values = from pair in vars.Data
                                         select string.Format("{0}={1}", pair.Key, pair.Value);

            return string.Format("SET {0};", string.Join(_COMMA, values));
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.core.amqp;

import com.azure.core.amqp.exception.AmqpException;

import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeoutException;

import static com.azure.core.amqp.exception.AmqpErrorCondition.SERVER_BUSY_ERROR;
import static com.azure.core.amqp.implementation.ClientConstants.SERVER_BUSY_WAIT_TIME;

/**
 * An abstract representation of a policy to govern retrying of messaging operations.
 */
public abstract class AmqpRetryPolicy {
    static final long NANOS_PER_SECOND = 1000_000_000L;

    private static final double JITTER_FACTOR = 0.08;

    private final AmqpRetryOptions retryOptions;
    private final Duration baseJitter;

    /**
     * Creates an instance with the given retry options. If {@link AmqpRetryOptions#getMaxDelay()}, {@link
     * AmqpRetryOptions#getDelay()}, or {@link AmqpRetryOptions#getMaxRetries()} is equal to {@link Duration#ZERO} or
     * zero, requests failing with a retriable exception will not be retried.
     *
     * @param retryOptions The options to set on this retry policy.
     * @throws NullPointerException if {@code retryOptions} is {@code null}.
     */
    protected AmqpRetryPolicy(AmqpRetryOptions retryOptions) {
        Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null.");

        this.retryOptions = retryOptions;

        // 1 second = 1.0 * 10^9 nanoseconds.
        final double jitterInNanos = retryOptions.getDelay().getSeconds() * JITTER_FACTOR * NANOS_PER_SECOND;
        baseJitter = Duration.ofNanos((long) jitterInNanos);
    }

    /**
     * Gets the set of options used to configure this retry policy.
     *
     * @return The set of options used to configure this retry policy.
     */
    public AmqpRetryOptions getRetryOptions() {
        return retryOptions;
    }

    /**
     * Gets the maximum number of retry attempts.
     *
     * @return The maximum number of retry attempts.
     */
    public int getMaxRetries() {
        return retryOptions.getMaxRetries();
    }

    /**
     * Calculates the amount of time to delay before the next retry attempt.
     *
     * @param lastException The last exception that was observed for the operation to be retried.
     * @param retryCount The number of attempts that have been made, including the initial attempt before any retries.
     * @return The amount of time to delay before retrying the associated operation; if {@code null}, then the operation
     * is no longer eligible to be retried.
     */
    public Duration calculateRetryDelay(Throwable lastException, int retryCount) {
        if (retryOptions.getDelay() == Duration.ZERO
            || retryOptions.getMaxDelay() == Duration.ZERO
            || retryCount > retryOptions.getMaxRetries()) {
            return null;
        }

        final Duration baseDelay;
        if (lastException instanceof AmqpException && isRetriableException(lastException)) {
            baseDelay = ((AmqpException) lastException).getErrorCondition() == SERVER_BUSY_ERROR
                ? retryOptions.getDelay().plus(SERVER_BUSY_WAIT_TIME)
                : retryOptions.getDelay();
        } else if (lastException instanceof TimeoutException) {
            baseDelay = retryOptions.getDelay();
        } else {
            baseDelay = null;
        }

        if (baseDelay == null) {
            return null;
        }

        final Duration delay = calculateRetryDelay(retryCount, baseDelay, baseJitter, ThreadLocalRandom.current());

        // If delay is smaller or equal to the maximum delay, return the maximum delay.
        return delay.compareTo(retryOptions.getMaxDelay()) <= 0
            ? delay
            : retryOptions.getMaxDelay();
    }

    /**
     * Calculates the amount of time to delay before the next retry attempt based on the {@code retryCount},
     * {@code baseDelay}, and {@code baseJitter}.
     *
     * @param retryCount The number of attempts that have been made, including the initial attempt before any retries.
     * @param baseDelay The base delay for a retry attempt.
     * @param baseJitter The base jitter delay.
     * @param random The random number generator. Can be utilised to calculate a random jitter value for the retry.
     * @return The amount of time to delay before retrying to associated operation; or {@code null} if the it cannot be
     * retried.
     */
    protected abstract Duration calculateRetryDelay(int retryCount, Duration baseDelay, Duration baseJitter,
        ThreadLocalRandom random);

    @Override
    public int hashCode() {
        return Objects.hash(retryOptions);
    }

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

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

        final AmqpRetryPolicy other = (AmqpRetryPolicy) obj;
        return retryOptions.equals(other.retryOptions);
    }

    /**
     * Check if the existing exception is a retriable exception.
     *
     * @param exception An exception that was observed for the operation to be retried.
     * @return true if the exception is a retriable exception, otherwise false.
     */
    private static boolean isRetriableException(Throwable exception) {
        return (exception instanceof AmqpException) && ((AmqpException) exception).isTransient();
    }
}


text:
package com.structurizr.analysis.myapp.api;

import com.structurizr.analysis.myapp.service.SomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SomeApiController {

    @Autowired
    private SomeService someService;

    //@RequestMapping(value = "/do/something") - commenting this out removes a dependency on Spring MVC
    public String findSomething() {
        someService.doSomething();

        return "{some json}";
    }

}


text:
// CalloutUtil.java
//
// This is a utility class for custom policies in Apigee Edge.
// For full details see the Readme accompanying this source file.
//
// Copyright (c) 2016 Apigee Corp, 2017 Google LLC
//
// 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.
//
// @author: Dino Chiesa
//
// Saturday, 21 May 2016, 08:59
//

package com.google.apigee.util;

import com.apigee.flow.message.MessageContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.Collectors;

public final class CalloutUtil {

    public static Map<String,String> genericizeMap(Map properties) {
        // convert an untyped Map to a generic map
        Map<String,String> m = new HashMap<String,String>();
        Iterator iterator =  properties.keySet().iterator();
        while(iterator.hasNext()){
            Object key = iterator.next();
            Object value = properties.get(key);
            if ((key instanceof String) && (value instanceof String)) {
                m.put((String) key, (String) value);
            }
        }
        return Collections.unmodifiableMap(m);
    }

    public static String getHeaderWithCommas(MessageContext msgCtxt, String headerName) {
        ArrayList<String> list =
            msgCtxt.getVariable("request.header." + headerName + ".values");
        return list
            .stream()
            .map( e -> e.toString())
            .collect(Collectors.joining(","));
    }

    // /**
    //  * Strips all leading and trailing characters from the given string.
    //  * Does NOT strip characters in the middle, and strips the leading and
    //  * trailing characters respectively.
    //  * e.g. "{abc}", "{", "}" returns "abc"
    //  * e.g. "aabccxyz", "ba", "z" returns "ccxy"
    //  *
    //  * @param toStrip  The String to remove characters from
    //  * @param start  The characters to remove from the start (in any order)
    //  * @param end The characters to remove from the end (in any order)
    //  * @return String with leading and trailing characters stripped
    //  */
    // public static String stripStartAndEnd(String toStrip, String start, String end) {
    //     if(toStrip == null || toStrip.trim().equals("")) {
    //         throw new IllegalArgumentException("toStrip must not be blank or null");
    //     }
    //     return StringUtils.stripEnd(StringUtils.stripStart(toStrip, start), end);
    // }

}


text:
package com.amazonaws.codesamples.gsg;

import java.util.Iterator;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemCollection;
import com.amazonaws.services.dynamodbv2.document.ScanOutcome;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;

public class MoviesScan {

    public static void main(String[] args) {

        AmazonDynamoDBClient client = new AmazonDynamoDBClient();
        client.setEndpoint("http://localhost:8000");
        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("Movies");

        ScanSpec scanSpec = new ScanSpec()
            .withProjectionExpression("#yr, title, info.rating")
            .withFilterExpression("#yr between :start_yr and :end_yr")
            .withNameMap(new NameMap().with("#yr",  "year"))
            .withValueMap(new ValueMap().withNumber(":start_yr", 1950).withNumber(":end_yr", 1959));

        ItemCollection<ScanOutcome> items = table.scan(scanSpec);

        Iterator<Item> iter = items.iterator();
        while (iter.hasNext()) {
            Item item = iter.next();
            System.out.println(item.toString());
        }
    }
}


text:
extern "C" {
#endif

#define __NEED_time_t

#include <bits/alltypes.h>

struct timeb {
	time_t time;
	unsigned short millitm;
	short timezone, dstflag;
};

int ftime(struct timeb *);

#ifdef __cplusplus
}
#endif
#endif


text:
- Blind Search
  - Breadth-First Search
  - Depth-First Search
- Heuristic Search
  - A* Search with two heuristics :
    - Euclidean Distance
    - Taxicab Distance

#### Original Snake Game Code Taken From :
[@JDStraughan HTML5-Snake](https://github.com/JDStraughan/html5-snake)
#### I am going to add AI to it :stuck_out_tongue_winking_eye::+1:


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.locale" value="zh_CN" />
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<constant name="struts.i18n.reload" value="true" />
	<constant name="struts.configuration.xml.reload" value="true" />
	<!-- <constant name="struts.custom.i18n.resources" value="tsss" /> -->
	<constant name="struts.devMode" value="true" />
	<constant name="struts.xslt.nocache" value="true" />
	<constant name="struts.action.extension" value="do,ftl,action" />

	<package name="system" extends="struts-default" namespace="/">
		<default-interceptor-ref name="defaultStack" />
		<default-action-ref name="index" />
		<global-results>
			<result name="error">/page/error.jsp</result>
			<result name="exception" type="redirect">/page/error.jsp</result>
			<!-- <result name="dialogResult">/page/mresult.jsp</result> -->
		</global-results>
		<global-exception-mappings>
			<exception-mapping result="exception" exception="java.lang.Exception" />
		</global-exception-mappings>
		<!--When the action does not exist, use the default action -->
		<action name="index">
			<result type="redirect">/index.jsp</result>
		</action>
		<!-- 用户登录 -->
		<action name="login" class="com.zero.billiards.web.action.LoginAction">
			<result name="success" type="redirect">index.jsp</result>
			<result name="input">login.jsp</result>
		</action>

		<!-- 用户退出 -->
		<action name="logout" class="com.zero.billiards.web.action.LogoutAction">
			<result name="success" type="redirect">login.jsp</result>
		</action>
	</package>
	<package name="game_action" extends="system"
		namespace="/game">

		<!-- 用户注册 -->
		<action name="registerAction" class="com.zero.billiards.web.action.RegisterAction">
			<result name="success" type="redirect">result.jsp</result>
			<result name="input">register.jsp</result>
		</action>

		<action name="*" class="com.zero.billiards.web.action.GameAction"
			method="{1}">
			<result name="success">result.jsp</result>
			<result name="input">inputResult.jsp</result>
			<result name="search">search.jsp</result>
			<result name="result">searchResult.jsp</result>
			<result name="findGameDetailRecord" type="redirectAction">findGameDetailRecord
			</result>
			<result name="index" type="redirect">/index.jsp</result>
		</action>

	</package>

	<package name="stats_action" extends="system" 	namespace="/stats">
		<action name="*" class="com.zero.billiards.web.action.StatsAction"
			method="{1}">
			<result name="success">stats.jsp</result>
			<result name="index" type="redirect">/index.jsp</result>
		</action>
	</package>
</struts>


text:
package com.alibaba.easyexcel.test.temp.issue1663;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@EqualsAndHashCode
public class FillData {
    private String name;
    private double number;
}


text:
      {{ partial "social_links.html" . }}

            Copyright © 2017

    {{ partial "google_analytics.html" . }}


text:
docdb-cms
=========

A simple cms written using Azure's DocumentDB


text:
/****************************************************
 *                                                  *
 *             (c) 2000-2003 TwelveMonkeys                *
 *             All rights reserved                  *
 *             http://www.twelvemonkeys.no                 *
 *                                                  *
 *   $RCSfile: ConditionalTagBase.java,v $
 *   @version  $Revision: #1 $
 *   $Date: 2008/05/05 $
 *                                                  *
 *   @author  Last modified by: $Author: haku $
 *                                                  *
 ****************************************************/

/*
 * Produced (p) 2002 TwelveMonkeys
 * Address : Svovelstikka 1, Box 6432 Etterstad, 0605 Oslo, Norway.
 * Phone   : +47 22 57 70 00
 * Fax     : +47 22 57 70 70
 */
package com.twelvemonkeys.servlet.jsp.taglib.logic;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

/**
 *
An abstract base class for tags with some kind of conditional presentation of the tag body.

 *
 * @version 1.0
 * @author Eirik Torske
 */
public abstract class ConditionalTagBase extends TagSupport {

  // Members
  protected String objectName;
  protected String objectValue;

  // Properties

  /**
   * Method getName
   *
   *
   * @return
   *
   */
  public String getName() {
    return objectName;
  }

  /**
   * Method setName
   *
   *
   * @param pObjectName
   *
   */
  public void setName(String pObjectName) {
    this.objectName = pObjectName;
  }

  /**
   * Method getValue
   *
   *
   * @return
   *
   */
  public String getValue() {
    return objectValue;
  }

  /**
   * Method setValue
   *
   *
   * @param pObjectValue
   *
   */
  public void setValue(String pObjectValue) {
    this.objectValue = pObjectValue;
  }

  /**
   *
Perform the test required for this particular tag, and either evaluate or skip the body of this tag.

   *
   *
   * @return
   * @exception JspException if a JSP exception occurs.
   */
  public int doStartTag() throws JspException {

    if (condition()) {
      return (EVAL_BODY_INCLUDE);
    } else {
      return (SKIP_BODY);
    }
  }

  /**
   *
Evaluate the remainder of the current page as normal.

   *
   *
   * @return
   * @exception JspException if a JSP exception occurs.
   */
  public int doEndTag() throws JspException {
    return (EVAL_PAGE);
  }

  /**
   *
Release all allocated resources.

   */
  public void release() {

    super.release();
    objectName = null;
    objectValue = null;
  }

  /**
   *
The condition that must be met in order to display the body of this tag.

   *
   * @exception JspException if a JSP exception occurs.
   * @return {@code true} if and only if all conditions are met.
   */
  protected abstract boolean condition() throws JspException;
}

/*--- Formatted in Sun Java Convention Style on ma, des 1, '03 ---*/

/*------ Formatted by Jindent 3.23 Basic 1.0 --- http://www.jindent.de ------*/


text:
using System;

namespace BetterSteamWebAPIDocumentation.Models
{
    public class ErrorViewModel
    {
        public string RequestId { get; set; }

        public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
    }
}


text:
using Xunit;
using Should;

namespace AutoMapper.UnitTests.Bug
{
    namespace ContextValuesIncorrect
    {
        public class Foo
        {
            public int? Value { get; set; }
            public int? Value2 { get; set; }
        }

        public class FooDto
        {
            public int? Value { get; set; }
            public int? Value2 { get; set; }
        }

        public class When_conditionally_skipping_null_destination_values : AutoMapperSpecBase
        {
            private FooDto _destination;

            protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Foo, FooDto>()
                    .ForAllMembers(opt => opt.Condition((src, p, srvVal, destVal) => destVal == null));
            });

            protected override void Because_of()
            {
                var source = new Foo
                {
                    Value = 3,
                    Value2 = 4
                };
                _destination = new FooDto
                {
                    Value = 5
                };

                Mapper.Map(source, _destination);
            }

            [Fact]
            public void Should_map_the_null_value()
            {
                _destination.Value2.ShouldEqual(4);
            }

            [Fact]
            public void Should_leave_the_non_null_value_alone()
            {
                _destination.Value.ShouldEqual(5);
            }
        }
    }
}


text:
Results for "{{query}}"

        {{magnet.name}}

      submitted {{magnet.createdAt | agoFilter}}


text:
/*
  A ping pong bot, whenever you send "ping", it replies "pong".
*/

// import the discord.js module
const Discord = require('discord.js');

// create an instance of a Discord Client
const client = new Discord.Client();

// the token of your bot - https://discordapp.com/developers/applications/me
const token = 'your bot token here';

// the ready event is vital, it means that your bot will only start reacting to information
// from Discord _after_ ready is emitted.
client.on('ready', () => {
  console.log('I am ready!');
});

// create an event listener for messages
client.on('message', message => {
  // if the message is "ping",
  if (message.content === 'ping') {
    // send "pong" to the same channel.
    message.channel.sendMessage('pong');
  }
});

// log our bot in
client.login(token);


text:
package com.lightcrafts.app;

import static com.lightcrafts.app.Locale.LOCALE;
import com.lightcrafts.ui.toolkit.IconFactory;
import com.lightcrafts.ui.editor.EditorMode;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

final class DoneButton extends EditorButton {

    private final static Icon Icon =
        IconFactory.createInvertedIcon(UndoButton.class, "save.png");

    private final static String ToolTip = LOCALE.get("DoneButtonToolTip");

    DoneButton(final ComboFrame frame) {
        super(frame, Icon);
        setToolTipText(ToolTip);

        addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    frame.getEditor().setMode( EditorMode.ARROW );
                    frame.showBrowserPerspective();
                }
            }
        );
    }
}


text:
Sync [Diigo](https://www.diigo.com) to Evernote with lambda.

# Config
see `serverless.yml`
```
environment:
  EVERNOTE_DEV_TOKEN: undefined
  EVERNOTE_DEV_STORE: undefined
  DIIGO_FETCH_USER: undefined
  DIIGO_API_KEY: undefined
  DIIGO_CREDENTIAL: undefined
```

*evernote dev: https://dev.evernote.com/doc/

*diigo dev: https://www.diigo.com/api_dev

# Deploy
`serverless deploy [--region ap-northeast-1]`

*serverless dev: https://serverless.com/framework/docs/


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

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

import ghidra.app.cmd.disassemble.DisassembleCommand;
import ghidra.app.cmd.function.CreateFunctionCmd;
import ghidra.app.util.importer.MessageLog;
import ghidra.program.database.function.OverlappingFunctionException;
import ghidra.program.model.address.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.symbol.*;
import ghidra.util.exception.CancelledException;
import ghidra.util.task.TaskMonitor;
import ghidra.util.xml.XmlUtilities;
import ghidra.xml.XmlElement;
import ghidra.xml.XmlPullParser;

class ApplyFunctions {

	private ApplyFunctions() {
		// static use only
	}

	/**
	 * Perform parsing and applying of functions
	 * @param pdbParser PDB parser object
	 * @param xmlParser XML parser position immediately after the functions start element
	 * @param monitor task monitor
	 * @param log message log
	 * @throws CancelledException if task cancelled
	 */
	static void applyTo(PdbParser pdbParser, XmlPullParser xmlParser, TaskMonitor monitor,
			MessageLog log) throws CancelledException {
		Program program = pdbParser.getProgram();
		Listing listing = program.getListing();
		while (xmlParser.hasNext()) {
			if (monitor.isCancelled()) {
				return;
			}
			XmlElement child = xmlParser.next();
			if (child.isEnd() && child.getName().equals("functions")) {
				break;
			}

			String name = child.getAttribute("name");
			int addr = XmlUtilities.parseInt(child.getAttribute("address"));

			Address address = PdbUtil.reladdr(program, addr);

			monitor.setMessage("Applying function at " + address + "...");

//TODO handle functions inside jmps (see pdb_test.exe 0x41100a

			Instruction instr = listing.getInstructionAt(address);
			if (instr == null) {
				DisassembleCommand cmd = new DisassembleCommand(address, null, true);
				cmd.applyTo(program, monitor);
			}

			pdbParser.createSymbol(address, name, true, log);

			Function function = listing.getFunctionAt(address);
			if (function == null) {
				function = createFunction(program, address);
			}
			if (function == null) {
				function = checkInsideThunkJump(program, address, monitor);
			}
			if (function == null) {
				function = checkInsideThunkFunction(program, address, monitor);
			}
			if (function == null) {
				xmlParser.discardSubTree(child);
				continue;
			}

			ApplyStackVariables applyStackVariables =
				new ApplyStackVariables(pdbParser, xmlParser, function);
			applyStackVariables.applyTo(monitor, log);

			ApplyLineNumbers applyLineNumbers = new ApplyLineNumbers(pdbParser, xmlParser, program);
			applyLineNumbers.applyTo(monitor, log);

			xmlParser.next();//skip function end element
		}
	}

	private static Function checkInsideThunkFunction(Program program, Address address,
			TaskMonitor monitor) throws CancelledException {
		Listing listing = program.getListing();
		Function thunkFunction = listing.getFunctionContaining(address);
		if (thunkFunction == null) {
			return null;
		}
		if (thunkFunction.getEntryPoint().equals(address)) {
			return null;
		}
		AddressSet thunkBody = new AddressSet(thunkFunction.getBody());
		boolean hasRangeMatch = true;
		AddressRangeIterator ari = thunkBody.getAddressRanges(true);
		while (ari.hasNext()) {
			if (monitor.isCancelled()) {
				throw new CancelledException();
			}
			AddressRange range = ari.next();
			if (range.getMinAddress().equals(address)) {
				hasRangeMatch = true;
				thunkBody.delete(range);
				break;
			}
		}
		if (!hasRangeMatch) {
			return null;
		}
		try {
			thunkFunction.setBody(thunkBody);
		}
		catch (OverlappingFunctionException e) {
			//should never happen...
		}
		Function newFunction = createFunction(program, address);
		thunkFunction.setThunkedFunction(newFunction);
		return newFunction;
	}

	private static Function checkInsideThunkJump(Program program, Address address,
			TaskMonitor monitor) throws CancelledException {
		Listing listing = program.getListing();
		List<Reference> refList = getReferencesTo(program, address, monitor);
		if (refList.size() != 1) {//sanity check...
			return null;
		}
		Address thunkAddress = refList.get(0).getFromAddress();
		Function thunkFunction = listing.getFunctionAt(thunkAddress);
		if (thunkFunction == null) {
			return null;
		}
		Instruction thunkInstr = listing.getInstructionAt(thunkAddress);
		if (thunkInstr.getFlowType().isJump()) {
			AddressSetView newThunkBody =
				new AddressSet(thunkInstr.getMinAddress(), thunkInstr.getMaxAddress());
			try {
				thunkFunction.setBody(newThunkBody);
			}
			catch (OverlappingFunctionException e) {
				//should never happen...
			}
		}
		Function newFunction = createFunction(program, address);
		thunkFunction.setThunkedFunction(newFunction);
		return newFunction;
	}

	private static List<Reference> getReferencesTo(Program program, Address address,
			TaskMonitor monitor) throws CancelledException {
		List<Reference> refList = new ArrayList<>();
		ReferenceManager refMgr = program.getReferenceManager();
		ReferenceIterator refIter = refMgr.getReferencesTo(address);
		while (refIter.hasNext()) {
			if (monitor.isCancelled()) {
				throw new CancelledException();
			}
			refList.add(refIter.next());
		}
		return refList;
	}

	private static Function createFunction(Program program, Address entryPoint) {
		CreateFunctionCmd fCmd = new CreateFunctionCmd(entryPoint);
		fCmd.applyTo(program);
		return program.getListing().getFunctionAt(entryPoint);
	}
}


text:
+++
date = 2017-01-30T21:55:23+08:00
title = "Minimalism -- 极简 Hugo Theme"
categories = ["Programming"]
tags = ["Hugo", "Github Pages"]

[minimalism]
    license = "by-nc-sa/4.0"
+++

最近把静态 Blog 生成工具由之前的 [Hexo](https://hexo.io) 切换到了 [Hugo](https://gohugo.io),
没有特别的原因, 只是因为相对于 nodejs, 更熟悉且更喜欢 golang 一些...

切换过来的同时, 由于没有找到符合自己喜好的主题, 就尝试着自己摸索写了一个:
[Minimalism](https://github.com/cissoid/hugo-theme-minimalism), 使用 flexbox
来解决排版及响应式的问题, 算是我这个前端苦手学习前端开发的第一步.

# 文本
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque venenatis eros ac varius blandit. Nunc pharetra tellus sed tortor imperdiet, pharetra feugiat felis finibus. Cras sit amet elit in nisi euismod congue. Nullam at quam sed sem semper pellentesque. Donec quis purus eu augue ornare venenatis. Ut sed eros nibh. Nullam mi elit, pharetra vel mi mollis, condimentum euismod urna. Pellentesque lorem felis, dapibus a tincidunt eget, rhoncus et diam. In ut metus in orci rhoncus efficitur nec venenatis ipsum.

*Pellentesque eu risus et turpis dapibus congue et interdum metus. Nulla placerat, ante sit amet suscipit fermentum, justo urna tincidunt turpis, ac dignissim eros felis ut nisl. Integer metus metus, consectetur a justo dictum, finibus commodo diam. Nunc maximus nec lectus in semper. Donec libero sapien, convallis eu venenatis ac, vehicula eu justo. Curabitur velit risus, condimentum vel quam ut, pulvinar aliquet purus. Duis consequat massa sit amet dolor suscipit elementum id id tortor. Pellentesque venenatis convallis ipsum eu accumsan. Maecenas a dolor sem.*

**Nam turpis sem, facilisis eu rhoncus nec, mattis vel nunc. Nulla volutpat mauris vitae ipsum accumsan, quis scelerisque arcu volutpat. Suspendisse a ipsum non urna tempus volutpat. Proin interdum pretium mauris sit amet porta. Aliquam erat volutpat. Proin vel neque sem. Praesent tristique sit amet neque ac hendrerit. Sed porttitor, massa ac ultrices efficitur, dui metus consequat dolor, vitae consectetur massa leo eget enim. Nunc eu faucibus ipsum.**

> Sed ut bibendum ipsum, non interdum erat. Fusce in porttitor velit. Nullam vitae elementum felis. Sed nec ultrices est. Nulla facilisis mattis nunc. Quisque leo nisi, pulvinar eget dignissim sit amet, porta vel ante. Phasellus pellentesque ac sem vitae pharetra. Phasellus efficitur sem eu felis euismod commodo eget et risus. Quisque sit amet tincidunt nibh. Nullam fermentum, odio vel venenatis egestas, risus tellus fermentum purus, eu accumsan massa velit quis est. Vestibulum sit amet sapien orci.

# 图片
![](https://images.unsplash.com/photo-1488764619428-8fc2aaf23eba)

# 列表
1. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
2. Mauris at libero convallis, tempus risus eu, malesuada urna.
3. In eu est ullamcorper, egestas metus sed, convallis neque.
4. Sed a dolor semper orci rutrum blandit ac vel nisi.
5. Praesent eget felis sit amet quam fringilla sodales ac a purus.

- Quisque fringilla nisi sed ipsum porta facilisis.
- Vestibulum sollicitudin purus at tempor aliquet.
- Morbi a nisi vel sapien gravida facilisis.
- Donec posuere sem ut enim pretium luctus.
- Donec ac mi fermentum, hendrerit libero et, egestas lacus.

# Checklist
- [x] [links](http://www.baidu.com), **formatting**, and tags supported
- [x] list syntax required (any unordered or ordered list supported)
- [x] this is a complete item
- [ ] this is an incomplete item

# 代码
I think you should use an `<addr>` element here instead.

Press Ctrl + C.

``` python
#!/usr/bin/env python
# coding: utf-8

def main():
    print('Hello World')

if __name__ == '__main__':
    main()
```

# 表格
| First Header                | Second Header                |
|:---------------------------:|:----------------------------:|
| Content from cell 1         | Content from cell 2          |
| Content in the first column | Content in the second column |


text:
-	[`1.7.5-python2`, `1.7-python2`, `1-python2`, `python2` (*2.7/Dockerfile*)](https://github.com/docker-library/django/blob/c8c5306033e9141babdb49008be4529261245091/2.7/Dockerfile)
-	[`python2-onbuild` (*2.7/onbuild/Dockerfile*)](https://github.com/docker-library/django/blob/a3ae98081865ff8aab7524c98318568c32828ed1/2.7/onbuild/Dockerfile)
-	[`1.7.5-python3`, `1.7.5`, `1.7-python3`, `1.7`, `1-python3`, `1`, `python3`, `latest` (*3.4/Dockerfile*)](https://github.com/docker-library/django/blob/bbafaaab189c626ae85dc7fae60b7c589e8783e6/3.4/Dockerfile)
-	[`python3-onbuild`, `onbuild` (*3.4/onbuild/Dockerfile*)](https://github.com/docker-library/django/blob/bbafaaab189c626ae85dc7fae60b7c589e8783e6/3.4/onbuild/Dockerfile)

For more information about this image and its history, please see the [relevant manifest file (`library/django`)](https://github.com/docker-library/official-images/blob/master/library/django) in the [`docker-library/official-images` GitHub repo](https://github.com/docker-library/official-images).

# What is Django?

Django is a free and open source web application framework, written in Python, which follows the model-view-controller architectural pattern. Django's primary goal is to ease the creation of complex, database-driven websites with an emphasis on reusability and "pluggability" of components.

> [wikipedia.org/wiki/Django_(web_framework)](https://en.wikipedia.org/wiki/Django_%28web_framework%29)

![logo](https://raw.githubusercontent.com/docker-library/docs/master/django/logo.png)

# How to use this image

## Create a `Dockerfile` in your Django app project

	FROM django:onbuild

Put this file in the root of your app, next to the `requirements.txt`.

This image includes multiple `ONBUILD` triggers which should cover most applications. The build will `COPY . /usr/src/app`, `RUN pip install`, `EXPOSE 8000`, and set the default command to `python manage.py runserver`.

You can then build and run the Docker image:

	docker build -t my-django-app .
	docker run --name some-django-app -d my-django-app

You can test it by visiting `http://container-ip:8000` in a browser or, if you need access outside the host, on `http://localhost:8000` with the following command:

	docker run --name some-django-app -p 8000:8000 -d my-django-app

## Without a `Dockerfile`

Of course, if you don't want to take advantage of magical and convenient `ONBUILD` triggers, you can always just use `docker run` directly to avoid having to add a `Dockerfile` to your project.

	docker run --name some-django-app -v "$PWD":/usr/src/app -w /usr/src/app -p 8000:8000 -d django bash -c "pip install -r requirements.txt && python manage.py runserver 0.0.0.0:8000"

## Bootstrap a new Django Application

If you want to generate the scaffolding for a new Django project, you can do the following:

	docker run -it --rm --user "$(id -u):$(id -g)" -v "$PWD":/usr/src/app -w /usr/src/app django django-admin.py startproject mysite

This will create a sub-directory named `mysite` inside your current directory.

# License

View [license information](https://github.com/django/django/blob/master/LICENSE) for the software contained in this image.

# Supported Docker versions

This image is officially supported on Docker version 1.5.0.

Support for older versions (down to 1.0) is provided on a best-effort basis.

# User Feedback

## Issues

If you have any problems with or questions about this image, please contact us through a [GitHub issue](https://github.com/docker-library/django/issues).

You can also reach many of the official image maintainers via the `#docker-library` IRC channel on [Freenode](https://freenode.net).

## Contributing

You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can.

Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/docker-library/django/issues), especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing.


text:
package io.smalldata.ohmageomh.dpu.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.smalldata.ohmageomh.data.domain.EndUser;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.stream.Collectors;

/**
 * @author Jared Sieling.
 */
@Service
public class OmhShimService {

    private static final Logger log = LoggerFactory.getLogger(OmhShimService.class);

    private
    @Value("${omh.shim.fakedata}") Boolean useFakeData = false;

    private
    @Value("${omh.shim.url}") String shimUrl;

    @Autowired
    ObjectMapper objectMapper;

    public String getDataAsString(EndUser user, String shim, String endpoint, Boolean normalize, LocalDate startDate, LocalDate endDate) {
        if (!useFakeData) {
            HttpClient client = HttpClients.createDefault();
            UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(shimUrl)
                    .pathSegment("data", shim, endpoint)
                    .queryParam("username", user.getUsername())
                    .queryParam("normalize", normalize.toString())
                    .queryParam("dateStart", startDate.format(DateTimeFormatter.ISO_LOCAL_DATE))
                    .queryParam("dateEnd", endDate.format(DateTimeFormatter.ISO_LOCAL_DATE));

            URI shimDataUrl = uriBuilder.build().toUri();

            HttpGet shimRequest = new HttpGet(shimDataUrl);
            shimRequest.setHeader("Accept", "application/json");

            try {
                HttpResponse response = client.execute(shimRequest);
                String responseString = new BasicResponseHandler().handleResponse(response);

                return responseString;
            } catch (Exception ex) {
                return null;
            }

        } else {
            File file = new File("sample-data/omh-" + shim + "-" + endpoint + "-" + normalize.toString() + ".json");
            try {
                BufferedReader bR = new BufferedReader(  new FileReader(file));
                String responseString = bR.lines().collect(Collectors.joining(""));
                return responseString;
            } catch (Exception ex) {
                return null;
            }
        }
    }

    public JsonNode getDataAsJsonNode(EndUser user, String shim, String endpoint, Boolean normalize, LocalDate startDate, LocalDate endDate) throws IOException {
        String responseString = getDataAsString(user, shim, endpoint, normalize, startDate, endDate);
        JsonNode responseRoot = objectMapper.readTree(responseString);

        return responseRoot;
    }

}


text:
{% extends "users/base.html" %}
{% set title = _("{user} | Subscriptions")|f(user=display_name(user)) %}
{% set canonical_url = canonicalize(viewname="users.subscriptions", username=user.username) %}
{% set active = "user-subscriptions" %}

{% block content %}

      {{ _("My Subscriptions") }}

    {% for product in products %}

              {{ _('{product}')|fe(product=pgettext('DB: products.Product.title', product.title)) }}

            {{ _('Manage Subscriptions') }}

    {% endfor %}

{% endblock %}


text:
class PagesController < ApplicationController
  def bootstrap; end

  def custom; end

  def foundation; end
end


text:
/*
Package rest is a RESTful web-service framework. It make struct method to http.Handler automatically.
*/
package rest


text:
"""
Copyright (c) 2016 Jet Propulsion Laboratory,
California Institute of Technology.  All rights reserved
"""

import ConfigParser
import logging
import uuid
from datetime import datetime

import numpy as np
import pkg_resources
from cassandra.cluster import Cluster
from cassandra.policies import TokenAwarePolicy, DCAwareRoundRobinPolicy
from cassandra.query import BatchStatement
from pytz import UTC

class AbstractResultsContainer:
    def __init__(self):
        self._log = logging.getLogger(__name__)
        self._log.info("Creating DOMS Results Storage Instance")

        self._session = None

    def __enter__(self):
        domsconfig = ConfigParser.RawConfigParser()
        domsconfig.readfp(pkg_resources.resource_stream(__name__, "domsconfig.ini"), filename='domsconfig.ini')

        cassHost = domsconfig.get("cassandra", "host")
        cassKeyspace = domsconfig.get("cassandra", "keyspace")
        cassDatacenter = domsconfig.get("cassandra", "local_datacenter")
        cassVersion = int(domsconfig.get("cassandra", "protocol_version"))

        dc_policy = DCAwareRoundRobinPolicy(cassDatacenter)
        token_policy = TokenAwarePolicy(dc_policy)

        self._cluster = Cluster([host for host in cassHost.split(',')], load_balancing_policy=token_policy,
                                protocol_version=cassVersion)

        self._session = self._cluster.connect(cassKeyspace)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._cluster.shutdown()

    def _parseDatetime(self, dtString):
        dt = datetime.strptime(dtString, "%Y-%m-%dT%H:%M:%SZ")
        epoch = datetime.utcfromtimestamp(0)
        time = (dt - epoch).total_seconds() * 1000.0
        return int(time)

class ResultsStorage(AbstractResultsContainer):
    def __init__(self):
        AbstractResultsContainer.__init__(self)

    def insertResults(self, results, params, stats, startTime, completeTime, userEmail, execution_id=None):
        if isinstance(execution_id, basestring):
            execution_id = uuid.UUID(execution_id)

        execution_id = self.insertExecution(execution_id, startTime, completeTime, userEmail)
        self.__insertParams(execution_id, params)
        self.__insertStats(execution_id, stats)
        self.__insertResults(execution_id, results)
        return execution_id

    def insertExecution(self, execution_id, startTime, completeTime, userEmail):
        if execution_id is None:
            execution_id = uuid.uuid4()

        cql = "INSERT INTO doms_executions (id, time_started, time_completed, user_email) VALUES (%s, %s, %s, %s)"
        self._session.execute(cql, (execution_id, startTime, completeTime, userEmail))
        return execution_id

    def __insertParams(self, execution_id, params):
        cql = """INSERT INTO doms_params
                    (execution_id, primary_dataset, matchup_datasets, depth_min, depth_max, time_tolerance, radius_tolerance, start_time, end_time, platforms, bounding_box, parameter)
                 VALUES
                    (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
        """
        self._session.execute(cql, (execution_id,
                                    params["primary"],
                                    ",".join(params["matchup"]) if type(params["matchup"]) == list else params[
                                        "matchup"],
                                    params["depthMin"] if "depthMin" in params.keys() else None,
                                    params["depthMax"] if "depthMax" in params.keys() else None,
                                    int(params["timeTolerance"]),
                                    params["radiusTolerance"],
                                    params["startTime"],
                                    params["endTime"],
                                    params["platforms"],
                                    params["bbox"],
                                    params["parameter"]
                                    ))

    def __insertStats(self, execution_id, stats):
        cql = """
           INSERT INTO doms_execution_stats
                (execution_id, num_gridded_matched, num_gridded_checked, num_insitu_matched, num_insitu_checked, time_to_complete)
           VALUES
                (%s, %s, %s, %s, %s, %s)
        """
        self._session.execute(cql, (
            execution_id,
            stats["numGriddedMatched"],
            stats["numGriddedChecked"],
            stats["numInSituMatched"],
            stats["numInSituRecords"],
            stats["timeToComplete"]
        ))

    def __insertResults(self, execution_id, results):

        cql = """
           INSERT INTO doms_data
                (id, execution_id, value_id, primary_value_id, x, y, source_dataset, measurement_time, platform, device, measurement_values, is_primary)
           VALUES
                (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """
        insertStatement = self._session.prepare(cql)
        batch = BatchStatement()

        for result in results:
            self.__insertResult(execution_id, None, result, batch, insertStatement)

        self._session.execute(batch)

    def __insertResult(self, execution_id, primaryId, result, batch, insertStatement):

        dataMap = self.__buildDataMap(result)
        result_id = uuid.uuid4()
        batch.add(insertStatement, (
            result_id,
            execution_id,
            result["id"],
            primaryId,
            result["x"],
            result["y"],
            result["source"],
            result["time"],
            result["platform"] if "platform" in result else None,
            result["device"] if "device" in result else None,
            dataMap,
            1 if primaryId is None else 0
        )
                  )

        n = 0
        if "matches" in result:
            for match in result["matches"]:
                self.__insertResult(execution_id, result["id"], match, batch, insertStatement)
                n += 1
                if n >= 20:
                    if primaryId is None:
                        self.__commitBatch(batch)
                    n = 0

        if primaryId is None:
            self.__commitBatch(batch)

    def __commitBatch(self, batch):
        self._session.execute(batch)
        batch.clear()

    def __buildDataMap(self, result):
        dataMap = {}
        for name in result:
            value = result[name]
            if name not in ["id", "x", "y", "source", "time", "platform", "device", "point", "matches"] and type(
                    value) in [float, int]:
                dataMap[name] = value
        return dataMap

class ResultsRetrieval(AbstractResultsContainer):
    def __init__(self):
        AbstractResultsContainer.__init__(self)

    def retrieveResults(self, execution_id, trim_data=False):
        if isinstance(execution_id, basestring):
            execution_id = uuid.UUID(execution_id)

        params = self.__retrieveParams(execution_id)
        stats = self.__retrieveStats(execution_id)
        data = self.__retrieveData(execution_id, trim_data=trim_data)
        return params, stats, data

    def __retrieveData(self, id, trim_data=False):
        dataMap = self.__retrievePrimaryData(id, trim_data=trim_data)
        self.__enrichPrimaryDataWithMatches(id, dataMap, trim_data=trim_data)
        data = [dataMap[name] for name in dataMap]
        return data

    def __enrichPrimaryDataWithMatches(self, id, dataMap, trim_data=False):
        cql = "SELECT * FROM doms_data where execution_id = %s and is_primary = false"
        rows = self._session.execute(cql, (id,))

        for row in rows:
            entry = self.__rowToDataEntry(row, trim_data=trim_data)
            if row.primary_value_id in dataMap:
                if not "matches" in dataMap[row.primary_value_id]:
                    dataMap[row.primary_value_id]["matches"] = []
                dataMap[row.primary_value_id]["matches"].append(entry)
            else:
                print row

    def __retrievePrimaryData(self, id, trim_data=False):
        cql = "SELECT * FROM doms_data where execution_id = %s and is_primary = true"
        rows = self._session.execute(cql, (id,))

        dataMap = {}
        for row in rows:
            entry = self.__rowToDataEntry(row, trim_data=trim_data)
            dataMap[row.value_id] = entry
        return dataMap

    def __rowToDataEntry(self, row, trim_data=False):
        if trim_data:
            entry = {
                "x": float(row.x),
                "y": float(row.y),
                "source": row.source_dataset,
                "time": row.measurement_time.replace(tzinfo=UTC)
            }
        else:
            entry = {
                "id": row.value_id,
                "x": float(row.x),
                "y": float(row.y),
                "source": row.source_dataset,
                "device": row.device,
                "platform": row.platform,
                "time": row.measurement_time.replace(tzinfo=UTC)
            }
        for key in row.measurement_values:
            value = float(row.measurement_values[key])
            entry[key] = value
        return entry

    def __retrieveStats(self, id):
        cql = "SELECT * FROM doms_execution_stats where execution_id = %s limit 1"
        rows = self._session.execute(cql, (id,))
        for row in rows:
            stats = {
                "numGriddedMatched": row.num_gridded_matched,
                "numGriddedChecked": row.num_gridded_checked,
                "numInSituMatched": row.num_insitu_matched,
                "numInSituChecked": row.num_insitu_checked,
                "timeToComplete": row.time_to_complete
            }
            return stats

        raise Exception("Execution not found with id '%s'" % id)

    def __retrieveParams(self, id):
        cql = "SELECT * FROM doms_params where execution_id = %s limit 1"
        rows = self._session.execute(cql, (id,))
        for row in rows:
            params = {
                "primary": row.primary_dataset,
                "matchup": row.matchup_datasets.split(","),
                "depthMin": row.depth_min,
                "depthMax": row.depth_max,
                "timeTolerance": row.time_tolerance,
                "radiusTolerance": row.radius_tolerance,
                "startTime": row.start_time.replace(tzinfo=UTC),
                "endTime": row.end_time.replace(tzinfo=UTC),
                "platforms": row.platforms,
                "bbox": row.bounding_box,
                "parameter": row.parameter
            }
            return params

        raise Exception("Execution not found with id '%s'" % id)