text:
<?php

include '../connection.php';

try {
    $key = $_POST['key'];
    $value = $_POST['value'];

    // first read the config table to see if a config already exists for this key
    $statement = $db->prepare("select value from config where key = '$key'");
    if(!$statement->execute()) {
        throw new Exception(implode(', ', $statement->errorInfo()));
    }
    if(!$statement->fetch(PDO::FETCH_COLUMN)) {
        $sql = "insert into config (key, value) values('$key', '$value')";
    } else {
        $sql = "update config set value = '$value' where key = '$key'";
    }

    $statement = $db->prepare($sql);
    if(!$statement->execute()) {
        throw new Exception(implode(', ', $statement->errorInfo()));
    }
    $jsonResult = array('success' => true);
} catch(Exception $e) {
    $jsonResult = array(
        'success' => false,
        'message' => $e->getMessage()
    );
}

echo json_encode($jsonResult);

?>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Teamer.Pages
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class LiderPage : Page
    {
        public LiderPage()
        {
            this.InitializeComponent();
        }

        private void SendTask(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(MainTaskPage));

        }
        public void GoBack(object sender, RoutedEventArgs args)
        {
            if (this.Frame.CanGoBack)
            {
                this.Frame.GoBack();
            }
        }

        private void GotoMyAccount(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(AccountPage));

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import hyphenate from "./hyphenate";
import isTransform from "./isTransform";
import transitionProps from "./transitionProps";
import directStyle from "./directStyle";
import { addEventListener, removeEventListener } from "./simpleEventListener";

const reset = {};
reset[transitionProps.property] = reset[transitionProps.duration] = reset[
  transitionProps.delay
] = reset[transitionProps.timing] = "";

function animate({ node, properties, duration = 200, easing, callback }) {
  const cssProperties = [];
  const fakeEvent = { target: node, currentTarget: node };
  const cssValues = {};
  let transforms = "";
  let fired;

  if (!transitionProps.end) {
    duration = 0;
  }

  Object.keys(properties).forEach(key => {
    if (isTransform(key)) {
      transforms += `${key}(${properties[key]}) `;
    } else {
      cssValues[key] = properties[key];
      cssProperties.push(hyphenate(key));
    }
  });

  if (transforms) {
    cssValues[transitionProps.transform] = transforms;
    cssProperties.push(transitionProps.transform);
  }

  if (duration > 0) {
    cssValues[transitionProps.property] = cssProperties.join(", ");
    cssValues[transitionProps.duration] = duration / 1000 + "s";
    cssValues[transitionProps.delay] = 0 + "s";
    cssValues[transitionProps.timing] = easing || "linear";

    addEventListener(node, transitionProps.end, done);

    setTimeout(() => {
      if (!fired) done(fakeEvent);
    }, duration + 500);
  }

  node.clientLeft; // trigger page reflow

  directStyle(node, cssValues);

  if (duration <= 0) {
    setTimeout(done.bind(null, fakeEvent), 0);
  }

  return {
    cancel() {
      if (fired) return;
      fired = true;
      removeEventListener(node, transitionProps.end, done);
      directStyle(node, reset);
    }
  };

  function done(event) {
    if (event.target !== event.currentTarget) return;

    fired = true;
    removeEventListener(event.target, transitionProps.end, done);
    directStyle(node, reset);
    callback && callback.call(this);
  }
}

function transitionAnimate(node, properties, duration, easing, callback) {
  if (arguments.length === 1 && typeof node === "object") {
    return animate(node);
  }

  if (typeof easing === "function") {
    callback = easing;
    easing = null;
  }

  return animate({ node, properties, duration, easing, callback });
}

export default transitionAnimate;


text:
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Connector.Utilities;
using Newtonsoft.Json;

namespace Stock_LUIS
{
    [BotAuthentication]
    public class MessagesController : ApiController
    {
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task<Message> Post([FromBody]Message message)
        {
            if (message.Type == "Message")
            {
                bool bSetStock = false;
                StockLUIS stLuis = await LUISStockClient.ParseUserInput(message.Text);
                string strRet = string.Empty;
                string strStock = message.Text;

                if (stLuis.intents.Count() > 0)
                {
                    switch (stLuis.intents[0].intent)
                    {
                        case "RepeatLastStock":
                            strStock = message.GetBotUserData<string>("LastStock");
                            if (null == strStock)
                            {
                                strRet = "I don't have a previous stock to look up!";
                            }
                            else
                            {
                                strRet = await GetStock(strStock);
                            }
                            break;
                        case "StockPrice":
                            bSetStock = true;
                            strRet = await GetStock(stLuis.entities[0].entity);
                            break;
                        default:
                            break;
                    }
                }
                else
                {
                    strRet = "Sorry, I don't understand...";
                }

                Message ReplyMessage = message.CreateReplyMessage(strRet);
                if (bSetStock)
                {
                    ReplyMessage.SetBotUserData("LastStock", stLuis.entities[0].entity);
                }
                return ReplyMessage;
            }
            else
            {
                return HandleSystemMessage(message);
            }
        }

        private async Task<string> GetStock(string strStock)
        {
            string strRet = string.Empty;
            double? dblStock = await Yahoo.GetStockPriceAsync(strStock);
            // return our reply to the user
            if (null == dblStock)
            {
                strRet = string.Format("Stock {0} doesn't appear to be valid", strStock.ToUpper());
            }
            else
            {
                strRet = string.Format("Stock: {0}, Value: {1}", strStock.ToUpper(), dblStock);
            }

            return strRet;
        }

        private Message HandleSystemMessage(Message message)
        {
            if (message.Type == "Ping")
            {
                Message reply = message.CreateReplyMessage();
                reply.Type = "Ping";
                return reply;
            }
            else if (message.Type == "DeleteUserData")
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == "BotAddedToConversation")
            {
            }
            else if (message.Type == "BotRemovedFromConversation")
            {
            }
            else if (message.Type == "UserAddedToConversation")
            {
            }
            else if (message.Type == "UserRemovedFromConversation")
            {
            }
            else if (message.Type == "EndOfConversation")
            {
            }

            return null;
        }
    }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
    <title>Responsive design</title>
    <link rel="stylesheet" href="../bower_components/reveal.js/css/reveal.min.css">
		<link rel="stylesheet" href="../styles/main.min.css" id="theme">

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

Responsive Design

What is Responsive Design?

The theory and practice of crafting websites that allow the user to enjoy its features no matter what device they are using.

Responsive terms

media queries

flexible images

fluid grids

breakpoints

Media queries

@media

Determines the screen size we want to target our styles to.

Media queries

Start with our default styles.

aside {
  width: 100%;
  text-align: center;
}

Create the styles we want to appear within a particular screen size.

@media screen and (max-width: 320px) {
  aside {
    width: 30%;
    text-align: left;
    float: right;
  }
}

Breakpoints

Everytime the design starts to break, it's time for a new media query.

Don't Forget!

There is a <meta> tag created by Apple to control zooming effects.

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

CSS for certain situations

Rather than looking for a type of device they look at the capability of the device, and you can use them to check for all kinds of things.

width and height of the viewport

device width and height

orientation (landscape or portrait)

resolution

Examples of responsive websites

Smashing Magazine

The Boston Globe

Starbucks

A List Apart

Ask students if they have any more examples.

How do I test on various devices without the device?

Just resize the browser for the most important media queries. Chrome has an emulator built in! Open up the Developer Tools, show the drawer, and select the "Emulation" tab.

Responsive design is disruptive

Before you can embrace Responsive, you have to update your processes. It also means educating clients and (for some) resetting their expectation that websites should look the same in every browser, on every device.

In support of responsive

With disruption comes new tools and new ways of thinking.

Wireframing

Lots of wireframing software such as Balsamiq now offer a plethora of responsive-capable tools.

Designing

New ways of presenting designs are also popping up,

						such as style tiles. The style tile to the left was

						turned into the website on the right.

Multiple screen sizes

This is the idea that there shouldn't be a mobile web and a tablet web and desktop web. We should assume that people will try to view a website on whatever device they have with them.

Our users love their devices, and it's not their fault they've been given 1 billion to choose from!

Media query support

The current versions of all major browsers support media queries. There will always be someone who is, for whatever reason, using an older browser.

No support

Internet Explorer 8 and below

Safari 3.2 and below

More information on browser support

At least most of us aren't coding for IE6 anymore!

Still need support for older browsers?

There's a Javascript library for that!

Modernizer

Respond.js

Use these only if you absolutely need to support older browsers. They're performance hogs.

Mobile first?

          What it means is, instead of offering "lighter" content or a seemingly restrictive experience to those viewing your site on a mobile device, stop. Regroup. Plan your site out thoughtfully enough that your content is already concise and simplified to begin with. Thinking "Mobile First" helps you accomplish this while you transition to Responsive Design. - Luke Wroblewski

Just a fad?

Responsive is not a fad, as it addresses a real

            need for planning our sites thoughtfully.

Elements of responsive design may be fads. Hamburger icon, menu slide down, etc.

A replacement for mobile apps?

Responsive is not a replacement for mobile apps. Responsive can save companies time and money by allowing for the development and maintenance of one set of code, but only if it's the appropriate solution.

When might you want an app rather than a website?

WEEKEND HOMEWORK

Continue work on desktop version of Surf + Paddle.

Create a 320px breakpoint for the Surf + Paddle website, PDF provided.

Read through Responsive Web Design.


text:
import { EventEmitter } from 'events'
import { Message, JSONObject } from '../../constants'
import { SocketWrapper } from '@deepstream/types'
const sinon = require('sinon')

