text:
"use strict";

/*global define, templates*/

define('rpg/battle/turn', ['translator', 'rpg/battle/ui'], function(translator, ui) {
	var turn = {},
		eventsEl,

		messageDuration = 1500;

	///*initiative, challengerDamage, opponentDamage, or eventArray?*/
	turn.go = function(result) {
		var events = result.events;

		eventsEl = $('#events')
			.removeClass('in');

		$('input, button, select').prop('disabled', true);

		for (var i = 0, ii = events.length; i < ii; i++) {
			renderEvent(i, result);
		}

		setTimeout(function() {
			if (result.finished !== 1) {
				endTurn();
			} else {
				endBattle();
			}
		}, (events.length - 1) * messageDuration);
	};

	function renderEvent(i, result) {
		setTimeout(function() {
			eventsEl.removeClass('in');
			setTimeout(function() {
				translator.translate(result.events[i].message, function(message) {
					message = templates.parse(message, {});
					eventsEl.html(message);
					eventsEl.addClass('in');

					switch (result.events[i].type) {
					case 'opponent:attack':
						animateOpponentAttack();
						break;
					case 'character:attack':
						animateOpponentDamaged();
					case 'character:attack:fail': // intentional fall through
						updateVitals(result.data);
						break;
					}
				});
			}, 250);
		}, messageDuration * i);
	}

	function animateOpponentAttack() {
		animate($('#opponent_img'), '');
		$('#opponent_img').attr('src', $('#opponent_img').attr('src') + '?t=' + (new Date()).getTime());
	}

	function animateOpponentDamaged() {
		animate($('#opponent_img'), 'bounce');
	}

	function animate(el, type) {
		el.removeClass('animated bounce shake rotateOut');
		setTimeout(function() { el.addClass('animated ' + type) }, 1);
	}

	function updateVitals(data) {
		$('#opponent_hp').css('width', data.battle_opponent_hp / data.battle_opponent_hp_max * 100 + '%');

		if (parseInt(data.battle_opponent_hp, 10) === 0) {
			setTimeout(function() {
				animate($('#opponent_img'), 'rotateOut');
			}, 500);
		}
	}

	function endTurn() {
		$('input, button, select').prop('disabled', false);
		ui.toggleEligibleActions();

		var loadingBtn = $('.btn[prevHtml]');
		loadingBtn.html(loadingBtn.attr('prevHtml')).removeAttr('prevHtml');
	}

	function endBattle() {
		var parents = $('input, button, select').parents('tr');
		parents.fadeOut(400, function() {
			parents.hide();
			$('.btn-restart').parents('tr').removeClass('hide');
		});
	}

	return turn;
});


text:
:host {
	display: block;
	background-color: white;
	width: 100%;
	height: 100%;
}
#admin-container {
	width: 100%;
	height: 100%;
	@apply(--layout-flex);
}
paper-toolbar {
	background: white;
	color: #757575;
	border-bottom: 1px solid #DEDEDE;
	padding: 0;
}
paper-toolbar::shadow .toolbar-tools {
	padding: 0;
}

#list-header {
	margin: 0;
	font-size: 1.1em;
	text-transform: capitalize;
	@apply(--layout-flex);
}

paper-tabs {
	position: relative;
	top: 8px;
	--paper-tabs-selection-bar-color: #FF7F50;
}
paper-tab {
	--paper-tab-ink: #FF7F50;
}
paper-tab.iron-selected {
	border: 1px solid #DEDEDE;
	background: white;
}

.admin-list {
	@apply(--layout-center);
	@apply(--layout-flex);
}
admin-li {
	padding-bottom: 10px;
	margin-bottom: 10px;
	/*border-bottom: 1px solid #DEDEDE;*/
	background: white;
}
admin-li h2 {
	text-transform: capitalize;
}

redpajama_set_name: RedPajamaGithub


text:
class AddDisplayNumberToChapter < ActiveRecord::Migration[5.2]
  def change
    add_column :chapters, :display_number, :text
  end
end


text:
package hadoopmongo;

import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hive.service.auth.HiveAuthFactory.AuthTypes;
import org.apache.hive.service.auth.PlainSaslHelper;
import org.apache.hive.service.cli.thrift.TCLIService;
import org.apache.hive.service.cli.thrift.TCLIService.Client;
import org.apache.hive.service.cli.thrift.TCloseSessionReq;
import org.apache.hive.service.cli.thrift.TExecuteStatementReq;
import org.apache.hive.service.cli.thrift.TExecuteStatementResp;
import org.apache.hive.service.cli.thrift.TOpenSessionReq;
import org.apache.hive.service.cli.thrift.TSessionHandle;
import org.apache.hive.service.server.HiveServer2;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

public class HiveServer2Launcher {

    private static final String HOST = "localhost";
    private static final int PORT = 11100;
    private static Client client;

    public static void main(String[] args) throws Exception {
        HiveConf hiveConf = new HiveConf();
        hiveConf.set("javax.jdo.option.ConnectionURL", "jdbc:derby:;databaseName=metastore_db;create=true");
        hiveConf.set("javax.jdo.option.ConnectionDriverName", "org.apache.derby.jdbc.EmbeddedDriver");
        hiveConf.set("hive.metastore.warehouse.dir", "file:///tmp");
        //hiveConf.set("hive.server2.thrift.port", "11100");
        hiveConf.setBoolVar(ConfVars.HIVE_SERVER2_ENABLE_DOAS, false);
        hiveConf.setVar(ConfVars.HIVE_SERVER2_THRIFT_BIND_HOST, HOST);
        hiveConf.setIntVar(ConfVars.HIVE_SERVER2_THRIFT_PORT, PORT);
        hiveConf.setVar(ConfVars.HIVE_SERVER2_AUTHENTICATION, AuthTypes.NOSASL.toString());
        hiveConf.setVar(ConfVars.HIVE_SERVER2_TRANSPORT_MODE, "binary");

        /*<!--hive.metastore.local=true
                mapreduce.framework.name=yarn
                hive.exec.submitviachild=false-->
                hive.debug.localtask=true
                hive.auto.convert.join.use.nonstaged=true*/
        HiveServer2 server = new HiveServer2();
        server.init(hiveConf);
        server.start();

        initClient(createBinaryTransport());
    }

    private static TTransport createBinaryTransport() throws Exception {
        return PlainSaslHelper.getPlainTransport("anonymous", "anonymous", new TSocket(HOST, PORT));
    }

    private static void initClient(TTransport transport) {
        TProtocol protocol = new TBinaryProtocol(transport);
        client = new TCLIService.Client(protocol);
    }

    private static TExecuteStatementResp executeQuerySync(String queryString, TSessionHandle sessHandle)
            throws Exception {
        TExecuteStatementReq execReq = new TExecuteStatementReq();
        execReq.setSessionHandle(sessHandle);
        execReq.setStatement(queryString);
        execReq.setRunAsync(false);
        TExecuteStatementResp execResp = client.ExecuteStatement(execReq);
        return execResp;
    }

    private static void createTable() throws Exception {
        TOpenSessionReq openReq = new TOpenSessionReq();
        TSessionHandle sessHandle = client.OpenSession(openReq).getSessionHandle();

        String queryString = "SET hive.lock.manager=org.apache.hadoop.hive.ql.lockmgr.EmbeddedLockManager";
        executeQuerySync(queryString, sessHandle);

        executeQuerySync("CREATE DATABASE IF NOT EXISTS es", sessHandle);
        executeQuerySync("USE es", sessHandle);

        queryString = "DROP TABLE IF EXISTS siebel_adresse";
        executeQuerySync(queryString, sessHandle);

        queryString = "CREATE EXTERNAL TABLE IF NOT EXISTS siebel_adresse (" +
                        "a_addr STRING, a_addr_line_2 STRING, a_addr_line_3 STRING, a_addr_line_4 STRING, " +
                        "a_addr_line_5 STRING, a_city STRING, a_country STRING, a_last_upd TIMESTAMP, " +
                        "a_principal_flg STRING, a_province STRING, a_row_id STRING, a_x_uge_flg STRING, " +
                        "a_zipcode STRING, b_active_flg STRING, d_asset_num STRING) " +
                        "STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler' " +
                        "TBLPROPERTIES('es.resource'='siebel/adresse', 'es.index.auto.create'='false', 'es.nodes'='192.168.1.45')";
        executeQuerySync(queryString, sessHandle);

        TCloseSessionReq closeReq = new TCloseSessionReq(sessHandle);
        client.CloseSession(closeReq);
    }
}