export const getTestMocks = () => {

  const subscriptionRegistry = {
    subscribe: () => {},
    unsubscribe: () => {},
    sendToSubscribers: () => {},
    setSubscriptionListener: () => {},
    getLocalSubscribers: () => new Set(),
    getAllRemoteServers: () => {},
    setAction: () => {},
    hasLocalSubscribers: () => true,
    subscribeBulk: () => {},
    unsubscribeBulk: () => {}
  }

  const listenerRegistry = {
    handle: () => {}
  }

  const emitter = new EventEmitter()
  const stateRegistry = {
    add: () => {},
    remove: () => {},
    on: () => {},
    emit: () => {},
    getAll: () => {},
    onAdd: () => {},
    onRemove: () => {}
  }
  stateRegistry.on = emitter.on as any
  stateRegistry.emit = emitter.emit as any

  const recordHandler = {
    broadcastUpdate: () => {},
    transitionComplete: () => {}
  }

  const subscriptionRegistryMock = sinon.mock(subscriptionRegistry)
  const listenerRegistryMock = sinon.mock(listenerRegistry)
  const stateRegistryMock = sinon.mock(stateRegistry)
  const recordHandlerMock = sinon.mock(recordHandler)

  function getSocketWrapper (userId: string, authData: JSONObject = {}, clientData: JSONObject = {}) {
    const socketWrapper = {
      authAttempts: 0,
      userId,
      authData,
      clientData,
      sendMessage: () => {},
      sendBuiltMessage: () => {},
      sendAckMessage: () => {},
      uuid: Math.random(),
      parseData: (message: Message) => {
        if (message.parsedData) {
          return true
        }
        try {
          message.parsedData = JSON.parse(message.data!.toString())
          return true
        } catch (e) {
          return e
        }
      },
      getMessage: (message: Message) => message,
      parseMessage: (message: Message) => message,
      destroy: () => {},
      getHandshakeData: () => ({}),
      close: () => {},
      onClose: () => {},
      removeOnClose: () => {}
    } as never as SocketWrapper

    return {
      socketWrapper,
      socketWrapperMock: sinon.mock(socketWrapper)
    }
  }

  return {
    subscriptionRegistry,
    listenerRegistry,
    stateRegistry,
    recordHandler,
    subscriptionRegistryMock,
    listenerRegistryMock,
    stateRegistryMock,
    recordHandlerMock,
    getSocketWrapper,
  }
}


text:
package com.thoughtworks.gauge.example.pages;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class CustomerPage extends BasePage {
    public static String CustomerUrl = Url.concat("admin/customers/");

    public WebElement q_username;

    public WebElement q_submit;

    @FindBy(how= How.CSS, css = "table#customers tbody tr:nth-child(1) td.username")
    public WebElement usernameResult;

    public void searchUser(String username) {
        q_username.clear();
        q_username.sendKeys(username);
        q_submit.click();
    }

    public void verifyUserListed(String username) {
        Assert.assertTrue(usernameResult.getText().equals(username));
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Mycena rubiaetincta Berk.

### Remarks
null


text:
package com.philips.microservices.core.patient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@EnableDiscoveryClient
@ComponentScan({"com.philips.microservices.core.patient", "com.philips.microservices.util"})
public class PatientServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(PatientServiceApplication.class, args);
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta content="App Inventor for Android" name="description" />
  <meta content="Android, Blocks App Inventor, Mobile, Phone, IDE" name="keywords" />
  <title>
   Bookstore - App Inventor for Android
  </title>
  <link href="/static/images/appinventor-16.png" rel="SHORTCUT ICON" type="image/ico" />
  <link href="/static/images/appinventor-16.png" rel="icon" type="image/png" />
  <link href="/static/css/appinventor.css" rel="stylesheet" />

        Bookstore


text:
define(['services/unitofwork'],
    function (uow) {

        var session = {
            isLoggedIn: ko.observable(false),
            unitofwork: ko.observable(),
            userName: ko.observable(undefined),

            clearUser: clearUser,
            initUnitOfWork: initUnitOfWork,
            setUser: setUser,
            userIsInRole: userIsInRole,
            userRoles: ko.observableArray(),
        };

        return session;

        function setUser(user) {
            if (user) {

                session.userName(user.userName);

                var roles = user.userRoles.split(",");

                $.each(roles, function (i, v) {
                    session.userRoles.push(v);
                });

                session.isLoggedIn(true);
            }
        }

        function clearUser() {
            session.userName('');
            session.userRoles.removeAll();
            session.isLoggedIn(false);
        }

        function userIsInRole(requiredRole) {
            if (requiredRole === undefined) {
                return true;
            } else if (session.userRoles() === undefined) {
                return false;
            } else {
                if ($.isArray(requiredRole)) {
                    if (requiredRole.length === 0) {
                        return true;
                    } else {
                        return $.arrayIntersect(
                            session.userRoles(), requiredRole).length > 0;
                    }
                } else {
                    return $.inArray(requiredRole, session.userRoles()) > -1;
                }
            }
        }

        function initUnitOfWork() {
            session.unitofwork(uow.create());
        }
    });


text:
package com.guhanjie.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

public final class HttpUtil {

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

	private static String SCHEMA_HTTPS = "https";
	private static String SCHEMA_HTTP = "http";

	public static String getCookieValueByName(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		if(cookies != null && name != null) {
			for(Cookie cookie : cookies) {
				if(name.equals(cookie.getName())) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}

    /**
     * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址;
     *
     * @param request
     * @return
     * @throws IOException
     */
    public final static String getIpAddress(HttpServletRequest request) {
        // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
        String ip = request.getHeader("X-Forwarded-For");
        LOGGER.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=[{}]", ip);
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
                LOGGER.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=[{}]", ip);
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
                LOGGER.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=[{}]", ip);
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
                LOGGER.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=[{}]", ip);
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
                LOGGER.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=[{}]", ip);
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                LOGGER.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=[{}]", ip);
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }

    public static int getResponseCode(String url) throws IOException {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpclient.execute(httpGet);
            return response.getStatusLine().getStatusCode();
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

    public static String getRequestBody(HttpServletRequest request, String charsetName) throws ServletException {
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request);
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            InputStream inputStream = requestWrapper.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, charsetName));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) != -1) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }
        } catch (IOException ex) {
            throw new ServletException("Error reading the request payload", ex);
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException iox) {
                    // ignore
                }
            }
        }
        return stringBuilder.toString();
    }

    public static HttpResponse sendDelete(String url) throws IOException {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpDelete httpDelete = new HttpDelete(url);
            return httpclient.execute(httpDelete);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

    public static HttpResponse sendDelete(String url, String username, String password) throws IOException {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpDelete httpDelete = new HttpDelete(url);
            String s = username + ":" + password;
            String basicHeader = "Basic " + Base64.encodeBase64String(s.getBytes());
            httpDelete.setHeader(HttpHeaders.AUTHORIZATION, basicHeader);
            return httpclient.execute(httpDelete);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
    }

    public static boolean isMultiPartRequest(HttpServletRequest request) {
        return request.getHeader(HTTP.CONTENT_TYPE) != null && request.getHeader(HTTP.CONTENT_TYPE).contains("multipart/form-data");
    }

    public static String encodeUTF8(String str) {
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            return str;
        }
    }

    public static String decodeUTF8(String str) {
        try {
            return URLDecoder.decode(str, "UTF-8");
        } catch (Exception e) {
            return str;
        }
    }

	/**
	 * 如果url不是以https开头,需要修改成request.getScheme()开头
	 *
	 * @param request
	 * @param url
	 * @return
	 */
	public static String schema(HttpServletRequest request, String url){
		if(url == null){
			return null;
		}
		String scheme = request.getScheme();
		if(url.startsWith(SCHEMA_HTTPS)){
			return url;
		}else if(url.startsWith(SCHEMA_HTTP)){
			if(SCHEMA_HTTPS.equalsIgnoreCase(scheme)){
				return SCHEMA_HTTPS + url.substring(4);
			}else{
				return url;
			}
		}else{
			return scheme + "://" + url;
		}
	}
}


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150324_273210_alter_table__cms_infoblock_2 extends Migration
{
    public function up()
    {
        $this->execute("ALTER TABLE {{%cms_infoblock%}} ADD `protected_widget_params` TEXT NULL;");
    }

    public function down()
    {
        echo "m150324_273210_alter_table__cms_infoblock_2 cannot be reverted.\n";
        return false;
    }
}


text:
package com.resttest.framework;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by sreepadbhagwat on 9/10/16.
 */
public class RestTest {

    RestDriver driver;
    final Logger logger = Logger.getLogger(RestTest.class);

public RestTest() {
    logger.info("Inside RestTest constructor");
     driver = new RestDriver();

}

    public void ExecuteJsonScripts(Map<String, String> capabilities){
        try {
            logger.info("Inside ExecuteJsonScripts method");
            driver.executeScripts(capabilities);

        } catch (IOException e) {
            logger.error("Inside ExecuteJsonScripts catch block"+e);
        }

    }

}


text:
<?php

namespace ZF2rapid\Task\RemoveConfig;

/**
 * Class RemoveValidatorConfig
 *
 * @package ZF2rapid\Task\RemoveConfig
 */
class RemoveValidatorConfig extends AbstractRemoveServiceManagerConfig
{
    /**
     * Process the command
     *
     * @return integer
     */
    public function processCommandTask()
    {
        // output message
        $this->console->writeTaskLine(
            'Writing validator configuration...'
        );

        $configKey = lcfirst($this->params->paramModule)
            . $this->params->paramValidator;

        $result = $this->removeConfig(
            'validators',
            $configKey
        );

        return $result == true ? 0 : 1;
    }
}


text:
package com.learning.problems.vehicleparking.model;

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

public class ParkingLocation {
    private String LocationId;
    private String locationAddress;
    private String postcode;
    private List<ParkingZone> parkingZones;

    public ParkingLocation() {
        parkingZones = new ArrayList<>();
    }

    public ParkingLocation(String locationId, String locationAddress, String postcode) {
        this.LocationId = locationId;
        this.locationAddress = locationAddress;
        this.postcode = postcode;
        this.parkingZones = new ArrayList<>();
        }

    public String getLocationId() {
        return LocationId;
    }

    public void setLocationId(String locationId) {
        LocationId = locationId;
    }

    public String getLocationAddress() {
        return locationAddress;
    }

    public void setLocationAddress(String locationAddress) {
        this.locationAddress = locationAddress;
    }

    public String getPostcode() {
        return postcode;
    }

    public void setPostcode(String postcode) {
        this.postcode = postcode;
    }

    public List<ParkingZone> getParkingZones() {
        return parkingZones;
    }

    public void setParkingZones(List<ParkingZone> parkingZones) {
        this.parkingZones = parkingZones;
    }

    public void addparkingZone(ParkingZone parkingZone){
        this.parkingZones.add(parkingZone);
    }
}


text:
class TouchFeeds
  include Sidekiq::Worker

  def perform(host)
    Feed.where(host: host).select(:id).find_in_batches do |feeds|
      Feed.where(id: feeds.map(&:id)).update_all(updated_at: Time.now)
    end
  end
end


text:
package org.apache.spark.deploy.master

import org.apache.spark.Logging
import org.apache.zookeeper._

import akka.serialization.Serialization

class ZooKeeperPersistenceEngine(serialization: Serialization)
  extends PersistenceEngine
  with SparkZooKeeperWatcher
  with Logging
{
  val WORKING_DIR = System.getProperty("spark.deploy.zookeeper.dir", "/spark") + "/master_status"

  val zk = new SparkZooKeeperSession(this)

  zk.connect()

  override def zkSessionCreated() {
    zk.mkdirRecursive(WORKING_DIR)
  }

  override def zkDown() {
    logError("PersistenceEngine disconnected from ZooKeeper -- ZK looks down.")
  }

  override def addApplication(app: ApplicationInfo) {
    serializeIntoFile(WORKING_DIR + "/app_" + app.id, app)
  }

  override def removeApplication(app: ApplicationInfo) {
    zk.delete(WORKING_DIR + "/app_" + app.id)
  }

  override def addWorker(worker: WorkerInfo) {
    serializeIntoFile(WORKING_DIR + "/worker_" + worker.id, worker)
  }

  override def removeWorker(worker: WorkerInfo) {
    zk.delete(WORKING_DIR + "/worker_" + worker.id)
  }

  override def close() {
    zk.close()
  }

  override def readPersistedData(): (Seq[ApplicationInfo], Seq[WorkerInfo]) = {
    val sortedFiles = zk.getChildren(WORKING_DIR).toList.sorted
    val appFiles = sortedFiles.filter(_.startsWith("app_"))
    val apps = appFiles.map(deserializeFromFile[ApplicationInfo])
    val workerFiles = sortedFiles.filter(_.startsWith("worker_"))
    val workers = workerFiles.map(deserializeFromFile[WorkerInfo])
    (apps, workers)
  }

  private def serializeIntoFile(path: String, value: AnyRef) {
    val serializer = serialization.findSerializerFor(value)
    val serialized = serializer.toBinary(value)
    zk.create(path, serialized, CreateMode.PERSISTENT)
  }

  def deserializeFromFile[T](filename: String)(implicit m: Manifest[T]): T = {
    val fileData = zk.getData("/spark/master_status/" + filename)
    val clazz = m.runtimeClass.asInstanceOf[Class[T]]
    val serializer = serialization.serializerFor(clazz)
    serializer.fromBinary(fileData).asInstanceOf[T]
  }
}


text:
//
//  FindPaswordViewController.m
//  BurstLaugh
//
//  Created by scjy on 16/3/8.
//  Copyright © 2016年 王雪娟. All rights reserved.
//

#import "FindPaswordViewController.h"
#import "LoginViewController.h"
#import "ProgressHUD.h"
#import <BmobSDK/BmobSMS.h>
#import <BmobSDK/BmobUser.h>
@interface FindPaswordViewController ()
@property (weak, nonatomic) IBOutlet UITextField *cellPhoneNumberTF;
@property (weak, nonatomic) IBOutlet UIButton *sureNumberBtn;
@property (weak, nonatomic) IBOutlet UITextField *sureNumberTF;
@property (weak, nonatomic) IBOutlet UITextField *passWordTF;

@property (weak, nonatomic) IBOutlet UISwitch *switchp;

@end

@implementation FindPaswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tabBarController.tabBar.hidden = YES;
    [self showBackButtonWithImage:@"back"];
    self.passWordTF.secureTextEntry = YES;

    self.switchp.on = NO;

}

//发送短信验证码
- (IBAction)sureNumBtnAction:(id)sender {

    if (self.cellPhoneNumberTF.text.length <= 0 && [self.cellPhoneNumberTF.text stringByReplacingOccurrencesOfString:@" " withString:@""].length <= 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示框" message:@"请输入您的手机号码" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        UIAlertAction *canAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:action];
        [alert addAction:canAction];
        [self presentViewController:alert animated:YES completion:nil];

    } else {
    [BmobSMS requestSMSCodeInBackgroundWithPhoneNumber:self.cellPhoneNumberTF.text andTemplate:@"test" resultBlock:^(int number, NSError *error) {
        if (error) {
            NSLog(@"error = %@",error);
        } else {
            //活动smsID
            NSLog(@"sms ID: %d",number);
        }
    }];
  }
}

//点击完成返回到登陆界面
- (IBAction)nextBtnAction:(id)sender {
    //验证短信验证码
    [BmobSMS verifySMSCodeInBackgroundWithPhoneNumber:self.cellPhoneNumberTF.text andSMSCode:self.sureNumberTF.text resultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            NSLog(@"验证成功,可执行其他操作");
        } else {
            NSLog(@"验证码出错%@",error);
        }

    }];

   // 用户收到验证码之后就可以调用resetPasswordBySMSCode方法将密码重置
    [BmobUser resetPasswordInbackgroundWithSMSCode:self.sureNumberTF.text andNewPassword:self.passWordTF.text block:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            [ProgressHUD showSuccess:@"密码验证成功,请重新登陆"];
            NSLog(@"密码重置成功");
        } else {
            [ProgressHUD showSuccess:@"密码验证不成功"];
            NSLog(@"密码修改不成功");

        }

    }];

}

//密码加密
- (IBAction)switchSecurity:(id)sender {
    UISwitch *passSwitch = sender;
    if (passSwitch.on) {
        self.passWordTF.secureTextEntry = NO;
    } else {
        self.passWordTF.secureTextEntry = YES;

    }
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
describe("Karma:Angular template creation mode", function() {

	var templifier = require("../builders/karma-angular.js");

	var templates;

	beforeEach(function() {
		templates = [];
		templates.push({
			"name": "example1",
			"html": "

"
		});
		templates.push({
			"name": "example2",
			"html": "

"
		});
	});

	it("Has the correct mode", function() {
		expect(templifier.mode).toBe("karma-angular");
	});

	it("Has a prefix, generator, and suffix method", function() {
		expect(templifier.prefix).toBeDefined();
		expect(templifier.generator).toBeDefined();
		expect(templifier.suffix).toBeDefined();
	});

	it("Has valid output", function() {
		var concated = templifier.prefix();
		templates.forEach(function(template) {
			concated += templifier.generator(template);
		});
		concated += templifier.suffix();

		eval(concated);

		expect(__templifyTemplates).toBeDefined();
	});
});


text:
package org.uberfire.ext.plugin.backend;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.uberfire.backend.vfs.Path;
import org.uberfire.ext.plugin.model.CodeType;
import org.uberfire.ext.plugin.model.Framework;
import org.uberfire.ext.plugin.model.Language;
import org.uberfire.ext.plugin.model.PluginSimpleContent;
import org.uberfire.ext.plugin.model.PluginType;

public class PluginSamples {

    private static final String ANGULAR_MAIN = "angular_main.txt";
    private static final String ANGULAR_TEMPLATE = "angular_template.txt";
    private static final String ANGULAR_CSS = "angular_css.txt";
    public static final String ANGULAR_TODO_REGISTRY = "angular_todo_registry.txt";
    public static final String EMPTY_SCREEN_REGISTRY = "empty_screen_registry.txt";
    public static final String SCREEN_WITH_TITLE_REGISTRY = "screen_with_title_registry.txt";
    public static final String SCREEN_WITH_TITLE_AND_NAME_REGISTRY = "screen_with_title_and_name_registry.txt";
    private static final String SPLASH_TEMPLATE = "splash_template.txt";
    private static final String SPLASH_MAIN = "splash_main.txt";
    public static final String SPLASH_SCREEN_REGISTRY = "splash_screen_registry.txt";

    public static PluginSimpleContent getTodoAngularPluginSimpleContent() {
        Map<CodeType, String> codeMap = new HashMap<CodeType, String>();
        codeMap.put( CodeType.MAIN, loadSample( ANGULAR_MAIN ) );
        Path path = null;
        Set<Framework> frameworks = new HashSet<Framework>();
        frameworks.add( Framework.ANGULAR );
        PluginSimpleContent plugin = new PluginSimpleContent( "Yo", PluginType.SCREEN, path, loadSample( ANGULAR_TEMPLATE ), loadSample( ANGULAR_CSS ), codeMap, frameworks, Language.JAVASCRIPT );
        return plugin;
    }

    public static PluginSimpleContent getSplashScreen() {
        Map<CodeType, String> codeMap = new HashMap<CodeType, String>();
        codeMap.put( CodeType.MAIN, loadSample( SPLASH_MAIN ) );
        codeMap.put( CodeType.ON_CLOSE, loadSample( SPLASH_MAIN ) );
        codeMap.put( CodeType.ON_CONCURRENT_COPY, loadSample( SPLASH_MAIN ) );
        codeMap.put( CodeType.TITLE, "Title" );
        Path path = null;
        Set<Framework> frameworks = new HashSet<Framework>();
        PluginSimpleContent plugin = new PluginSimpleContent( "Splash", PluginType.SPLASH, path, loadSample( SPLASH_TEMPLATE ), "", codeMap, frameworks, Language.JAVASCRIPT );
        return plugin;
    }

    public static PluginSimpleContent getEmptyScreen() {
        Map<CodeType, String> codeMap = new HashMap<CodeType, String>();
        codeMap.put( CodeType.MAIN, "" );
        Path path = null;
        Set<Framework> frameworks = new HashSet<Framework>();
        PluginSimpleContent plugin = new PluginSimpleContent( "Yo", PluginType.SCREEN, path, "", "", codeMap, frameworks, Language.JAVASCRIPT );
        return plugin;
    }

    public static PluginSimpleContent getScreenWithTitle() {
        Map<CodeType, String> codeMap = new HashMap<CodeType, String>();
        codeMap.put( CodeType.MAIN, "" );
        codeMap.put( CodeType.TITLE, "My Title" );
        Path path = null;
        Set<Framework> frameworks = new HashSet<Framework>();
        PluginSimpleContent plugin = new PluginSimpleContent( "ScreenWithTitle", PluginType.SCREEN, path, "", "", codeMap, frameworks, Language.JAVASCRIPT );
        return plugin;
    }

    public static PluginSimpleContent getScreenWithMainAndTitle() {
        Map<CodeType, String> codeMap = new HashMap<CodeType, String>();
        codeMap.put( CodeType.MAIN, "alert('main');" );
        codeMap.put( CodeType.TITLE, "My Title" );
        Path path = null;
        Set<Framework> frameworks = new HashSet<Framework>();
        PluginSimpleContent plugin = new PluginSimpleContent( "ScreenWithTitle", PluginType.SCREEN, path, "", "", codeMap, frameworks, Language.JAVASCRIPT );
        return plugin;
    }

    public static String loadSample( String file ) {
        try {
            return IOUtils.toString( new PluginSamples().getClass().getResourceAsStream( file ),
                                     "UTF-8" );
        } catch ( IOException e ) {
            return "";
        }
    }

}


text:
using System;
using Microsoft.Win32;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using OpenSage.Utilities;
using OpenSage.Utilities.Extensions;

namespace OpenSage.Data
{
    public sealed class RegistryKeyPath
    {
        public readonly string Key;
        public readonly string ValueName;

        // This is required because one possible registry key for the Generals + ZH bundle points to the
        // root directory of the bundle.
        public readonly string Append;

        public RegistryKeyPath(string key, string valueName, string append = null)
        {
            Key = key;
            ValueName = valueName;
            Append = append;
        }
    }

    public sealed class GameInstallation
    {
        public static IEnumerable<GameInstallation> FindAll(IEnumerable<IGameDefinition> gameDefinitions)
        {
            return InstallationLocators
                .GetAllForPlatform()
                .SelectMany(x => gameDefinitions.SelectMany(y => x.FindInstallations(y)));
        }

        public IGameDefinition Game { get; }
        public string Path { get; }

        private readonly GameInstallation _baseGameInstallation;

        public GameInstallation(IGameDefinition game, string path, GameInstallation baseGame = null)
        {
            Game = game;
            Path = path;
            _baseGameInstallation = baseGame;
        }

        public FileSystem CreateFileSystem()
        {
            FileSystem nextFileSystem = null;
            if (_baseGameInstallation != null)
            {
                nextFileSystem = new FileSystem(_baseGameInstallation.Path);
            }

            return new FileSystem(Path, nextFileSystem);
        }
    }

    public interface IInstallationLocator
    {
        IEnumerable<GameInstallation> FindInstallations(IGameDefinition game);
    }

    public class EnvironmentInstallationLocator : IInstallationLocator
    {
        public IEnumerable<GameInstallation> FindInstallations(IGameDefinition game)
        {
            var identifier = game.Identifier.ToUpperInvariant() + "_PATH";
            var path = Environment.GetEnvironmentVariable(identifier);

            if (path == null)
            {
                path = Environment.GetEnvironmentVariable(identifier, EnvironmentVariableTarget.User);
            }
            if (path == null || !Directory.Exists(path))
            {
                return new GameInstallation[]{};
            }

            var installations = new GameInstallation[]{new GameInstallation(game, path)};

            return installations;
        }
    }

    // TODO: Move this to the Platform project.
    public class RegistryInstallationLocator : IInstallationLocator
    {

        // Validates paths to directories. Removes duplicates.
        private static IEnumerable<string> GetValidPaths(IEnumerable<string> paths)
        {
            return paths
                .WhereNot(string.IsNullOrWhiteSpace)
                .Distinct()
                .Where(Directory.Exists);
        }

        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        public IEnumerable<GameInstallation> FindInstallations(IGameDefinition game)
        {
            GameInstallation baseGameInstallation = null;

            if (game.BaseGame != null)
            {
                // TODO: Allow selecting one of these?
                baseGameInstallation = FindInstallations(game.BaseGame).FirstOrDefault();

                if (baseGameInstallation == null)
                {
                    logger.Warn("No game installations found");
                    return Enumerable.Empty<GameInstallation>();
                }
            }

            var paths = game.RegistryKeys.Select(RegistryUtility.GetRegistryValue);

            var installations = GetValidPaths(paths)
                .Select(p => new GameInstallation(game, p, baseGameInstallation))
                .ToList();

            return installations;
        }
    }

    public static class InstallationLocators
    {
        public static IEnumerable<IInstallationLocator> GetAllForPlatform()
        {
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                yield return new RegistryInstallationLocator();
            }

            yield return new EnvironmentInstallationLocator();
        }

        public static IEnumerable<GameInstallation> FindAllInstallations(IGameDefinition game)
        {
            var locators = GetAllForPlatform();
            var result = new List<GameInstallation>();
            foreach (var locator in locators)
            {
                var installations = locator.FindInstallations(game);
                foreach (var installation in installations)
                {
                    if (!result.Contains(installation))
                    {
                        result.Add(installation);
                    }
                }
            }
            return result;
        }
    }
}