text:
/*
	jQuery.mmenu leftsubpanel extension CSS
*/
.mm-menu.mm-leftsubpanels .mm-panel:not(.mm-opened) {
  -webkit-transform: translate3d(-100%, 0, 0);
  -moz-transform: translate3d(-100%, 0, 0);
  -ms-transform: translate3d(-100%, 0, 0);
  -o-transform: translate3d(-100%, 0, 0);
  transform: translate3d(-100%, 0, 0); }
.mm-menu.mm-leftsubpanels .mm-panel.mm-subopened {
  -webkit-transform: translate3d(30%, 0, 0);
  -moz-transform: translate3d(30%, 0, 0);
  -ms-transform: translate3d(30%, 0, 0);
  -o-transform: translate3d(30%, 0, 0);
  transform: translate3d(30%, 0, 0); }
  .mm-menu.mm-leftsubpanels .mm-panel.mm-subopened[class*="mm-iconpanel-"] {
    -webkit-transform: translate3d(0, 0, 0);
    -moz-transform: translate3d(0, 0, 0);
    -ms-transform: translate3d(0, 0, 0);
    -o-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0); }
.mm-menu.mm-leftsubpanels .mm-panel[class*="mm-iconpanel-"] {
  left: 0px; }
.mm-menu.mm-leftsubpanels.mm-iconpanel .mm-panel {
  -webkit-transition-property: -webkit-transform, right;
  -moz-transition-property: -moz-transform, right;
  -ms-transition-property: -ms-transform, right;
  -o-transition-property: -o-transform, right;
  transition-property: transform, right; }
  .mm-menu.mm-leftsubpanels.mm-iconpanel .mm-panel.mm-iconpanel-0 {
    right: 0px; }
  .mm-menu.mm-leftsubpanels.mm-iconpanel .mm-panel.mm-iconpanel-1 {
    right: 40px; }
  .mm-menu.mm-leftsubpanels.mm-iconpanel .mm-panel.mm-iconpanel-2 {
    right: 80px; }
  .mm-menu.mm-leftsubpanels.mm-iconpanel .mm-panel.mm-iconpanel-3 {
    right: 120px; }
  .mm-menu.mm-leftsubpanels.mm-iconpanel .mm-panel.mm-iconpanel-4 {
    right: 160px; }
  .mm-menu.mm-leftsubpanels.mm-iconpanel .mm-panel.mm-iconpanel-5 {
    right: 200px; }
  .mm-menu.mm-leftsubpanels.mm-iconpanel .mm-panel.mm-iconpanel-6 {
    right: 240px; }
  .mm-menu.mm-leftsubpanels.mm-iconpanel .mm-panel.mm-opened {
    border-left: none;
    border-right: 1px solid;
    border-color: inherit; }


text:
RockPaperScissors
=================

Android Project


text:
<?PHP
require_once("class.base.php");

class ListenedSong extends Conn{
	// ¹¹Ô캯Êý
	function __construct(){
		parent::__construct();
	}

	function insert($usid){
		$sql = "CALL test($usid)";
		mysql_query($sql, $this->link);
		return mysql_insert_id($this->link);
	}
}

?>


text:
module Metasploit::Model::Search::Operation
  extend ActiveSupport::Autoload

  autoload :Association
  autoload :Base
  autoload :Boolean
  autoload :Date
  autoload :Group
  autoload :Integer
  autoload :Null
  autoload :Set
  autoload :String
  autoload :Value

  # @param options [Hash{Symbol => Object}]
  # @option options [Metasploit::Module::Search::Query] :query The query that the parsed operation is a part.
  # @option options [String] :formatted_operation A '<operator>:<value>' string.
  # @return [Metasploit::Model::Search::Operation::Base, Array<Metasploit::Model::Search::Operation::Base>]
  #   operation(s) parsed from the formatted operation.
  # @raise [KeyError] unless :formatted_operation is given.
  # @raise [KeyError] unless :query is given.
  def self.parse(options={})
    formatted_operation = options.fetch(:formatted_operation)
    query = options.fetch(:query)

    formatted_operator, formatted_value = formatted_operation.split(':', 2)
    operator = query.parse_operator(formatted_operator)

    # formatted_value will be nil if formatted_operation did not contain a ':', it should be treated the same
    # as nothing after the ':'.
    formatted_value ||= ''
    operation_or_operations = operator.operate_on(formatted_value)

    operation_or_operations
  end
end


text:
import wx
import waxyobject

class FileDialog(wx.FileDialog, waxyobject.WaxyObject):

    def __init__(self, parent, title="Choose a file", default_dir="",
                 default_file="", wildcard="*.*", open=0, save=0, multiple=0):
        style = 0
        if open:
            style |= wx.OPEN
        elif save:
            style |= wx.SAVE
            style |= wx.OVERWRITE_PROMPT
        if multiple:
            style |= wx.MULTIPLE

        self.multiple=multiple

        wx.FileDialog.__init__(self, parent, title, default_dir, default_file,
         wildcard, style)

    def ShowModal(self):
        """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """
        result = wx.FileDialog.ShowModal(self)
        if result == wx.ID_OK:
            return 'ok'
        else:
            return 'cancel'

    def GetChosenFile(self):
        """ Shorthand... """
        data = self.GetPaths()

        if not self.multiple:
            data=data[0]

        return data


text:
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function( root, jQuery ) {
            if ( jQuery === undefined ) {
                // require('jQuery') returns a factory that requires window to
                // build a jQuery instance, we normalize how we use modules
                // that require this pattern but the window provided is a noop
                // if it's defined (how jquery works)
                if ( typeof window !== 'undefined' ) {
                    jQuery = require('jquery');
                }
                else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

  'use strict';

  $.FE.PLUGINS.quote = function (editor) {
    function _deepestParent(node) {
      while (node.parentNode && node.parentNode != editor.$el.get(0)) {
        node = node.parentNode;
      }

      return node;
    }

    function _increase () {
      // Get blocks.
      var blocks = editor.selection.blocks();
      var i;

      // Normalize blocks.
      for (i = 0; i < blocks.length; i++) {
        blocks[i] = _deepestParent(blocks[i]);
      }

      // Save selection to restore it later.
      editor.selection.save();

      var $quote = $('<blockquote>');
      $quote.insertBefore(blocks[0]);
      for (i = 0; i < blocks.length; i++) {
        $quote.append(blocks[i]);
      }

      // Unwrap temp divs.
      editor.html.unwrap();

      editor.selection.restore();
    }

    function _decrease () {
      // Get blocks.
      var blocks = editor.selection.blocks();
      var i;

      for (i = 0; i < blocks.length; i++) {
        if (blocks[i].tagName != 'BLOCKQUOTE') {
          blocks[i] = $(blocks[i]).parentsUntil(editor.$el, 'BLOCKQUOTE').get(0);
        }
      }

      editor.selection.save();

      for (i = 0; i < blocks.length; i++) {
        if (blocks[i]) {
          $(blocks[i]).replaceWith(blocks[i].innerHTML);
        }
      }

      // Unwrap temp divs.
      editor.html.unwrap();

      editor.selection.restore();
    }

    function apply (val) {
      // Wrap.
      editor.selection.save();
      editor.html.wrap(true, true, true, true);
      editor.selection.restore();

      if (val == 'increase') {
        _increase();
      }
      else if (val == 'decrease') {
        _decrease();
      }

    }

    return {
      apply: apply
    }
  }

  // Register the quote command.
  $.FE.RegisterShortcut($.FE.KEYCODE.SINGLE_QUOTE, 'quote', 'increase', '\'');
  $.FE.RegisterShortcut($.FE.KEYCODE.SINGLE_QUOTE, 'quote', 'decrease', '\'', true);
  $.FE.RegisterCommand('quote', {
    title: 'Quote',
    type: 'dropdown',
    options: {
      increase: 'Increase',
      decrease: 'Decrease'
    },
    callback: function (cmd, val) {
      this.quote.apply(val);
    },
    plugin: 'quote'
  })

  // Add the quote icon.
  $.FE.DefineIcon('quote', {
    NAME: 'quote-left'
  });

}));


text:
/*!
 *  Copyright (c) 2016 by Contributors
 * \file initialize.cc
 * \brief initialize mxnet library
 */
#include <signal.h>
#include <dmlc/logging.h>
#include <mxnet/engine.h>
#include "engine/profiler.h"

namespace mxnet {
#if MXNET_USE_SIGNAL_HANDLER && DMLC_LOG_STACK_TRACE
static void SegfaultLogger(int sig) {
  fprintf(stderr, "\nSegmentation fault: %d\n\n", sig);
  fprintf(stderr, "%s", dmlc::StackTrace().c_str());
  exit(-1);
}
#endif

class LibraryInitializer {
 public:
  LibraryInitializer() {
    dmlc::InitLogging("mxnet");
#if MXNET_USE_SIGNAL_HANDLER && DMLC_LOG_STACK_TRACE
    signal(SIGSEGV, SegfaultLogger);
#endif
#if MXNET_USE_PROFILER
    // ensure profiler's constructor are called before atexit.
    engine::Profiler::Get();
    // DumpProfile will be called before engine's and profiler's destructor.
    std::atexit([](){
      engine::Profiler* profiler = engine::Profiler::Get();
      if (profiler->IsEnableOutput()) {
        profiler->DumpProfile();
      }
    });
#endif
  }

  static LibraryInitializer* Get();
};

LibraryInitializer* LibraryInitializer::Get() {
  static LibraryInitializer inst;
  return &inst;
}

#ifdef __GNUC__
// Don't print an unused variable message since this is intentional
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif

static LibraryInitializer* __library_init = LibraryInitializer::Get();
}  // namespace mxnet


text:
package org.hswebframework.web.database.mamager;

import org.hswebframework.ezorm.rdb.executor.SqlExecutor;
import org.hswebframework.ezorm.rdb.meta.parser.OracleTableMetaParser;
import org.hswebframework.web.database.manager.meta.ObjectMetadata;
import org.hswebframework.web.database.manager.meta.table.parser.MetaDataParserRegister;
import org.hswebframework.web.database.manager.meta.table.parser.MetaDataParserSupplier;
import org.hswebframework.web.database.manager.meta.table.parser.TableMetaDataParser;
import org.hswebframework.web.database.manager.meta.table.parser.support.H2TableMetaDataParser;
import org.hswebframework.web.database.manager.meta.table.parser.support.MysqlTableMetaDataParser;
import org.hswebframework.web.database.manager.meta.table.parser.support.SqlServerTableMetaDataParser;
import org.hswebframework.web.datasource.DatabaseType;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TableMetaDataParserAutoConfiguration {

    @Autowired
    private SqlExecutor sqlExecutor;

    @Autowired
    private MetaDataParserRegister metaDataParserRegister;

    @Bean
    @ConditionalOnClass(name = "org.h2.Driver")
    public H2TableMetaDataParser h2TableMetaDataParser() {
        return new H2TableMetaDataParser(sqlExecutor);
    }

    @Bean
    @ConditionalOnClass(name = "com.mysql.jdbc.Driver")
    public MysqlTableMetaDataParser mysqlTableMetaDataParser() {
        return new MysqlTableMetaDataParser(sqlExecutor);
    }

    @Bean
    @ConditionalOnClass(name = "oracle.jdbc.driver.OracleDriver")
    public OracleTableMetaParser oracleTableMetaParser() {
        return new OracleTableMetaParser(sqlExecutor);
    }

    @Bean
    @ConditionalOnClass(name = "com.microsoft.sqlserver.jdbc.SQLServerDriver")
    public SqlServerTableMetaDataParser sqlServerTableMetaDataParser() {
        return new SqlServerTableMetaDataParser(sqlExecutor);
    }

    @Bean
    @ConditionalOnClass(name = "net.sourceforge.jtds.jdbc.Driver")
    public SqlServerTableMetaDataParser jstdSqlServerTableMetaDataParser() {
        return new SqlServerTableMetaDataParser(sqlExecutor);
    }

    @Bean
    public BeanPostProcessor tableMetaDataAutoParserRegister() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
                return o;
            }

            @Override
            @SuppressWarnings("unchecked")
            public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
                if (o instanceof MetaDataParserSupplier) {
                    MetaDataParserSupplier<? extends TableMetaDataParser> supplier = ((MetaDataParserSupplier) o);
                    for (DatabaseType databaseType : DatabaseType.values()) {
                        if (supplier.isSupport(databaseType)) {
                            metaDataParserRegister.registerMetaDataParser(databaseType, ObjectMetadata.ObjectType.TABLE, supplier.get());
                        }
                    }
                }
                return o;
            }
        };
    }
}


text:
.class public Landroid/os/BatteryStats$Uid$Pid;
.super Ljava/lang/Object;
.source "BatteryStats.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/os/BatteryStats$Uid;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1
    name = "Pid"
.end annotation

# instance fields
.field public mWakeNesting:I

.field public mWakeStartMs:J

.field public mWakeSumMs:J

.field final synthetic this$0:Landroid/os/BatteryStats$Uid;

# direct methods
.method public constructor <init>(Landroid/os/BatteryStats$Uid;)V
    .locals 0

    .prologue
    .line 439
    iput-object p1, p0, Landroid/os/BatteryStats$Uid$Pid;->this$0:Landroid/os/BatteryStats$Uid;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