text:
"""empty message

Revision ID: 6504bfe5203c
Revises: e2cfee316e0a
Create Date: 2016-08-25 20:28:04.737541

"""

# revision identifiers, used by Alembic.
revision = '6504bfe5203c'
down_revision = 'e2cfee316e0a'

from alembic import op
import sqlalchemy as sa
import server

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('client',
    sa.Column('name', sa.String(length=40), nullable=True),
    sa.Column('description', sa.String(length=400), nullable=True),
    sa.Column('user_id', sa.Integer(), nullable=True),
    sa.Column('client_id', sa.String(length=40), nullable=False),
    sa.Column('client_secret', sa.String(length=55), nullable=False),
    sa.Column('is_confidential', sa.Boolean(), nullable=False),
    sa.Column('redirect_uris', server.models.StringList(), nullable=False),
    sa.Column('default_scopes', server.models.StringList(), nullable=False),
    sa.ForeignKeyConstraint(['user_id'], ['user.id'], name=op.f('fk_client_user_id_user')),
    sa.PrimaryKeyConstraint('client_id', name=op.f('pk_client'))
    )
    op.create_index(op.f('ix_client_client_secret'), 'client', ['client_secret'], unique=True)
    op.create_table('grant',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('user_id', sa.Integer(), nullable=True),
    sa.Column('client_id', sa.String(length=40), nullable=False),
    sa.Column('code', sa.String(length=255), nullable=False),
    sa.Column('redirect_uri', sa.String(length=255), nullable=True),
    sa.Column('expires', sa.DateTime(), nullable=True),
    sa.Column('scopes', server.models.StringList(), nullable=True),
    sa.ForeignKeyConstraint(['client_id'], ['client.client_id'], name=op.f('fk_grant_client_id_client')),
    sa.ForeignKeyConstraint(['user_id'], ['user.id'], name=op.f('fk_grant_user_id_user'), ondelete='CASCADE'),
    sa.PrimaryKeyConstraint('id', name=op.f('pk_grant'))
    )
    op.create_index(op.f('ix_grant_code'), 'grant', ['code'], unique=False)
    op.create_table('token',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('client_id', sa.String(length=40), nullable=False),
    sa.Column('user_id', sa.Integer(), nullable=True),
    sa.Column('token_type', sa.String(length=40), nullable=True),
    sa.Column('access_token', sa.String(length=255), nullable=True),
    sa.Column('refresh_token', sa.String(length=255), nullable=True),
    sa.Column('expires', sa.DateTime(), nullable=True),
    sa.Column('scopes', server.models.StringList(), nullable=True),
    sa.ForeignKeyConstraint(['client_id'], ['client.client_id'], name=op.f('fk_token_client_id_client')),
    sa.ForeignKeyConstraint(['user_id'], ['user.id'], name=op.f('fk_token_user_id_user')),
    sa.PrimaryKeyConstraint('id', name=op.f('pk_token')),
    sa.UniqueConstraint('access_token', name=op.f('uq_token_access_token')),
    sa.UniqueConstraint('refresh_token', name=op.f('uq_token_refresh_token'))
    )
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('token')
    op.drop_index(op.f('ix_grant_code'), table_name='grant')
    op.drop_table('grant')
    op.drop_index(op.f('ix_client_client_secret'), table_name='client')
    op.drop_table('client')
    ### end Alembic commands ###


text: <player-list id="out"/>


text:
layout: post
title: "Kobold Inventor"
date: 2017-09-10
tags: [small, humanoid, cr1/4, volos-guide]
---

**Small humanoid (kobold), lawful evil**

**Armor Class** 12

**Hit Points** 13 (3d6+3)

**Speed** 30 ft.

|   STR   |   DEX   |   CON   |   INT   |   WIS   |   CHA   |
|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|
| 7 (-2) | 15 (+2) | 12 (+1) | 8 (-1) | 7 (-2) | 8 (-1) |

**Skills** Perception +0

**Senses** darkvision 60 ft.

**Languages** Common, Draconic

**Challenge** 1/4 (50 XP)

**Actions**

***Dagger.*** Melee or Ranged Weapon Attack: +4 to hit, reach 5 ft. or range 20/60 ft., one target. Hit: 4 (1d4+2) piercing damage.

***Sling.*** Ranged Weapon Attack: +4 to hit, range 30/120 ft., one target. Hit: 4 (1d4+2) bludgeoning damage.

***Weapon Invention.*** The kobold uses one of the following options (roll a d8 or choose one); the kobold can use each one no more than once per day:

1. Acid. The kobold hurls a flask of acid. Ranged Weapon Attack: +4 to hit, range 5/20 ft., one target. Hit: 7 (2d6) acid damage.

2. Alchemist's fire. The kobold throws a flask of alchemist's fire. Ranged Weapon Attack: +4 to hit, range 5/20 ft., one target. Hit: 2 (1d4) fire damage at the start of each of the target's turns. A creature can end this damage by using its action to make a DC 10 Dexterity check to extinguish the flames.

3. Basket of Centipedes. The kobold throws a small basket into a S-foot-square space within 20 feet of it. A swarm of insects (centipedes) with 11 hit points emerges from the basket and rolls initiative. At the end of each of the swarm's turns, there's a 50 percent chance that the swarm disperses.