[![Build Status](https://dev.azure.com/screendriver/cp-cli/_apis/build/status/screendriver.cp-cli?branchName=master)](https://dev.azure.com/screendriver/cp-cli/_build/latest?definitionId=8&branchName=master)
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat)](https://github.com/prettier/prettier)

## This GitHub project has been archived in favour of

- [cpy-cli](https://github.com/sindresorhus/cpy-cli)
- [ncp](https://github.com/AvianFlu/ncp)
- [cpx](https://github.com/mysticatea/cpx)

---

The [UNIX command](<https://en.wikipedia.org/wiki/Cp_(Unix)>) `cp` for Node.js
which is useful for cross platform support.

Just install it with

```sh
$ npm install -g cp-cli
```

After that you can use `cp-cli` from your command prompt

```sh
$ cp-cli
Usage: cp-cli [-d] source target

Options:
  -d, --dereference  Dereference symlinks  [boolean]
```

You can copy files directly

```sh
$ cp-cli foo.txt bar.txt
```

or copy a file into an existing directory

```sh
$ cp-cli foo.text dest/
```


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef nsILineIterator_h___
#define nsILineIterator_h___

#include "nscore.h"
#include "nsPoint.h"
#include "mozilla/Attributes.h"

class nsIFrame;
struct nsRect;

/**
 * Line iterator API.
 *
 * Lines are numbered from 0 to N, where 0 is the top line and N is
 * the bottom line.
 *
 * Obtain this interface from frames via nsIFrame::GetLineIterator.
 * When you are finished using the iterator, call DisposeLineIterator()
 * to destroy the iterator if appropriate.
 */
class nsILineIterator
{
protected:
  ~nsILineIterator() { }

public:
  virtual void DisposeLineIterator() = 0;

  /**
   * The number of lines in the block
   */
  virtual int32_t GetNumLines() = 0;

  /**
   * The prevailing direction of lines.
   *
   * @return true if the CSS direction property for the block is
   *         "rtl", otherwise false
   *
   *XXX after bug 924851 change this to return a UBiDiDirection
   */
  virtual bool GetDirection() = 0;

  // Return structural information about a line. aFirstFrameOnLine is
  // the first frame on the line and aNumFramesOnLine is the number of
  // frames that are on the line. If the line-number is invalid then
  // aFirstFrameOnLine will be nullptr and aNumFramesOnLine will be
  // zero.
  //
  // For valid line numbers, aLineBounds is set to the bounding box of
  // the line (which is based on the in-flow position of the frames on
  // the line; if a frame was moved because of relative positioning
  // then its coordinates may be outside the line bounds).
  NS_IMETHOD GetLine(int32_t aLineNumber,
                     nsIFrame** aFirstFrameOnLine,
                     int32_t* aNumFramesOnLine,
                     nsRect& aLineBounds) = 0;

  /**
   * Given a frame that's a child of the block, find which line its on
   * and return that line index, as long as it's at least as big as
   * aStartLine.  Returns -1 if the frame cannot be found on lines
   * starting with aStartLine.
   */
  virtual int32_t FindLineContaining(nsIFrame* aFrame,
                                     int32_t aStartLine = 0) = 0;

  // Given a line number and a coordinate, find the frame on the line
  // that is nearest to aPos along the inline axis. (The block-axis coord
  // of aPos is irrelevant.)
  // The aPosIsBeforeFirstFrame and aPosIsAfterLastFrame flags are updated
  // appropriately.
  NS_IMETHOD FindFrameAt(int32_t aLineNumber,
                         nsPoint aPos,
                         nsIFrame** aFrameFound,
                         bool* aPosIsBeforeFirstFrame,
                         bool* aPosIsAfterLastFrame) = 0;

  // Give the line iterator implementor a chance todo something more complicated than
  // nsIFrame::GetNextSibling()
  NS_IMETHOD GetNextSiblingOnLine(nsIFrame*& aFrame, int32_t aLineNumber) = 0;

  // Check whether visual and logical order of frames within a line are identical.
  //  If not, return the first and last visual frames
  NS_IMETHOD CheckLineOrder(int32_t                  aLine,
                            bool                     *aIsReordered,
                            nsIFrame                 **aFirstVisual,
                            nsIFrame                 **aLastVisual) = 0;
};

class nsAutoLineIterator
{
public:
  nsAutoLineIterator() : mRawPtr(nullptr) { }
  MOZ_IMPLICIT nsAutoLineIterator(nsILineIterator *i) : mRawPtr(i) { }

  ~nsAutoLineIterator() {
    if (mRawPtr)
      mRawPtr->DisposeLineIterator();
  }

  operator nsILineIterator*() { return mRawPtr; }
  nsILineIterator* operator->() { return mRawPtr; }

  nsILineIterator* operator=(nsILineIterator* i) {
    if (i == mRawPtr)
      return i;

    if (mRawPtr)
      mRawPtr->DisposeLineIterator();

    mRawPtr = i;
    return i;
  }

private:
  nsILineIterator* mRawPtr;
};

#endif /* nsILineIterator_h___ */


text:
using UnityEngine;
using UnityEngine.Audio;

namespace OVR
{

public enum SoundFXNext {
	Random = 0,
	Sequential = 1,
}

public enum FreqHint {
	None = 0,
	Wide = 1,
	Narrow = 2,
}

public enum SoundPriority {
	VeryLow = -2,
	Low = -1,
	Default = 0,
	High = 1,
	VeryHigh = 2,
}

[System.Serializable]
public class OSPProps {
	public OSPProps() {
        enableSpatialization = false;
		useFastOverride = false;
		gain = 0.0f;
        enableInvSquare = false;
        volumetric = 0.0f;
		invSquareFalloff = new Vector2( 1.0f, 25.0f );
	}

	[Tooltip( "Set to true to play the sound FX spatialized with binaural HRTF, default = false")]
    public bool enableSpatialization = false;
	[Tooltip( "Play the sound FX with reflections, default = false")]
	public bool			useFastOverride = false;
	[Tooltip( "Boost the gain on the spatialized sound FX, default = 0.0")]
	[Range( 0.0f, 24.0f )]
	public float		gain = 0.0f;
    [Tooltip("Enable Inverse Square attenuation curve, default = false")]
    public bool         enableInvSquare = false;
    [Tooltip("Change the sound from point source (0.0f) to a spherical volume, default = 0.0")]
    [Range(0.0f, 1000.0f)]
    public float volumetric = 0.0f;
    [Tooltip("Set the near and far falloff value for the OSP attenuation curve, default = 1.0")]
	[MinMax ( 1.0f, 25.0f, 0.0f, 250.0f )]
	public Vector2		invSquareFalloff = new Vector2( 1.0f, 25.0f );
}

/*
-----------------------

SoundFX

-----------------------
*/
[System.Serializable]
public class SoundFX {
	public SoundFX() {
		playback = SoundFXNext.Random;
		volume = 1.0f;
		pitchVariance = Vector2.one;
		falloffDistance = new Vector2( 1.0f, 25.0f );
		falloffCurve = AudioRolloffMode.Linear;
		volumeFalloffCurve = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } );
		reverbZoneMix = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } );
		spread = 0.0f;
		pctChanceToPlay = 1.0f;
		priority = SoundPriority.Default;
		delay = Vector2.zero;
		looping = false;
		ospProps = new OSPProps();
	}

	[Tooltip( "Each sound FX should have a unique name")]
	public string			name = string.Empty;
	[Tooltip( "Sound diversity playback option when multiple audio clips are defined, default = Random")]
	public SoundFXNext		playback = SoundFXNext.Random;
	[Tooltip( "Default volume for this sound FX, default = 1.0")]
	[Range (0.0f, 1.0f)]
	public float			volume = 1.0f;
	[Tooltip( "Random pitch variance each time a sound FX is played, default = 1.0 (none)")]
	[MinMax ( 1.0f, 1.0f, 0.0f, 2.0f )]
	public Vector2			pitchVariance = Vector2.one;
	[Tooltip( "Falloff distance for the sound FX, default = 1m min to 25m max")]
	[MinMax ( 1.0f, 25.0f, 0.0f, 250.0f )]
	public Vector2			falloffDistance = new Vector2( 1.0f, 25.0f );
	[Tooltip( "Volume falloff curve - sets how the sound FX attenuates over distance, default = Linear")]
	public AudioRolloffMode	falloffCurve = AudioRolloffMode.Linear;
	[Tooltip( "Defines the custom volume falloff curve")]
	public AnimationCurve   volumeFalloffCurve = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } );
	[Tooltip( "The amount by which the signal from the AudioSource will be mixed into the global reverb associated with the Reverb Zones | Valid range is 0.0 - 1.1, default = 1.0" )]
	public AnimationCurve   reverbZoneMix = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } );
	[Tooltip( "Sets the spread angle (in degrees) of a 3d stereo or multichannel sound in speaker space, default = 0")]
	[Range (0.0f, 360.0f)]
	public float			spread = 0.0f;
	[Tooltip( "The percentage chance that this sound FX will play | 0.0 = none, 1.0 = 100%, default = 1.0")]
	[Range (0.0f, 1.0f)]
	public float			pctChanceToPlay = 1.0f;
	[Tooltip( "Sets the priority for this sound to play and/or to override a currently playing sound FX, default = Default")]
	public SoundPriority	priority = SoundPriority.Default;
	[Tooltip( "Specifies the default delay when this sound FX is played, default = 0.0 secs")]
	[MinMax ( 0.0f, 0.0f, 0.0f, 2.0f )]
	public Vector2          delay = Vector2.zero;   // this overrides any delay passed into PlaySound() or PlaySoundAt()
	[Tooltip( "Set to true for the sound to loop continuously, default = false")]
	public bool				looping = false;
	public OSPProps			ospProps = new OSPProps();
	[Tooltip( "List of the audio clips assigned to this sound FX")]
	public AudioClip[]		soundClips = new AudioClip[1];
	// editor only - unfortunately if we set it not to serialize, we can't query it from the editor
	public bool             visibilityToggle = false;
	// runtime vars
	[System.NonSerialized]
	private SoundGroup      soundGroup = null;
	private int				lastIdx = -1;
	private int				playingIdx = -1;

	public int 				Length { get { return soundClips.Length; } }
	public bool				IsValid { get { return ( ( soundClips.Length != 0 ) && ( soundClips[0] != null ) ); } }
	public SoundGroup		Group { get { return soundGroup; } set { soundGroup = value; } }
	public float			MaxFalloffDistSquared { get { return falloffDistance.y * falloffDistance.y; } }
	public float			GroupVolumeOverride { get { return ( soundGroup != null ) ? soundGroup.volumeOverride : 1.0f; } }

	/*
	-----------------------
	GetClip()
	-----------------------
	*/
	public AudioClip GetClip() {
		if ( soundClips.Length == 0 ) {
			return null;
		} else if ( soundClips.Length == 1 ) {
			return soundClips[0];
		}
		if ( playback == SoundFXNext.Random ) {
			// random, but don't pick the last one
			int idx = Random.Range( 0, soundClips.Length );
			while ( idx == lastIdx ) {
				idx = Random.Range( 0, soundClips.Length );
			}
			lastIdx = idx;
			return soundClips[idx];
		} else {
			// sequential
			if ( ++lastIdx >= soundClips.Length ) {
				lastIdx = 0;
			}
			return soundClips[lastIdx];
		}
	}

	/*
	-----------------------
	GetMixerGroup()
	-----------------------
	*/
	public AudioMixerGroup GetMixerGroup( AudioMixerGroup defaultMixerGroup ) {
		if ( soundGroup != null ) {
			return ( soundGroup.mixerGroup != null ) ? soundGroup.mixerGroup : defaultMixerGroup;
		}
		return defaultMixerGroup;
	}

	/*
	-----------------------
	ReachedGroupPlayLimit()
	-----------------------
	*/
	public bool ReachedGroupPlayLimit() {
		if ( soundGroup != null ) {
			return !soundGroup.CanPlaySound();
		}
		return false;
	}

	/*
	-----------------------
	GetClipLength()
	-----------------------
	*/
	public float GetClipLength( int idx ) {
		if ( ( idx == -1 ) || ( soundClips.Length == 0 ) || ( idx >= soundClips.Length ) || ( soundClips[idx] == null ) ) {
			return 0.0f;
		} else {
			return soundClips[idx].length;
		}
	}

	/*
	-----------------------
	GetPitch()
	-----------------------
	*/
	public float GetPitch() {
		return Random.Range( pitchVariance.x, pitchVariance.y );
	}

	/*
	-----------------------
	PlaySound()
	-----------------------
	*/
	public int PlaySound( float delaySecs = 0.0f ) {
		playingIdx = -1;

		if ( !IsValid ) {
			return playingIdx;
		}

		// check the random chance to play here to save the function calls
		if ( ( pctChanceToPlay > 0.99f ) || ( Random.value < pctChanceToPlay ) ) {
			if ( delay.y > 0.0f ) {
				delaySecs = Random.Range( delay.x, delay.y );
			}
			playingIdx = AudioManager.PlaySound( this, EmitterChannel.Any, delaySecs );
		}

		return playingIdx;
	}

	/*
	-----------------------
	PlaySoundAt()
	-----------------------
	*/
	public int PlaySoundAt( Vector3 pos, float delaySecs = 0.0f, float volumeOverride = 1.0f, float pitchMultiplier = 1.0f ) {
		playingIdx = -1;

		if ( !IsValid ) {
			return playingIdx;
		}

		// check the random chance to play here to save the function calls
		if ( ( pctChanceToPlay > 0.99f ) || ( Random.value < pctChanceToPlay ) ) {
			if ( delay.y > 0.0f ) {
				delaySecs = Random.Range( delay.x, delay.y );
			}
			playingIdx = AudioManager.PlaySoundAt( pos, this, EmitterChannel.Any, delaySecs, volumeOverride, pitchMultiplier );
		}

		return playingIdx;
	}

	/*
	-----------------------
	SetOnFinished()
	get a callback when the sound is finished playing
	-----------------------
	*/
	public void SetOnFinished( System.Action onFinished ) {
		if ( playingIdx > -1 ) {
			AudioManager.SetOnFinished( playingIdx, onFinished );
		}
	}

	/*
	-----------------------
	SetOnFinished()
	get a callback with an object parameter when the sound is finished playing
	-----------------------
	*/
	public void SetOnFinished( System.Action<object> onFinished, object obj ) {
		if ( playingIdx > -1 ) {
			AudioManager.SetOnFinished( playingIdx, onFinished, obj );
		}
	}

	/*
	-----------------------
	StopSound()
	-----------------------
	*/
	public bool StopSound() {
		bool stopped = false;

		if (playingIdx > -1){
			stopped = AudioManager.StopSound(playingIdx);
			playingIdx = -1;
		}

		return stopped;
	}

	/*
	-----------------------
	AttachToParent()
	-----------------------
	*/
	public void AttachToParent( Transform parent) {
		if (playingIdx > -1) {
			AudioManager.AttachSoundToParent(playingIdx, parent);
		}
	}

	/*
	-----------------------
	DetachFromParent()
	-----------------------
	*/
	public void DetachFromParent() {
		if (playingIdx > -1) {
			AudioManager.DetachSoundFromParent(playingIdx);
		}
	}
}

} // namespace OVR


text:
@implementation SDLShowConstantTBTResponse

-(id) init {
    if (self = [super initWithName:NAMES_ShowConstantTBT]) {}
    return self;
}

-(id) initWithDictionary:(NSMutableDictionary*) dict {
    if (self = [super initWithDictionary:dict]) {}
    return self;
}

@end


text:
ALTER TABLE `vms` ADD `locked` VARCHAR(11) NOT NULL DEFAULT 'false' AFTER `os_type`;
UPDATE `config` SET `valuechar`='20160831001' WHERE `name`='dbversion';


text:
const resolveDependencies = require('./resolveDependencies');

const getEnv = ({target, uglify}) => {
  switch (target) {
    case 'node':
      return [['env', {targets: {node: 4, uglify}}]];
    case 'web':
      return [['env', {targets: {browsers: ['last 2 versions', 'safari >= 7'], uglify}}]];
    default:
      return [];
  }
};

const getPresets = ({react, reactNative}) => {
  return [
    react && 'react',
    reactNative && 'react-native',
  ];
};

const getPlugins = ({target}) => {
  switch (target) {
    case 'node':
      return ['runtime'];
    default:
      return [];
  }
};

// These are the plugins that are shared with all targets.
// NOTE(mark): Decorators MUST come before class properties.
const sharedPlugins = [
  'decorators-legacy',

  ['builtin-extend', {globals: ['Array', 'Error']}],
  'class-properties',
  'export-extensions',
  'object-rest-spread',
];

const getCustomPlugins = ({useStaticImport}) => {
  return [
    useStaticImport && require('./transforms/static-import'),
  ];
};

module.exports = (context, options = {}) => { // eslint-disable-line
  const {
    target,
    react = false,
    reactNative = false,
    uglify = false,
    useStaticImport = false,
  } = options;

  return {
    // Remove comments and compact the code.
    comments: false,
    compact: true,

    presets: [
      ...resolveDependencies('babel-preset', getEnv({target, uglify})),
      ...resolveDependencies('babel-preset', getPresets({react, reactNative})),
    ].filter(Boolean),
    plugins: [
      // Built-in babel plugin transforms.
      ...resolveDependencies('babel-plugin-transform', sharedPlugins),
      ...resolveDependencies('babel-plugin-transform', getPlugins({target})),

      // Custom babel plugin transforms.
      ...getCustomPlugins({useStaticImport}),
    ].filter(Boolean),
  };
};


text:
// Copyright 2017 The Lynx Authors. All rights reserved.
package com.lynx.core.base;

import android.support.annotation.NonNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Uses for saving fields and methods, which is convenient for
 * method invoking and field setting
 */

/* package */ public class JavaCenter {
    private static JavaCenter sCenter;
    // Uses for finding the matched method while params need to be transformed
    private Map<Class<?>, Map<String, List<JavaMethod>>> mMethods;
    // Uses for finding the matched method fast
    private Map<Class<?>, Map<String, JavaMethod>> mSignatureMethods;
    private Map<Class<?>, Map<String, JavaField>> mFields;

    public synchronized static JavaCenter link() {
        if (sCenter == null) {
            sCenter = new JavaCenter();
        }
        return sCenter;
    }

    public JavaCenter() {
        mMethods = new HashMap<>();
        mSignatureMethods = new HashMap<>();
        mFields = new HashMap<>();
    }

    public boolean hasRegistered(Class clazz) {
        if (mMethods.containsKey(clazz)
                || mFields.containsKey(clazz)
                || mSignatureMethods.containsKey(clazz)) {
            return true;
        }
        return false;
    }

    public Map<String, List<JavaMethod>> getMethods(Class clazz) {
        return mMethods.get(clazz);
    }

    public void registerMethod(JavaMethod method) {
        Map<String, List<JavaMethod>> methodMap = mMethods.get(method.getDeclaringClass());
        if (methodMap == null) {
            methodMap = new HashMap<>();
            mMethods.put(method.getDeclaringClass(), methodMap);
        }
        List<JavaMethod> methodList = methodMap.get(method.getName());
        if (methodList == null) {
            methodList = new ArrayList<>();
            methodMap.put(method.getName(), methodList);
        }
        methodList.add(method);

        registerAsSignatureMethod(method);
    }

    private void registerAsSignatureMethod(JavaMethod method) {
        Map<String, JavaMethod> methodMap = mSignatureMethods.get(method.getDeclaringClass());
        if (methodMap == null) {
            methodMap = new HashMap<>();
            mSignatureMethods.put(method.getDeclaringClass(), methodMap);
        }
        methodMap.put(method.getSignature(), method);
    }

    public void registerField(JavaField field) {
        Map<String, JavaField> fieldMap = mFields.get(field.getDeclaringClass());
        if (fieldMap == null) {
            fieldMap = new HashMap<>();
            mFields.put(field.getDeclaringClass(), fieldMap);
        }
        if (!fieldMap.containsKey(field.getName())) {
            fieldMap.put(field.getName(), field);
        }
    }

    public JavaMethod findMethod(Object receiver, String methodName, Object... args) {
        if (mMethods.get(receiver.getClass()) == null) {
            return null;
        }
        String signature = JavaMethod.generateSignature(methodName, args);
        // First check width signature
        JavaMethod targetMethod = mSignatureMethods.get(receiver.getClass()).get(signature);
        if (targetMethod == null) {
            // Second find match method
            targetMethod = findMatchedMethod(receiver, methodName, args);
        }
        return targetMethod;
    }

    private JavaMethod findMatchedMethod(Object receiver, String methodName, Object[] args) {

        List<JavaMethod> methods = mMethods.get(receiver.getClass()).get(methodName);
        for (JavaMethod method : methods) {
            if (method.getParameterTypes().isMatchedWith(args)) {
                return method;
            }
        }
        return null;
    }

    public JavaField findField(@NonNull Object receiver, String field) {
        return findField(receiver.getClass(), field);
    }

    public JavaField findField(@NonNull Class receiver, String field) {
        if (mFields.get(receiver) == null) {
            return null;
        }
        return mFields.get(receiver).get(field);
    }
}