4. Green Slime Pot. The kobold throws a clay pot full of green slime at the target, and it breaks open on impact. Ranged Weapon Attack: +4 to hit, range 5/20 ft., one target. Hit: The target is covered in a patch of green slime (see chapter 5 of the Dungeon Master's Guide). Miss: A patch of green slime covers a randomly determined S-foot-square section of wall or floor within 5 feet of the target.

5. Rot Grub Pot. The kobold throws a clay pot into a 5-foot-square space within 20 feet of it, and it breaks open on impact. A swarm of rot grubs (see appendix A) emerges from the shattered pot and remains a hazard in that square.

6. Scorpion on a Stick. The kobold makes a melee attack with a scorpion tied to the end of a 5-foot-long pole. Melee Weapon Attack: +4 to hit, reach 5 ft., one target. Hit: 1 piercing damage, and the target must make a DC 9 Constitution saving throw, taking 4 (1d8) poison damage on a failed save, or half as much damage on a successful one.

7. Skunk in a Cage. The kobold releases a skunk into an unoccupied space within 5 feet of it. The skunk has a walking speed of 20 feet, AC 10, 1 hit point, and no effective attacks. It rolls initiative and, on its turn, uses its action to spray musk at a random creature within 5 feet of it. The target must make a DC 9 Constitution saving throw. On a failed save, the target retches and can't take actions for 1 minute. The target can repeat the saving throw at the end of each of its turns, ending the effect on itself on a success. A creature that doesn't need to breathe or is immune to poison automatically succeeds on the saving throw. Once the skunk has sprayed its musk, it can't do so again until it finishes a short or long rest.

8. Wasp Nest in a Bag. The kobold throws a small bag into a 5-foot-square space within 20 feet of it. A swarm of insects (wasps) with 11 hit points emerges from the bag and rolls initiative. At the end of each of the swarm's turns, there's a 50 percent chance that the swarm disperses.


text:
<?php

/**
 * Adminhtml AdminNotification inbox grid
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */

class Mage_Adminhtml_Block_Notification_Inbox extends Mage_Adminhtml_Block_Widget_Grid_Container
{
    public function __construct()
    {
        $this->_controller = 'notification';
        $this->_headerText = Mage::helper('adminnotification')->__('Messages Inbox');
        parent::__construct();
    }

    protected function _prepareLayout()
    {
        $this->_removeButton('add');

        return parent::_prepareLayout();
    }
}


text:
namespace hefur {
   bool LogHandler::handle(mh::RequestReader &request, mh::ResponseWriter &response) const {
      Address original_ip;
      original_ip = request.channel().remoteAddr();
      std::string ip_str;

      struct sockaddr_in in;
      struct sockaddr_in6 in6;

      // Are the reverse proxy settings enabled?
      if (!REVERSE_PROXY_FROM.empty() && !REVERSE_PROXY_HEADER.empty() &&
          (REVERSE_PROXY_FROM == "0.0.0.0" ||
           REVERSE_PROXY_FROM == "::" ||
           REVERSE_PROXY_FROM == original_ip.ipStr())) {
         // Does the original IP match the reverse-proxy-from setting?
         auto headers = request.unparsedHeaders();
         auto header = headers.find(REVERSE_PROXY_HEADER);

         std::string real_ip;
         if (header != headers.end())
            real_ip = header->second;

         if (!real_ip.empty()) {
            Address ip;
            auto port = original_ip.port();
            auto real_ip_cstr = real_ip.c_str();

            if (inet_pton(AF_INET, real_ip_cstr, &(in.sin_addr.s_addr)) == 1) {
               in.sin_family = AF_INET;
               in.sin_port = port;

               request.channel().setRemoteAddr((struct ::sockaddr *)&in, sizeof(in));
               ip = ∈
               ip_str = ip.ipStr();
            } else if (inet_pton(AF_INET6, real_ip_cstr, &(in6.sin6_addr.s6_addr)) == 1) {
               // Are we using ipv4 over ipv6?
               if (memcmp("\0\0\0\0\0\0\0\0\0\0\xFF\xFF", &in6.sin6_addr.s6_addr, 12)) {
                  in6.sin6_family = AF_INET6;
                  in6.sin6_scope_id = 0;
                  in6.sin6_port = port;

                  request.channel().setRemoteAddr((struct ::sockaddr *)&in6, sizeof(in6));
                  ip = &in6;
               } else {
                  in.sin_family = AF_INET;
                  in.sin_port = port;

                  memcpy(&in.sin_addr.s_addr, in6.sin6_addr.s6_addr + 12, 4);

                  request.channel().setRemoteAddr((struct ::sockaddr *)&in, sizeof(in));
                  ip = ∈
               }

               ip_str = ip.ipStr();
            }
         }
      }

      auto http_log = mh::http_log;
      http_log->info("%s %s %s:%s",
                     original_ip.ipStr() + (!ip_str.empty() ? " (" + ip_str + ")" : ""),
                     methodString(request.method()), request.host(), request.rawLocation());
      return handler_->handle(request, response);
   }
} // namespace hefur


text:
module.exports = {
  policy: require('./oauth2'),
  routes: require('./oauth2-routes'),
  schema: {}
};


text:
module Printfection
  class Relation
    include Enumerable
    extend Forwardable
    def_delegators :@children, :each, :first, :last, :size, :count, :length

    attr_reader :parent, :children, :klass, :path, :keys, :actions

    def initialize(options={})
      options = {
        parent:   nil,
        children: [],
        klass:    Hashie::Mash,
        path:     "",
        keys:     {},
        actions:  []
      }.merge(options)

      @parent   = options.fetch(:parent)
      @children = options.fetch(:children)
      @klass    = options.fetch(:klass)
      @path     = options.fetch(:path)
      @keys     = options.fetch(:keys)
      @actions  = options.fetch(:actions)

      actions.each do |mod|
        self.extend(mod)
      end

      children.each do |child|
        apply_relation(child)
      end
    end

    def uri
      Util.join_uri(parent.uri, path)
    end

    def new(*args)
      child = klass.new(*args)
      apply_relation(child)
      return child
    end

    private

    def apply_relation(child)
      keys.each do |primary, foreign|
        child[foreign] = parent[primary]
      end

      if child.respond_to? :relation=
        child.relation = self
      end
    end

  end
end


text:
package com.adaptris.core.services.jdbc;

import com.adaptris.annotation.DisplayOrder;
import com.thoughtworks.xstream.annotations.XStreamAlias;

/**
 * {@link Long} Statement Parameter.
 *
 * <p>
 * If {@code convert-null} is true, then empty/blank/whitespace only values will default to 0.
 * </p>
 *
 * @config jdbc-long-statement-parameter
 * @author lchan
 *
 */
@XStreamAlias("jdbc-long-statement-parameter")
@DisplayOrder(order = {"name", "queryString", "queryType"})
public class LongStatementParameter extends TypedStatementParameter<Long> {

  public LongStatementParameter() {
    super();
  }

  public LongStatementParameter(String query, QueryType type, Boolean nullConvert, String name) {
    super(query, type, nullConvert, name);
  }

  @Override
  public LongStatementParameter makeCopy() {
    return new LongStatementParameter(getQueryString(), getQueryType(), getConvertNull(), getName());
  }

  @Override
  protected Long defaultValue() {
    return Long.valueOf(0);
  }

  @Override
  protected Long convertToType(Object value) {
    return Long.valueOf((String) value);
  }
}


text:
/*
 * ----------------------------------------
 *          Jenkins Test Tracker
 * ----------------------------------------
 *          Produced by Dan Grew
 *                 2016
 * ----------------------------------------
 */
package uk.dangrew.jtt.desktop.buildwall.panel.type;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import uk.dangrew.jtt.desktop.buildwall.configuration.properties.BuildWallConfiguration;
import uk.dangrew.jtt.desktop.buildwall.configuration.properties.BuildWallConfigurationImpl;
import uk.dangrew.jtt.desktop.buildwall.configuration.theme.BuildWallTheme;
import uk.dangrew.jtt.desktop.buildwall.configuration.theme.BuildWallThemeImpl;
import uk.dangrew.jtt.desktop.buildwall.panel.description.DefaultJobPanelDescriptionImpl;
import uk.dangrew.jtt.desktop.buildwall.panel.description.DetailedJobPanelDescriptionImpl;
import uk.dangrew.jtt.desktop.buildwall.panel.description.JobPanelDescriptionBaseImpl;
import uk.dangrew.jtt.desktop.buildwall.panel.description.SimpleJobPanelDescriptionImpl;
import uk.dangrew.jtt.desktop.graphics.DecoupledPlatformImpl;
import uk.dangrew.jtt.desktop.graphics.TestPlatformDecouplerImpl;
import uk.dangrew.jtt.model.jobs.JenkinsJob;
import uk.dangrew.jtt.model.jobs.JenkinsJobImpl;
import uk.dangrew.kode.launch.TestApplication;

import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;

/**
 * {@link JobPanelDescriptionProviders}
 */
public class JobPanelDescriptionProvidersTest {

   private BuildWallTheme theme;
   private BuildWallConfiguration configuration;
   private JenkinsJob job;

   @BeforeClass public static void initialisePlatform(){
      DecoupledPlatformImpl.setInstance( new TestPlatformDecouplerImpl() );
      TestApplication.startPlatform();
   }//End Method

   @Before public void initialiseEnvironment(){
      configuration = new BuildWallConfigurationImpl();
      theme = new BuildWallThemeImpl( "Test" );
      job = new JenkinsJobImpl( "some job" );
   }//End Method

   @Test public void simpleShouldProvideSimple() {
      JobPanelDescriptionBaseImpl description = JobPanelDescriptionProviders.Simple.constructJobDescriptionPanel( configuration, theme, job );
      assertThat( description, notNullValue() );
      assertThat( description, instanceOf( SimpleJobPanelDescriptionImpl.class ) );
   }//End Method

   @Test public void defaultShouldProvideDefault() {
      JobPanelDescriptionBaseImpl description = JobPanelDescriptionProviders.Default.constructJobDescriptionPanel( configuration, theme, job );
      assertThat( description, notNullValue() );
      assertThat( description, instanceOf( DefaultJobPanelDescriptionImpl.class ) );
   }//End Method

   @Test public void detailedShouldProvideDetailed() {
      JobPanelDescriptionBaseImpl description = JobPanelDescriptionProviders.Detailed.constructJobDescriptionPanel( configuration, theme, job );
      assertThat( description, notNullValue() );
      assertThat( description, instanceOf( DetailedJobPanelDescriptionImpl.class ) );
   }//End Method

}//End Class


text:
Sdsapp.controllers :api do

	#swap request token for authentication token
	post 'oauth/token' do

	  #1. check params, client id / secret combination
	  body = JSON.parse params.first.first
	  sda = SharedDataApplication.get body["client_id"]

	 ##validate client id in authorization
	  if(body["grant_type"] == "authorization_code" && sda != nil && sda.secret == body["client_secret"])

		#2. find authorization for request token
		puts "provided code: #{body["code"]}"
		pca = PersonalContextAuthorization.find_by_request_token(body["code"])
		puts "found pca, state #{pca.state},provided: #{body[:code]} token: #{pca.request_token}"
		##validate client authorized and that the state is 'in request'
		puts pca.client_id
		puts pca.resource_owner_id
		puts sda.id
		if(pca != nil && pca.client_id == sda.id && pca.state == AuthorizationState::PENDING_REQUEST)

			#everything seems in order
			#let's swap and return the access code
			pca.state = AuthorizationState::ACCESS_GRANTED
			pca.save
			return "{ \"access_token\": \"#{pca.access_token}\" }"
			#TODO:return expiry/refresh stuff
		else
		 	halt 422, "invalid or outdated  authorization request"
		end
	  else
		halt 422, "invalid request"
	  end
	end

	#store a document
	#the token indicates the application, context etc
	post 'store' do
		token = env["HTTP_AUTHORIZATION"].split.last
		puts "using token: #{token}"

		#make json can parse the data as a hash
		document = params.first.first
		data = JSON.parse document
		puts data.inspect

		#hmm not the right way to find the correct token?
		pca = PersonalContextAuthorization.find_by_access_token(token)

		if(document != nil && pca != nil && pca.state == AuthorizationState::ACCESS_GRANTED)

			puts "pca.resource_owner_id: #{pca.resource_owner_id}"
			#wtf this shouldn't be empty

			store = PersonalStore.find_by_account_id(pca.resource_owner_id)

			#1.store clear text document in temp db
			#id = store.persist(data, pca.scope.context)
			id = TempDatabase.persist(data,pca.scope.context)

			#2.create anonymized version of the document, by transformation
			anonimized_data = TempDatabase.anonimize(pca.scope.context,id)

			#delete temp database
		 	TempDatabase.proxy_database(pca.scope.context).delete!

			#get reference to the public context store
			sdc = SharedDataContext.find_by_name pca.scope.context
			cstore = ContextStore.find_by_shared_data_context_id sdc
			if(cstore == nil)
				cstore = ContextStore.new(:shared_data_context => sdc)
				cstore.save #save the store document
			end

			cstore.persist anonimized_data	#save some public data in the context store
			#3. now encrypt the personal data
			#
			client = SharedDataApplication.get(pca.client_id)
			puts client.public_key
			#3a. create random symmetric encryption key
			secret_key = SecureRandom.hex(11)
			puts "secret key: #{secret_key}"

			#3b. symetrically encrypt the message

			data.each do |key,value|
				if(key == "_id")
					next
				end
				data[key] = Base64.encode64(Encryptor.encrypt(value, :key => secret_key))
			end
			puts "encrypted message: #{data.inspect}"

			#3c. encrypt symmetric key with public key of client
			public_key = OpenSSL::PKey::RSA.new client.public_key
			ciphertext = public_key.public_encrypt(secret_key)
			safe = Base64.encode64(ciphertext)
			puts "encrypted key: #{safe}"
			data["cipher"] = safe

			#3d.persist the encrypted data
			store.persist(data,pca.scope.context)

		else
			halt 422, "no valid token"
		end
	end

	get 'all' do
		token = env["HTTP_AUTHORIZATION"].split.last
		pca = PersonalContextAuthorization.find_by_access_token(token)

		if(pca != nil && pca.state == AuthorizationState::ACCESS_GRANTED)
			store = PersonalStore.find_by_account_id(pca.resource_owner_id)
			application = SharedDataApplication.get(pca.client_id)
		        list = store.list(application, pca.scope.context)
			response = ""
			list.each do |doc|
				json = doc.to_json
				response << "#{json}\n"
			end
			return response
		else
			halt 422, "no valid token"
		end
	end

	get 'context/:name' do
		sdc = SharedDataContext.find_by_name(params[:name])
		if(sdc != nil)
			cstore = ContextStore.find_by_shared_data_context_id sdc
			list = cstore.list
			response = ""
			list.each do |doc|
				response << "#{doc}\n"
			end
			return response
		else
			halt 404, "context not found"
		end
	end
end


text:
from base/arch

MAINTAINER rijalati@gmail.com

RUN [ -d /etc/pacman.d ] || mkdir -p /etc/pacman.d

RUN pacman -Syy
RUN pacman -S --noconfirm archlinux-keyring
RUN pacman -Syu -y --needed --noconfirm --force
RUN pacman-db-upgrade
RUN pacman -Syu --noconfirm --needed \
    base-devel \
    python2 \
    wxgtk2.8 \
    curl \
    git \
    wxpython2.8 \
    bash \
    python2-pip \
    xorg-xauth \
    xorg-fonts \
    xorg-fonts-75dpi \
    xorg-fonts-100dpi \
    firefox \
    emacs-nox \
    vim \
    vim-plugins \
    sudo

RUN pip2 install \
    Paver \
    robotframework \
    robotframework-tools \
    robotframework-rfdoc \
    robotframework-selenium2library \
    robotframework-selenium2screenshots \
    robotframework-sshlibrary \
    robotframework-hub \
    robotframework-lint \
    robotframework-pageobjects \
    robotframework-pycurllibrary \
    robotframework-httplibrary \
    sphinxcontrib-robotframework \
    Pygments \
    jedi \
    pep8 \
    pylint \
    pyflakes \
    requests \
    rope

RUN useradd -m -G wheel -U admin
RUN echo 'admin:secret' | chpasswd
RUN echo 'admin ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

#RUN chown -R admin:admin /RIDE

USER admin
RUN git clone https://github.com/robotframework/RIDE.git /home/admin/RIDE
ENV HOME /home/admin
WORKDIR /home/admin/RIDE
CMD ["/usr/bin/paver", "run"]


text:
all : out/crash_test.exe out/qalloc_test.exe out/options_test.exe out/bfile_test.exe out/xml_test.exe

CC := wpp386
# escape ;'s or shell will try to execute them as separate commands
INCLUDES=-i=..\main\;..\main\crashlog\;..\main\qalloc\;..\main\mplayer\;..\main\xml
CRASH_CFLAGS =-bt=dos4g -d3 -s -wx -fp6 -mf -fr=nul -dDEBUG=1 -dTEST=1 $(INCLUDES)
CFLAGS =-bt=nt -j -d3 -hc -s -wx -fp6 -mf -fr=nul -dDEBUG=1 -dTEST=1 $(INCLUDES)

#
# crash test
#

obj/crash_test.obj : crash_test.c swos.h util.h dos.h ../main/crashlog/crashlog.h
	@$(CC) $(CRASH_CFLAGS) -fo=obj\crash_test.obj crash_test.c

obj/crash_mock.obj : crash_mock.c util.h swos.h
	@$(CC) $(CRASH_CFLAGS) -fo=obj\crash_mock.obj crash_mock.c

obj/crashlog.obj : ../main/crashlog/crashlog.cpp swos.h util.h dos.h ../main/crashlog/crashlog.h
	@$(CC) $(CRASH_CFLAGS) -fo=obj\crashlog.obj ..\main\crashlog\crashlog.cpp

obj/xmlparse_c.obj : ../main/xml/xmlparse.cpp ../main/types.h swos.h util.h \
    ../main/xml/xmlparse.h ../main/xml/xmltree.h dos.h ../main/qalloc/qalloc.h
	@$(CC) $(CRASH_CFLAGS) -fo=obj\xmlparse_c.obj ..\main\xml\xmlparse.cpp

obj/vsprintf.obj : ../main/vsprintf.cpp swos.h
	@$(CC) $(CRASH_CFLAGS) -fo=obj\vsprintf.obj ..\main\vsprintf.cpp

out/crash_test.exe : obj/crash_test.obj obj/crashlog.obj obj/crash_mock.obj obj/vsprintf.obj obj/xmlparse_c.obj
	@echo option quiet, stack=32k, map system dos4g name $@ file obj/crash_test.obj >obj/lnk.txt
	@echo file obj/crashlog.obj, obj/crash_mock.obj, obj/vsprintf.obj >>obj/lnk.txt
	@wlink @obj/lnk.txt
	@mv crash_test.map map

#
# qalloc test
#

obj/qalloc_mock.obj : qalloc_mock.c swos.h util.h
	@$(CC) $(CFLAGS) -fo=obj\qalloc_mock.obj qalloc_mock.c

obj/qalloc.obj : ../main/qalloc/qalloc.cpp ../main/qalloc/qalloc.h swos.h util.h
	@$(CC) $(CFLAGS) -fo=obj\qalloc.obj ..\main\qalloc\qalloc.cpp

obj/qalloc_test.obj : qalloc_test.c ../main/qalloc/qalloc.h
	@$(CC) $(CFLAGS) -fo=obj\qalloc_test.obj qalloc_test.c

out/qalloc_test.exe : obj/qalloc_test.obj obj/qalloc.obj obj/qalloc_mock.obj
	@echo Debug Codeview option quiet, stack=32k, map system nt name $@ >obj/lnk.txt
	@echo file obj/qalloc_test.obj, obj/qalloc.obj, obj/qalloc_mock.obj >>obj/lnk.txt
	@wlink @obj/lnk.txt
	@mv qalloc_test.map map

#
# options test
#

obj/options_test.obj : options_test.c swos.h ../main/qalloc/qalloc.h bfile_mock.h util.h
	@$(CC) $(CFLAGS) -fo=obj\options_test.obj options_test.c

obj/options.obj : ../main/options.cpp swos.h util.h ../main/options.h ../main/xml/xmltree.h
	@$(CC) $(CFLAGS) -fo=obj\options.obj ..\main\options.cpp

obj/xmltree.obj : ../main/xml/xmltree.cpp util.h ../main/xml/xmltree.h dos.h \
    ../main/qalloc/qalloc.h swos.h
	@$(CC) $(CFLAGS) -fo=obj\xmltree.obj ..\main\xml\xmltree.cpp

obj/xmlparse.obj : ../main/xml/xmlparse.cpp ../main/types.h swos.h util.h \
    ../main/xml/xmlparse.h ../main/xml/xmltree.h dos.h ../main/qalloc/qalloc.h
	@$(CC) $(CFLAGS) -fo=obj\xmlparse.obj ..\main\xml\xmlparse.cpp

obj/util.obj : ../main/util.cpp swos.h util.h
	@$(CC) $(CFLAGS) -fo=obj\util.obj ..\main\util.cpp

obj/options_mock.obj : options_mock.c ../main/types.h ../main/mplayer/mplayer.h \
    ../main/mplayer/dosipx.h ../main/xml/xmltree.h
	@$(CC) $(CFLAGS) -fo=obj\options_mock.obj options_mock.c

obj/bfile_mock.obj : bfile_mock.c
	@$(CC) $(CFLAGS) -fo=obj\bfile_mock.obj bfile_mock.c

out/options_test.exe : obj/options_test.obj obj/options.obj obj/xmltree.obj obj/qalloc.obj \
    obj/options_mock.obj obj/qalloc_mock.obj obj/util.obj obj/xmlparse.obj obj/bfile_mock.obj
	@echo Debug Codeview All option quiet, stack=128k, map, cvpack system nt name $@ >obj/lnk.txt
	@echo file clib3r.lib\(memset\), clib3r.lib\(_strcmp\), clib3r.lib\(strncmp\) >>obj/lnk.txt
	@echo file clib3r.lib\(memmove\), clib3r.lib\(strlen\), clib3r.lib\(segread\) >>obj/lnk.txt
	@echo file clib3r.lib\(exit\), clib3r.lib\(time\), clib3r.lib\(asctime.c\) >>obj/lnk.txt
	@echo file obj/options_test.obj, obj/options.obj, obj/qalloc.obj >>obj/lnk.txt
	@echo file obj/options_mock.obj, obj/xmltree.obj, obj/qalloc_mock.obj >>obj/lnk.txt
	@echo file obj/util.obj, obj/xmlparse.obj, obj/bfile_mock.obj disable 1027 >>obj/lnk.txt
	@wlink @obj/lnk.txt
	@mv options_test.map map

#
# BFile test
#

obj/bfile_test.obj : bfile_test.cpp bfile_mock.h util.h ../main/types.h dos.h
	@$(CC) $(CFLAGS) -fo=obj\bfile_test.obj bfile_test.cpp

out/bfile_test.exe : obj/bfile_test.obj obj/util.obj obj/options_mock.obj obj/qalloc.obj \
    obj/qalloc_mock.obj obj/bfile_mock.obj
	@echo Debug Codeview All option quiet, stack=32k, map, cvpack system nt name $@ >obj/lnk.txt
	@echo file clib3r.lib\(memset\), clib3r.lib\(_strcmp\) >>obj/lnk.txt
	@echo file clib3r.lib\(memmove\), clib3r.lib\(strlen\), clib3r.lib\(segread\) >>obj/lnk.txt
	@echo file clib3r.lib\(exit\), clib3r.lib\(time\), clib3r.lib\(asctime.c\) >>obj/lnk.txt
	@echo file clib3r.lib\(rand\), obj/bfile_test.obj, obj/util.obj >>obj/lnk.txt
	@echo file obj/options_mock.obj, obj/qalloc.obj, obj/qalloc_mock.obj, obj/bfile_mock.obj >>obj/lnk.txt
	@echo disable 1027 >>obj/lnk.txt
	@wlink @obj/lnk.txt
	@mv bfile_test.map map

#
# XML test
#

obj/xml_test.obj : xml_test.c ../main/types.h swos.h util.h ../main/xml/xmltree.h \
    ../main/xml/xmlparse.h ../main/qalloc/qalloc.h bfile_mock.h dos.h
	@$(CC) $(CFLAGS) -fo=obj\xml_test.obj xml_test.c

out/xml_test.exe : obj/xml_test.obj obj/xmlparse.obj obj/xmlparse.obj obj/util.obj obj/options_mock.obj \
    obj/qalloc_mock.obj obj/qalloc.obj obj/bfile_mock.obj obj/xmltree.obj
	@echo Debug Codeview All option quiet, stack=64k, map, cvpack system nt name $@ >obj/lnk.txt
	@echo file clib3r.lib\(memset\), clib3r.lib\(_strcmp\), clib3r.lib\(strncmp\) >>obj/lnk.txt
	@echo file clib3r.lib\(memmove\), clib3r.lib\(strlen\), clib3r.lib\(segread\) >>obj/lnk.txt
	@echo file clib3r.lib\(exit\), clib3r.lib\(time\), clib3r.lib\(asctime.c\) >>obj/lnk.txt
	@echo file clib3r.lib\(rand\), obj/xml_test.obj, obj/xmlparse.obj, obj/util.obj >>obj/lnk.txt
	@echo file obj/options_mock.obj, obj/qalloc_mock.obj, obj/qalloc.obj, obj/bfile_mock.obj >>obj/lnk.txt
	@echo file obj/xmltree.obj >>obj/lnk.txt
	@echo disable 1027 >>obj/lnk.txt
	@wlink @obj/lnk.txt
	@mv xml_test.map map

obj/lnk.txt : .INTERMEDIATE


text:
'use strict';

var D = require('./dict');

function Set(elems) {
    this.dict = new D({});
    var self = this;
    elems.map(function(e) {
        self.add(e);
    });
}

Set.prototype.add = function(key) {
    this.dict.set(key, 1);
};

Set.prototype.has = function(key) {
    return this.dict.has(key);
};

Set.prototype.remove = function(key) {
    return this.dict.remove(key);
};

Set.prototype.keys = function() {
    return this.dict.keys();
};

Set.prototype.toJSON = function() {
    return {'type': 'Set', 'elements': this.keys()};
};

Set.prototype.toString = function() {
    return JSON.stringify(this.toJSON());
};

module.exports = Set;


text:
package org.odlabs.wiquery.core.events;

/**
 * $Id: EventLabel.java 1714 2011-09-22 20:38:30Z hielke.hoeve $
 * <p>
 * Defines a kind of "toString" method for all effects.
 * </p>
 *
 * @author lionel
 * @since 1.0
 */
public interface EventLabel
{

	/**
	 * @return The event string label
	 */
	String getEventLabel();

}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
	value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _api = require('./api');

var _api2 = _interopRequireDefault(_api);

var teamwork = _extends({

	config: {}

}, _api2['default']);

exports['default'] = Object.create(teamwork);
module.exports = exports['default'];
//# sourceMappingURL=teamwork.js.map


text:
package com.rwtema.extrautils.block;

import net.minecraft.world.IBlockAccess;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.block.Block;
import java.util.Iterator;
import net.minecraftforge.common.util.FakePlayer;
import java.util.List;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.tileentity.TileEntityHopper;
import com.rwtema.extrautils.helper.XUHelper;
import net.minecraft.util.DamageSource;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.util.FakePlayerFactory;
import net.minecraft.entity.IEntityLivingData;
import net.minecraft.entity.Entity;
import net.minecraft.command.IEntitySelector;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.EntityLiving;
import net.minecraft.item.ItemSword;
import net.minecraft.inventory.IInventory;
import net.minecraft.util.Facing;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.WorldServer;
import java.util.Random;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import com.rwtema.extrautils.ExtraUtils;
import net.minecraft.block.material.Material;
import net.minecraft.util.IIcon;

public class BlockPeacefulTable extends BlockMultiBlock
{
    private IIcon[] icons;

    public BlockPeacefulTable() {
        super(Material.wood);
        this.setCreativeTab((CreativeTabs)ExtraUtils.creativeTabExtraUtils);
        this.setBlockBounds(0.0f, 0.0f, 0.0f, 1.0f, 0.25f, 1.0f);
        this.setBlockName("extrautils:peaceful_table_top");
        this.setBlockTextureName("extrautils:peaceful_table_top");
        this.setTickRandomly(true);
        this.setHardness(1.0f);
        this.setResistance(10.0f).setStepSound(BlockPeacefulTable.soundTypeWood);
    }

    @SideOnly(Side.CLIENT)
    public void registerBlockIcons(final IIconRegister par1IIconRegister) {
        (this.icons = new IIcon[3])[0] = par1IIconRegister.registerIcon("extrautils:peaceful_table_bottom");
        this.icons[1] = par1IIconRegister.registerIcon("extrautils:peaceful_table_top");
        this.icons[2] = par1IIconRegister.registerIcon("extrautils:peaceful_table_side");
    }

    public void updateTick(final World world, final int x, final int y, final int z, final Random par5Random) {
        if (!world.isRemote && world instanceof WorldServer) {
            if (!ExtraUtils.peacefulTableInAllDifficulties && world.difficultySetting != EnumDifficulty.PEACEFUL) {
                return;
            }
            final BiomeGenBase.SpawnListEntry var7 = ((WorldServer)world).spawnRandomCreature(EnumCreatureType.monster, x, y, z);
            if (var7 != null) {
                IInventory swordInv = null;
                int swordSlot = -1;
                ItemStack sword = null;
                for (int j = 0; j < 6; ++j) {
                    final TileEntity tile = world.getTileEntity(x + Facing.offsetsXForSide[j], y + Facing.offsetsYForSide[j], z + Facing.offsetsZForSide[j]);
                    if (tile instanceof IInventory) {
                        final IInventory inv = (IInventory)tile;
                        for (int i = 0; i < inv.getSizeInventory(); ++i) {
                            final ItemStack item = inv.getStackInSlot(i);
                            if (item != null && item.getItem() instanceof ItemSword) {
                                swordInv = inv;
                                swordSlot = i;
                                sword = item;
                                break;
                            }
                        }
                        if (sword != null) {
                            break;
                        }
                    }
                }
                if (sword == null) {
                    return;
                }
                EntityLiving t;
                try {
                    t = (EntityLiving) var7.entityClass.getConstructor(World.class).newInstance(world);
                }
                catch (Exception var8) {
                    var8.printStackTrace();
                    return;
                }
                final List list1 = world.selectEntitiesWithinAABB((Class)EntityItem.class, AxisAlignedBB.getBoundingBox((double)(x - 2), (double)y, (double)(z - 2), (double)(x + 3), (double)(y + 4), (double)(z + 2)), IEntitySelector.selectAnything);
                t.setLocationAndAngles(x + 0.5, y + 1.25, z + 0.5, par5Random.nextFloat() * 360.0f, 0.0f);
                world.spawnEntityInWorld((Entity)t);
                final EnumDifficulty prev = world.difficultySetting;
                world.difficultySetting = EnumDifficulty.HARD;
                t.onSpawnWithEgg((IEntityLivingData)null);
                world.difficultySetting = prev;
                final FakePlayer fakePlayer = FakePlayerFactory.getMinecraft((WorldServer)world);
                fakePlayer.setCurrentItemOrArmor(0, sword.copy());
                final float h1 = t.getHealth();
                fakePlayer.attackTargetEntityWithCurrentItem((Entity)t);
                final float h2 = t.getHealth();
                if (t.isDead) {
                    if (fakePlayer.getCurrentEquippedItem() == null || fakePlayer.getCurrentEquippedItem().stackSize == 0) {
                        swordInv.setInventorySlotContents(swordSlot, (ItemStack)null);
                    }
                    else {
                        swordInv.setInventorySlotContents(swordSlot, fakePlayer.getCurrentEquippedItem());
                    }
                }
                else {
                    if (fakePlayer.getCurrentEquippedItem() == null || fakePlayer.getCurrentEquippedItem().stackSize == 0) {
                        swordInv.setInventorySlotContents(swordSlot, (ItemStack)null);
                    }
                    else {
                        if (h1 > h2) {
                            for (float h3 = h2; h3 > 0.0f; h3 -= h1 - h2) {
                                sword.hitEntity((EntityLivingBase)t, (EntityPlayer)fakePlayer);
                            }
                        }
                        if (sword.stackSize == 0) {
                            swordInv.setInventorySlotContents(swordSlot, (ItemStack)null);
                        }
                    }
                    t.onDeath(DamageSource.causePlayerDamage((EntityPlayer)fakePlayer));
                    t.motionX = 0.0;
                    t.motionY = 0.0;
                    t.motionZ = 0.0;
                }
                fakePlayer.setCurrentItemOrArmor(0, (ItemStack)null);
                t.setDead();
                final List list2 = world.getEntitiesWithinAABB((Class)EntityItem.class, AxisAlignedBB.getBoundingBox((double)(x - 2), (double)y, (double)(z - 2), (double)(x + 3), (double)(y + 4), (double)(z + 2)));
                for (final Object aList2 : list2) {
                    if (!list1.contains(aList2)) {
                        final int[] seq = XUHelper.rndSeq(6, world.rand);
                        for (int k = 0; k < 6; ++k) {
                            final IInventory inv2 = TileEntityHopper.func_145893_b(world, (double)(x + Facing.offsetsXForSide[seq[k]]), (double)(y + Facing.offsetsYForSide[seq[k]]), (double)(z + Facing.offsetsZForSide[seq[k]]));
                            if (inv2 != null && !((EntityItem)aList2).isDead) {
                                final ItemStack itemstack = ((EntityItem)aList2).getEntityItem().copy();
                                final ItemStack itemstack2 = XUHelper.invInsert(inv2, itemstack, Facing.oppositeSide[k]);
                                if (itemstack2 != null && itemstack2.stackSize != 0) {
                                    ((EntityItem)aList2).setEntityItemStack(itemstack2);
                                }
                                else {
                                    ((EntityItem)aList2).setDead();
                                }
                            }
                        }
                        ((EntityItem)aList2).setDead();
                    }
                }
            }
        }
    }

    public void onBlockAdded(final World world, final int x, final int y, final int z) {
        if (!world.isRemote) {
            world.scheduleBlockUpdate(x, y, z, (Block)this, 5 + world.rand.nextInt(100));
        }
    }

    public void onEntityCollidedWithBlock(final World world, final int x, final int y, final int z, final Entity par5Entity) {
        if (par5Entity instanceof EntityXPOrb) {
            par5Entity.setDead();
        }
    }

    @SideOnly(Side.CLIENT)
    public IIcon getIcon(final int par1, final int x) {
        final int i = Math.min(par1, 2);
        return this.icons[i];
    }

    public void prepareForRender(final String label) {
    }

    public BoxModel getWorldModel(final IBlockAccess world, final int x, final int y, final int z) {
        final BoxModel boxes = new BoxModel();
        final float h = 0.0625f;
        boxes.add(new Box(0.0f, 0.75f, 0.0f, 1.0f, 1.0f, 1.0f));
        boxes.add(new Box(0.0625f, 0.0f, 0.0625f, 0.3125f, 0.75f, 0.3125f));
        boxes.add(new Box(0.0625f, 0.0f, 0.0625f, 0.3125f, 0.75f, 0.3125f).rotateY(1));
        boxes.add(new Box(0.0625f, 0.0f, 0.0625f, 0.3125f, 0.75f, 0.3125f).rotateY(2));
        boxes.add(new Box(0.0625f, 0.0f, 0.0625f, 0.3125f, 0.75f, 0.3125f).rotateY(3));
        return boxes;
    }

    public BoxModel getInventoryModel(final int metadata) {
        return this.getWorldModel(null, 0, 0, 0);
    }
}


text:
package com.epam.ta.reportportal.ws.converter.builders;

import com.epam.ta.reportportal.entity.integration.Integration;
import com.epam.ta.reportportal.entity.integration.IntegrationParams;
import com.epam.ta.reportportal.entity.integration.IntegrationType;
import com.epam.ta.reportportal.entity.project.Project;

import java.time.LocalDateTime;
import java.util.function.Supplier;

/**
 * @author Ihar Kahadouski
 */
public class IntegrationBuilder implements Supplier<Integration> {

	private Integration integration;

	public IntegrationBuilder() {
		integration = new Integration();
	}

	public IntegrationBuilder(Integration integration) {
		this.integration = integration;
	}

	public IntegrationBuilder withCreationDate(LocalDateTime date) {
		this.integration.setCreationDate(date);
		return this;
	}

	public IntegrationBuilder withCreator(String creator) {
		this.integration.setCreator(creator);
		return this;
	}

	public IntegrationBuilder withEnabled(boolean enabled) {
		this.integration.setEnabled(enabled);
		return this;
	}

	public IntegrationBuilder withName(String name) {
		this.integration.setName(name);
		return this;
	}

	public IntegrationBuilder withType(IntegrationType type) {
		this.integration.setType(type);
		return this;
	}

	public IntegrationBuilder withProject(Project project) {
		this.integration.setProject(project);
		return this;
	}

	public IntegrationBuilder withParams(IntegrationParams params) {
		this.integration.setParams(params);
		return this;
	}

	@Override
	public Integration get() {
		return integration;
	}
}


text:
<?php defined('C5_EXECUTE') or die("Access Denied."); ?>
<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneHeaderWrapper(
    t('Public Registration'),
    t(
        'Control the options available for Public Registration.'),
    'span6 offset3',
    false); ?>
<?php
$h = Loader::helper('concrete/ui');
?>
<form method="post" id="registration-type-form"
      action="<?php echo $view->action('update_registration_type') ?>">
        <?php echo $token->output('update_registration_type')?>

        <?php echo t('Allow visitors to signup as site members?') ?>

                <input type="radio" name="registration_type" value="disabled"
                       style="" <?php echo ($registration_type == "disabled" || !strlen(
                        $registration_type)) ? 'checked' : '' ?> />

                        <?php echo t('Off - only admins can create accounts from Dashboard') ?>

                <input type="radio" name="registration_type" value="enabled"
                       style="" <?php echo ($registration_type == "enabled") ? 'checked' : '' ?> />
                <?php echo t('On - anyone can create an account from Login page') ?>

                <input type="radio" name="registration_type" value="manual_approve"
                       style="" <?php echo ($registration_type == "manual_approve") ? 'checked' : '' ?> />
                <?php echo t('On - approve manually') ?>

                <input type="radio" name="registration_type" value="validate_email"
                       style="" <?php echo ($registration_type == "validate_email") ? 'checked' : '' ?> />
                <?php echo t('Validate - anyone can create an account from Login page, once validated by email') ?>

        <?php echo t('Notification') ?>

                <input type="checkbox" name="register_notification"
                       value="1"<?php echo ($register_notification) ? ' checked="checked"' : '' ?>/>
                <?php echo t('Send admin an email when new user registers.'); ?>

        <?php echo t('Email address'); ?>
        <input class="form-control" name="register_notification_email" type="text"
            value="<?php echo h($register_notification_email); ?>"/>

        <?php echo t('Spam') ?>

                <input type="checkbox" name="enable_registration_captcha" value="1"
                       style="" <?php echo ($enable_registration_captcha) ? 'checked' : '' ?> />
                <?php echo t('CAPTCHA required') ?>

        <?php echo t('Username') ?>

                <input type="radio" name="email_as_username" value="0"
                       style="" <?php echo (!$email_as_username) ? 'checked' : '' ?> />

                        <?php echo t('Ask for Username & password on login form') ?>

                <input type="radio" name="email_as_username" value="1"
                       style="" <?php echo ($email_as_username) ? 'checked' : '' ?> />

                        <?php echo t('Ask for Email & password on login form') ?>

            <?php echo $h->submit(t('Save'), 'registration-type-form', 'right', 'btn-primary'); ?>

</form>


text:
// @flow
import Document from '../elements/document'
import type Element from '../elements/element'

type Position = Array<number>

const aiueo = 'アイウエオカキクケコサシスセソタチツテトナニヌネノ'.split('')
const elementNameConverters = [
  (num: number): string => `第${num}条`,
  (num: number): string => `${num}項`,
  (num: number): string => `(${num})`,
  (num: number): string => `${aiueo[num - 1]}`,
  (num: number): string => `(${aiueo[num - 1]})`,
  (num: number): string => `の${num}`,
  (num: number): string => `の${num}`,
  (num: number): string => `の${num}`,
  (num: number): string => `の${num}`,
  (num: number): string => `の${num}`,
]

function newPos(pos: Position, num: number): Position {
  const ret = pos.slice()
  ret.push(num)
  return ret
}

function appendElements(ds: DocumentStructure, el: Element, pos: Position, depth: number) {
  ds.elementsById[el.id] = el
  ds.positionsById[el.id] = pos
  ds.depthsById[el.id] = depth
  if (el.labelName) {
    ds.elementsByLabel[el.labelName] = el
  }
  el.items.forEach((item, i) => appendElements(ds, item, newPos(pos, i + 1), depth + 1))
}

/**
 * 文書構造
 */
export default class DocumentStructure {
  elementsById: { [id: string]: Element }
  elementsByLabel: { [label: string]: Element }
  positionsById: { [id: string]: Position }
  depthsById: { [id: string]: number }

  constructor(doc: Document) {
    this.elementsById = {}
    this.elementsByLabel = {}
    this.positionsById = {}
    this.depthsById = {}
    doc.articles.forEach((article, i) => appendElements(this, article, [i + 1], 0))
  }

  getNumber(el: Element): number {
    const pos = this.positionsById[el.id]
    return pos[pos.length - 1]
  }

  getDepth(el: Element): number {
    return this.depthsById[el.id]
  }

  getElementNameByLabel(labelName: string): string {
    const el = this.elementsByLabel[labelName]
    const pos = this.positionsById[el.id]
    return pos.map((num, i) => elementNameConverters[i](num)).join('')
  }
}


text:
Leaderboard Example
===================

Described in this article: [http://blog.fanout.io/2015/05/20/building-a-realtime-api-with-rethinkdb/](http://blog.fanout.io/2015/05/20/building-a-realtime-api-with-rethinkdb/)

Live instance here: [http://leaderboardapp.org/](http://leaderboardapp.org/)

License: MIT


text:
import eatTheRichRaw from './eatTheRich';

export default function welfare(
  parent, x0, y0, x1, y1,
  ratio = 3 / 2,
  budget = ratio,
  misery = ratio,
  step = 0.1,
  ) {
  let max = { firstRatio: 0, ratio };
  for (let offset = 0; offset < budget; offset += step) {
    eatTheRichRaw(parent, x0, y0, x1, y1, ratio + offset);
    const first = parent.children[0];
    const firstRatio = (first.x1 - first.x0) / (first.y1 - first.y0);
    if (firstRatio >= misery) return;
    if (firstRatio > max.firstRatio) max = { firstRatio, ratio: ratio + offset };
  }
  // Nothing worked, so revert to original ratio
  eatTheRichRaw(parent, x0, y0, x1, y1, max.ratio);
}