text:
package com.facebook.buck.shell;

import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.AbstractNodeBuilder;
import com.facebook.buck.rules.SourcePath;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;

public class ShBinaryBuilder extends AbstractNodeBuilder<ShBinaryDescription.Arg> {

  public ShBinaryBuilder(BuildTarget target) {
    super(new ShBinaryDescription(), target);
  }

  public ShBinaryBuilder setMain(SourcePath path) {
    arg.main = path;
    return this;
  }

  public ShBinaryBuilder setDeps(ImmutableSortedSet<BuildTarget> deps) {
    arg.deps = Optional.of(deps);
    return this;
  }

  public ShBinaryBuilder setResources(ImmutableSet<SourcePath> resources) {
    arg.resources = Optional.of(resources);
    return this;
  }

}


text:
from playwright.sync_api import expect
from context_managers import check_for_console_errors

def test_api(page, live_server):
    with check_for_console_errors(page):
        page.goto(f"{live_server.url}/api")
        expect(page.locator("text=wheredoivote.co.uk Beta API")).not_to_be_empty()

def test_api_beta(page, live_server):
    with check_for_console_errors(page):
        page.goto(f"{live_server.url}/api/beta")
        expect(page.locator("h1")).to_have_text("Api Root")

def test_email_mailing_list(page, live_server):
    with check_for_console_errors(page):
        page.goto(f"{live_server.url}/email/mailing_list")
        expect(page.locator("h3")).to_have_text("Join our mailing list")

def test_feedback(page, live_server):
    with check_for_console_errors(page):
        page.goto(f"{live_server.url}/feedback")
        expect(page.locator("text=Did you find this useful?"))

def test_report_problem(page, live_server):
    with check_for_console_errors(page):
        page.goto(f"{live_server.url}/report_problem")
        expect(page.locator("h3")).to_have_text("Report a Problem")

def test_embed(page, live_server):
    with check_for_console_errors(page):
        page.goto(f"{live_server.url}/embed")
        expect(page.locator("text=Enter your postcode")).not_to_be_empty()

def test_example(page, live_server):
    with check_for_console_errors(page):
        page.goto(f"{live_server.url}/example")
        expect(page.locator("h2")).to_have_text("Your polling station")


text:
package org.jboss.resteasy.plugins.guice;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer;
import org.jboss.resteasy.test.TestPortProvider;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Module;

public class ResourceTest
{
   private static NettyJaxrsServer server;
   private static Dispatcher dispatcher;

   @BeforeClass
   public static void beforeClass() throws Exception
   {
      server = new NettyJaxrsServer();
      server.setPort(TestPortProvider.getPort());
      server.setRootResourcePath("/");
      server.start();
      dispatcher = server.getDeployment().getDispatcher();
   }

   @AfterClass
   public static void afterClass() throws Exception
   {
      server.stop();
      server = null;
      dispatcher = null;
   }

   @Test
   public void testResourceRegistered()
   {
      final Module module = new Module()
      {
         @Override
         public void configure(final Binder binder)
         {
            binder.bind(TestResource.class).to(TestResourceSimple.class);
         }
      };
      final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
      processor.processInjector(Guice.createInjector(module));
      final TestResource resource = TestPortProvider.createProxy(TestResource.class, TestPortProvider.generateBaseUrl());
      Assert.assertEquals("name", resource.getName());
      dispatcher.getRegistry().removeRegistrations(TestResource.class);
   }

   @Test
   public void testResourceInjected()
   {
      final Module module = new Module()
      {
         @Override
         public void configure(final Binder binder)
         {
            binder.bind(String.class).toInstance("injected-name");
            binder.bind(TestResource.class).to(TestResourceInjected.class);
         }
      };
      final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
      processor.processInjector(Guice.createInjector(module));
      final TestResource resource = TestPortProvider.createProxy(TestResource.class, TestPortProvider.generateBaseUrl());
      Assert.assertEquals("injected-name", resource.getName());
      dispatcher.getRegistry().removeRegistrations(TestResource.class);
   }

   @Path("test")
   public interface TestResource
   {
      @GET
      public String getName();
   }

   public static class TestResourceSimple implements TestResource
   {
      @Override
      public String getName()
      {
         return "name";
      }
   }

   public static class TestResourceInjected implements TestResource
   {
      private final String name;

      @Inject
      public TestResourceInjected(final String name)
      {
         this.name = name;
      }

      @Override
      public String getName()
      {
         return name;
      }
   }
}


text:
package com.astro.androidtuts;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

public class Imagebutton extends Activity {

	ImageButton button;
	RelativeLayout layout;
	int set = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_imagebutton);

		button =(ImageButton)findViewById(R.id.imageButton1);
		layout =(RelativeLayout)findViewById(R.id.change);

		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (set == 0) {
					layout.setBackgroundColor(Color.WHITE);
					set = 1;
				}else {
					String color = "#ececec";
					layout.setBackgroundColor(Color.parseColor(color));
					set = 0;
				}

			}
		});

	}

}


text:
package com.lucilu.rxdynamicsearch.activities.base;

import com.lucilu.rxdynamicsearch.IInjectable;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import rx.subscriptions.CompositeSubscription;

/**
 * This base activity provides the common functionality to all activities in the app.
 */
public abstract class BaseActivity extends AppCompatActivity implements IInjectable {

    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        onInject();
    }

    protected abstract void onBind(@NonNull final CompositeSubscription subscription);
}


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

package com.google.security.zynamics.binnavi.Database.PostgreSQL.Notifications.containers;

import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.Database.PostgreSQL.Notifications.interfaces.CommentNotification;
import com.google.security.zynamics.binnavi.disassembly.CommentManager.CommentOperation;
import com.google.security.zynamics.binnavi.disassembly.CommentManager.CommentScope;

/**
 * This class implements the common methods for {@link CommentNotification comment notifications}.
 */
public abstract class AbstractScopedCommentNotification extends AbstractCommentNotification {

  private final CommentScope scope;

  public AbstractScopedCommentNotification(
      final CommentOperation operation, final Integer commentId, final CommentScope scope) {
    super(operation, commentId);
    this.scope = Preconditions.checkNotNull(scope, "Error: Scope argument can not be null.");
  }

  public CommentScope getScope() {
    return scope;
  }
}


text:
/******************************************************************************
 * history *
******************************************************************************/
#define __INIC_IPC_MSG_QUEUE_C__

/* -------------------------------- Includes -------------------------------- */
/* external head files */

/* internal head files */
#include "inic_ipc_msg_queue.h"

/* -------------------------------- Defines --------------------------------- */
#define IPC_MSG_QUEUE_DEPTH (10)
#define IPC_MSG_QUEUE_WARNING_DEPTH (4)

/* -------------------------------- Macros ---------------------------------- */

/* ------------------------------- Data Types ------------------------------- */
/* node to store the message to the queue. */
struct ipc_msg_node {
	_list list;
	inic_ipc_ex_msg_t ipc_msg; /* to store ipc message */
	u8 is_used; /* sign whether to be used */
};

/* message queue priv */
struct ipc_msg_q_priv {
	_queue msg_queue; /* msg queue */
	_sema msg_q_sema;
	_sema msg_send_sema;
	void (*task_hdl)(inic_ipc_ex_msg_t *); /* the haddle function of task */
	u8 b_queue_working; /* flag to notice the queue is working */
	struct ipc_msg_node ipc_msg_pool[IPC_MSG_QUEUE_DEPTH]; /* static pool for queue node */
	u8 queue_free; /* the free size of queue */
	u8 rsvd[40]; /* keep total size 64B alignment */
};

/* -------------------------- Function declaration -------------------------- */

/* ---------------------------- Global Variables ---------------------------- */

/* --------------------------- Private Variables ---------------------------- */

static struct ipc_msg_q_priv g_ipc_msg_q_priv __attribute__((aligned(64)));
#ifdef IPC_DIR_MSG_TX
inic_ipc_ex_msg_t g_inic_ipc_ex_msg __attribute__((aligned(64)));
IPC_MSG_64_STRUCT g_inic_ipc_msg __attribute__((aligned(64)));
#else
static inic_ipc_ex_msg_t g_inic_ipc_ex_msg = {0};
#endif
#if defined(configNUM_CORES) && (configNUM_CORES > 1)
static spinlock_t ipc_msg_queue_lock = {0};
#endif
struct task_struct ipc_msgQ_wlan_task;
/* ---------------------------- Private Functions --------------------------- */
/**
 * @brief  put the ipc message to queue.
 * @param  p_node[in]: the pointer for the ipc message node that need to be
 * 	pushed into the queue.
 * @param  p_queue[in]: the queue used to store the p_node.
 * @return status, always _SUCCESS.
 */
static sint enqueue_ipc_msg_node(struct ipc_msg_node *p_node, _queue *p_queue)
{
#if defined(configNUM_CORES) && (configNUM_CORES > 1)
	/* this function is called in ISR, no need to mask interrupt since gic already do it*/
	spin_lock(&ipc_msg_queue_lock);
#else
	_irqL irqL;
	rtw_enter_critical(&(p_queue->lock), &irqL);
#endif
	/* put the ipc message to the tail of the queue */
	rtw_list_insert_tail(&(p_node->list), get_list_head(p_queue));
#if defined(configNUM_CORES) && (configNUM_CORES > 1)
	spin_unlock(&ipc_msg_queue_lock);
#else
	rtw_exit_critical(&(p_queue->lock), &irqL);
#endif
	return _SUCCESS;
}

/**
 * @brief  get the ipc message from queue.
 * @param  p_ipc_msg[in]: the queue used to store the p_node.
 * @return the ipc_msg_node got from message queue.
 */
static struct ipc_msg_node *dequeue_ipc_msg_node(_queue *p_queue)
{
	struct ipc_msg_node *p_node;
	_list *plist, *phead;

#if defined(configNUM_CORES) && (configNUM_CORES > 1)
	u32 isr_status = portDISABLE_INTERRUPTS();
	spin_lock(&ipc_msg_queue_lock);
#else
	_irqL irqL;
	rtw_enter_critical(&(p_queue->lock), &irqL);
#endif

	if (rtw_queue_empty(p_queue) == _TRUE) {
		p_node = NULL;
	} else {
		phead = get_list_head(p_queue);
		plist = get_next(phead);
		p_node = LIST_CONTAINOR(plist, struct ipc_msg_node, list);
		rtw_list_delete(&(p_node->list));
	}

#if defined(configNUM_CORES) && (configNUM_CORES > 1)
	spin_unlock(&ipc_msg_queue_lock);
	portRESTORE_INTERRUPTS(isr_status);
#else
	rtw_exit_critical(&(p_queue->lock), &irqL);
#endif

	return p_node;
}

/**
 * @brief  task to operation the queue when the queue is not empty.
 * @param  none
 * @return none
 */
static void inic_ipc_msg_q_task(void)
{
	struct ipc_msg_node *p_node = NULL;
	_queue *p_queue = NULL;

	p_queue = &g_ipc_msg_q_priv.msg_queue;
	do {
		//xSemaphoreTake(g_ipc_msg_q_priv.msg_q_sema, 0xFFFFFFFF);
		rtw_down_sema(&g_ipc_msg_q_priv.msg_q_sema);
		/* get the data from tx queue. */
		p_node = dequeue_ipc_msg_node(p_queue);
		while (p_node) {
			/* haddle the message */
			if (g_ipc_msg_q_priv.task_hdl) {
				g_ipc_msg_q_priv.task_hdl(&(p_node->ipc_msg));
			}
			/* release the memory for this ipc message. */
			p_node->is_used = 0;
#if defined(configNUM_CORES) && (configNUM_CORES > 1)
			u32 isr_status = portDISABLE_INTERRUPTS();
			spin_lock(&ipc_msg_queue_lock);
#else
			rtw_enter_critical(NULL, NULL);
#endif
			g_ipc_msg_q_priv.queue_free++;
#if defined(configNUM_CORES) && (configNUM_CORES > 1)
			spin_unlock(&ipc_msg_queue_lock);
			portRESTORE_INTERRUPTS(isr_status);
#else
			rtw_exit_critical(NULL, NULL);
#endif
			p_node = dequeue_ipc_msg_node(p_queue);
		}
	} while (g_ipc_msg_q_priv.b_queue_working);
	rtw_delete_task(&ipc_msgQ_wlan_task);
}

/* ---------------------------- Public Functions ---------------------------- */
/**
 * @brief  to initialize the message queue.
 * @param  task_func[in]: the pointer to the task function to operate this
 * 	queue.
 * @return none
 */
void inic_ipc_msg_q_init(void (*task_hdl)(inic_ipc_ex_msg_t *))
{
	int i = 0;

	rtw_memset(&g_ipc_msg_q_priv, 0, sizeof(struct ipc_msg_q_priv));
	rtw_memset(&g_inic_ipc_ex_msg, 0, sizeof(inic_ipc_ex_msg_t));
	rtw_memset(&g_inic_ipc_msg, 0, sizeof(IPC_MSG_STRUCT));

	/* initialize queue. */
	rtw_init_queue(&(g_ipc_msg_q_priv.msg_queue));

	/* assign the haddle function for the task */
	g_ipc_msg_q_priv.task_hdl = task_hdl;

	/* initialize the sema to wakeup the message queue task */
	rtw_init_sema(&g_ipc_msg_q_priv.msg_q_sema, 0);
	rtw_init_sema(&g_ipc_msg_q_priv.msg_send_sema, 0);
	rtw_up_sema(&g_ipc_msg_q_priv.msg_send_sema);

	for (i = 0; i < IPC_MSG_QUEUE_DEPTH; i++) {
		g_ipc_msg_q_priv.ipc_msg_pool[i].is_used = 0;
	}
	g_ipc_msg_q_priv.queue_free = IPC_MSG_QUEUE_DEPTH;

	/* Initialize the queue task */
	if (rtw_create_task(&ipc_msgQ_wlan_task, (const char *const)"inic_msg_q_task", 1024, (0 + CONFIG_INIC_IPC_MSG_Q_PRI), (void*)inic_ipc_msg_q_task, NULL) != 1) {
		DBG_8195A("Create inic_ipc_msg_q_task Err!!\n");
	}

	/* sign the queue is working */
	g_ipc_msg_q_priv.b_queue_working = 1;
}

/**
 * @brief  put the ipc message to queue.
 * @param  p_node[in]: the pointer for the ipc message that need to be
 * 	pushed into the queue.
 * @return status, always _SUCCESS.
 */
sint inic_ipc_msg_enqueue(inic_ipc_ex_msg_t *p_ipc_msg)
{
	struct ipc_msg_node *p_node = NULL;
	_queue *p_queue = &(g_ipc_msg_q_priv.msg_queue);
	sint ret = FAIL;
	int i = 0;

	/* allocate memory for message node */
	for (i = 0; i < IPC_MSG_QUEUE_DEPTH; i++) {
		if (g_ipc_msg_q_priv.ipc_msg_pool[i].is_used == 0) {
			p_node = &(g_ipc_msg_q_priv.ipc_msg_pool[i]);
			/* a node is used, the free node will decrease */
			g_ipc_msg_q_priv.queue_free--;
			break;
		}
	}

	if (p_node == NULL) {
		DBG_8195A("NO buffer for new nodes, waiting!\n\r");
		goto func_out;
	}

	/* To store the ipc message to queue's node. */
	p_node->ipc_msg.event_num = p_ipc_msg->event_num;
	p_node->ipc_msg.msg_addr = p_ipc_msg->msg_addr;
	p_node->ipc_msg.msg_len = p_ipc_msg->msg_len;
	p_node->is_used = 1;

	/* put the ipc message to the queue */
	ret = enqueue_ipc_msg_node(p_node, p_queue);

	/* the free number of nodes is smaller than the warning depth. */
	if (g_ipc_msg_q_priv.queue_free <= IPC_MSG_QUEUE_WARNING_DEPTH) {
		/* ask peer to wait */
		ret = FAIL;
	}

func_out:
	/* wakeup task */
	rtw_up_sema_from_isr(&g_ipc_msg_q_priv.msg_q_sema);

	return ret;
}

/**
 * @brief  to deinitialize the message queue.
 * @param  none.
 * @return none
 */
void inic_ipc_msg_q_deinit(void)
{
	/* sign the queue is stop */
	g_ipc_msg_q_priv.b_queue_working = 0;

	/* assign the haddle function to NULL */
	g_ipc_msg_q_priv.task_hdl = NULL;

	/* free sema to wakeup the message queue task */
	rtw_free_sema(&g_ipc_msg_q_priv.msg_q_sema);
	/* de initialize queue, todo */
}

/**
 * @brief  to get the status of queue, working or stop.
 * @param  none.
 * @return the status of queue, 1 means working, 0 means stop.
 */
u8 inic_ipc_msg_get_queue_status(void)
{
	return g_ipc_msg_q_priv.b_queue_working;
}

/**
 * @brief  to send the ipc message. It will wait when the last message is not
 * 	read.
 * @param  p_ipc_msg[inout]: the message to send.
 * @return none.
 */
void inic_ipc_ipc_send_msg(inic_ipc_ex_msg_t *p_ipc_msg)
{
	u32 cnt = 100000;
	/* Get the warning of queue's depth not enough in peer, delay send the
	 * the next message.
	 */
	if (p_ipc_msg->msg_len == IPC_WIFI_MSG_MEMORY_NOT_ENOUGH) {
		rtw_mdelay_os(5);
	}

	rtw_down_sema(&g_ipc_msg_q_priv.msg_send_sema);

	/* Wait for another port ack acknowledgement last message sending */
	while (g_inic_ipc_ex_msg.event_num != IPC_WIFI_MSG_READ_DONE) {
		DelayUs(2);
		DCache_Invalidate((u32)&g_inic_ipc_ex_msg, sizeof(inic_ipc_ex_msg_t));
		cnt--;
		if (cnt == 0) {
			DBG_8195A("inic ipc wait timeout\n");
			break;
		}
	}
	/* Send the new message after last one acknowledgement */
	g_inic_ipc_ex_msg.event_num = p_ipc_msg->event_num;
	g_inic_ipc_ex_msg.msg_addr = p_ipc_msg->msg_addr;
	g_inic_ipc_ex_msg.msg_len = p_ipc_msg->msg_len;
	DCache_Clean((u32)&g_inic_ipc_ex_msg, sizeof(inic_ipc_ex_msg_t));

#ifdef IPC_DIR_MSG_TX
	g_inic_ipc_msg.msg_type = IPC_USER_POINT;
	g_inic_ipc_msg.msg = (u32)&g_inic_ipc_ex_msg;
	g_inic_ipc_msg.msg_len = sizeof(inic_ipc_ex_msg_t);
	DCache_Clean((u32)&g_inic_ipc_msg, sizeof(IPC_MSG_64_STRUCT));
	ipc_send_message(IPC_DIR_MSG_TX, IPC_INT_CHAN_WIFI_TRX_TRAN, \
					 (PIPC_MSG_STRUCT)&g_inic_ipc_msg);
#else
	ipc_send_message(IPC_INT_CHAN_WIFI_TRX_TRAN, (PIPC_MSG_STRUCT)&g_inic_ipc_ex_msg);
#endif /* IPC_DIR_MSG_TX */

	rtw_up_sema(&g_ipc_msg_q_priv.msg_send_sema);
}


text:
/**
 * 是否登录
 */
window.isLogin = function(siteId){

    $.ajax({
        url:"/default.php?mod=user&a=async_get_one",
        data:{"site_id":siteId},
        dataType:"jsonp",
        jsonp:"jsonpcallback",
        success:function(data){
            var result = parseInt(data["result"]);
            if(result <= 0){
                window.showLoginBoxCallBack();
            }else{
                var user = eval(data["result"]);
                window.showIsLoginBoxCallBack(user);
            }
        }
    });
}


text:
package pl.itdonat.demo.wsfbd.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by Robert on 2017-03-11.
 */
@Service
public class UserService {

    private final UserRepository userRepository;
    private final UserDataConverter userDataConverter;

    @Autowired
    public UserService(UserRepository userRepository, UserDataConverter userDataConverter) {
        this.userRepository = userRepository;
        this.userDataConverter = userDataConverter;
    }

    UserData getUserData(User user){
        return userDataConverter.convertToData(user);
    }

    public Optional<UserData> getCurrentUserData(){
        return currentUserDetails()
            .map(userDetails -> userRepository.findOneByLogin(userDetails.getUsername()))
            .flatMap(user -> user)
            .map(this::getUserData);
    }

    public List<UserData> allUsersData(){
        return userRepository.findAll().stream()
            .map(this::getUserData)
            .collect(Collectors.toList());
    }

    public Optional<UserDetails> currentUserDetails(){
        Optional<UserDetails> details = Optional.empty();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication !=null && authentication.isAuthenticated()){
            Object principal = authentication.getPrincipal();
            if(principal instanceof UserDetails){
                details = Optional.of((UserDetails) principal);
            } else {
                throw new RuntimeException("Principal object mast be UserDetails");
            }
        }
        return details;
    }

    public SecurityExpressionRoot securityExpressionRoot(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
        SecurityExpressionRoot securityExpressionRoot = new SecurityExpressionRoot(authentication){};
        securityExpressionRoot.setTrustResolver(trustResolver);
        return securityExpressionRoot;
    }

    public Optional<String> currentUserLogin(){
        return currentUserDetails().map(UserDetails::getUsername);
    }

    public Optional<UserData> getUserDataByLogin(String name) {
        return userRepository.findOneByLogin(name)
                .map(this::getUserData);
    }
}


text:
package editor;

import gw.lang.parser.IExpression;
import gw.lang.parser.IFunctionSymbol;
import gw.lang.parser.IHasArguments;
import gw.lang.parser.IParsedElement;
import gw.lang.parser.expressions.IBeanMethodCallExpression;
import gw.lang.parser.expressions.IMethodCallExpression;
import gw.lang.reflect.FunctionType;
import gw.lang.reflect.IFunctionType;
import gw.lang.reflect.IType;
import java.awt.Point;
import javax.swing.text.JTextComponent;

/**
 */
public class ParseExceptionResolver
{
  public static IType resolvePossibleContextTypesFromEmptyMethodCalls( IExpression expression, JTextComponent editor )
  {
    IType[] paramTypes = null;
    if( expression instanceof IMethodCallExpression )
    {
      IMethodCallExpression mce = (IMethodCallExpression)expression;
      if( mce.getArgs() == null || mce.getArgs().length == 0 )
      {
        if( isEditorAtPossibleArgPosition( mce, editor ) )
        {
          IFunctionSymbol symbol = mce.getFunctionSymbol();
          if( symbol != null )
          {
            IFunctionType funType = (FunctionType)symbol.getType();
            if( funType != null && funType.getParameterTypes() != null && funType.getParameterTypes().length > 0 )
            {
              paramTypes = funType.getParameterTypes();
            }
          }
        }
      }
    }
    if( expression instanceof IBeanMethodCallExpression )
    {
      IBeanMethodCallExpression bmce = (IBeanMethodCallExpression)expression;
      if( bmce.getArgs() == null || bmce.getArgs().length == 0 )
      {
        if( isEditorAtPossibleArgPosition( bmce, editor ) )
        {
          IFunctionType funType = bmce.getFunctionType();
          if( funType != null && funType.getParameterTypes() != null && funType.getParameterTypes().length > 0 )
          {
            paramTypes = funType.getParameterTypes();
          }
        }
      }
    }
    return paramTypes != null && paramTypes.length > 0 ? paramTypes[0] : null;
  }

  public static boolean isEditorAtPossibleArgPosition( IParsedElement e, JTextComponent editor )
  {
    boolean returnVal = false;
    if( e instanceof IHasArguments )
    {
      Point argPosition = findMethodArgPoint( e, editor );
      if( argPosition != null )
      {
        int position = editor.getCaretPosition();
        if( position > argPosition.x && position <= argPosition.y )
        {
          returnVal = true;
        }
      }
    }
    return returnVal;
  }

  private static Point findMethodArgPoint( IParsedElement mce, JTextComponent editor )
  {
    int start = mce.getLocation().getOffset();
    int end = mce.getLocation().getExtent();
    try
    {
      while( !"(".equals( editor.getText( start, 1 ) ) && start < end )
      {
        start++;
      }
      while( !")".equals( editor.getText( end, 1 ) ) && end > start )
      {
        end--;
      }
      return new Point( start, end );
    }
    catch( Exception e )
    {
      //ignore
    }
    return null;
  }
}


text:
<?php

/** Zend_Form_Element_Select */
require_once 'Zend/Form/Element/Select.php';

/**
 * Multiselect form element
 *
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */
class Zend_Form_Element_Multiselect extends Zend_Form_Element_Select
{
    /**
     * 'multiple' attribute
     * @var string
     */
    public $multiple = 'multiple';

    /**
     * Use formSelect view helper by default
     * @var string
     */
    public $helper = 'formSelect';

    /**
     * Multiselect is an array of values by default
     * @var bool
     */
    protected $_isArray = true;
}