text:
#ifndef DALE_FORM_STRUCT
#define DALE_FORM_STRUCT

#include "../../Units/Units.h"

namespace dale
{
/*! Parse a struct definition form.
 *  @param units The units context.
 *  @param node The node containing the definition.
 *  @param name The name of the new struct type.
 */
bool FormStructParse(Units *units, Node *n, const char *name);
}

#endif

redpajama_set_name: RedPajamaGithub


text:
The Python components of Aurora are built using [Pants](https://pantsbuild.github.io).

Python Build Conventions
========================
The Python code is laid out according to the following conventions:

1. 1 `BUILD` per 3rd level directory. For a list of current top-level packages run:

        % find src/main/python -maxdepth 3 -mindepth 3 -type d |\
        while read dname; do echo $dname |\
            sed 's@src/main/python/\(.*\)/\(.*\)/\(.*\).*@\1.\2.\3@'; done

2.  Each `BUILD` file exports 1
    [`python_library`](https://pantsbuild.github.io/build_dictionary.html#bdict_python_library)
    that provides a
    [`setup_py`](https://pantsbuild.github.io/build_dictionary.html#setup_py)
    containing each
    [`python_binary`](https://pantsbuild.github.io/build_dictionary.html#python_binary)
    in the `BUILD` file, named the same as the directory it's in so that it can be referenced
    without a ':' character. The `sources` field in the `python_library` will almost always be
    `rglobs('*.py')`.

3.  Other BUILD files may only depend on this single public `python_library`
    target. Any other target is considered a private implementation detail and
    should be prefixed with an `_`.

4.  `python_binary` targets are always named the same as the exported console script.

5.  `python_binary` targets must have identical `dependencies` to the `python_library` exported
    by the package and must use `entry_point`.

    The means a PEX file generated by pants will contain exactly the same files that will be
    available on the `PYTHONPATH` in the case of `pip install` of the corresponding library
    target. This will help our migration off of Pants in the future.

Annotated example - apache.thermos.runner
-----------------------------------------
```
% find src/main/python/apache/thermos/runner
src/main/python/apache/thermos/runner
src/main/python/apache/thermos/runner/__init__.py
src/main/python/apache/thermos/runner/thermos_runner.py
src/main/python/apache/thermos/runner/BUILD
% cat src/main/python/apache/thermos/runner/BUILD
# License boilerplate omitted
import os

# Private target so that a setup_py can exist without a circular dependency. Only targets within
# this file should depend on this.
python_library(
  name = '_runner',
  # The target covers every python file under this directory and subdirectories.
  sources = rglobs('*.py'),
  dependencies = [
    '3rdparty/python:twitter.common.app',
    '3rdparty/python:twitter.common.log',
    # Source dependencies are always referenced without a ':'.
    'src/main/python/apache/thermos/common',
    'src/main/python/apache/thermos/config',
    'src/main/python/apache/thermos/core',
  ],
)

# Binary target for thermos_runner.pex. Nothing should depend on this - it's only used as an
# argument to ./pants binary.
python_binary(
  name = 'thermos_runner',
  # Use entry_point, not source so the files used here are the same ones tests see.
  entry_point = 'apache.thermos.bin.thermos_runner',
  dependencies = [
    # Notice that we depend only on the single private target from this BUILD file here.
    ':_runner',
  ],
)

# The public library that everyone importing the runner symbols uses.
# The test targets and any other dependent source code should depend on this.
python_library(
  name = 'runner',
  dependencies = [
    # Again, notice that we depend only on the single private target from this BUILD file here.
    ':_runner',
  ],
  # We always provide a setup_py. This will cause any dependee libraries to automatically
  # reference this library in their requirements.txt rather than copy the source files into their
  # sdist.
  provides = setup_py(
    # Conventionally named and versioned.
    name = 'apache.thermos.runner',
    version = open(os.path.join(get_buildroot(), '.auroraversion')).read().strip().upper(),
  ).with_binaries({
    # Every binary in this file should also be repeated here.
    # Always use the dict-form of .with_binaries so that commands with dashes in their names are
    # supported.
    # The console script name is always the same as the PEX with .pex stripped.
    'thermos_runner': ':thermos_runner',
  }),
)
```


text:
"""
Cohorte Composer criteria components

:author: Thomas Calmant
:license: Apache Software License 2.0
"""

# Documentation strings format
__docformat__ = "restructuredtext en"

# ------------------------------------------------------------------------------


text:
package mods.flammpfeil.slashbladezephyr;

import cpw.mods.fml.common.SidedProxy;

public class InitProxy {
	@SidedProxy(clientSide = "mods.flammpfeil.slashbladezephyr.InitProxyClient", serverSide = "mods.flammpfeil.slashbladezephyr.InitProxy")
	public static InitProxy proxy;

	public void initializeItemRenderer() {}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;

namespace QuantConnect.Algorithm.CSharp
{
    /// <summary>
    /// This regression algorithm tests Out of The Money (OTM) index option expiry for calls.
    /// We expect 2 orders from the algorithm, which are:
    ///
    ///   * Initial entry, buy SPX Call Option (expiring OTM)
    ///     - contract expires worthless, not exercised, so never opened a position in the underlying
    ///
    ///   * Liquidation of worthless SPX call option (expiring OTM)
    ///
    /// Additionally, we test delistings for index options and assert that our
    /// portfolio holdings reflect the orders the algorithm has submitted.
    /// </summary>
    /// <remarks>
    /// Total Trades in regression algorithm should be 1, but expiration is counted as a trade.
    /// See related issue: https://github.com/QuantConnect/Lean/issues/4854
    /// </remarks>
    public class IndexOptionCallOTMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
    {
        private Symbol _spx;
        private Symbol _spxOption;
        private Symbol _expectedContract;

        public override void Initialize()
        {
            SetStartDate(2021, 1, 4);
            SetEndDate(2021, 1, 31);

            _spx = AddIndex("SPX", Resolution.Minute).Symbol;

            // Select a index option call expiring OTM, and adds it to the algorithm.
            _spxOption = AddIndexOptionContract(OptionChainProvider.GetOptionContractList(_spx, Time)
                .Where(x => x.ID.StrikePrice >= 4250m && x.ID.OptionRight == OptionRight.Call && x.ID.Date.Year == 2021 && x.ID.Date.Month == 1)
                .OrderBy(x => x.ID.StrikePrice)
                .Take(1)
                .Single(), Resolution.Minute).Symbol;

            _expectedContract = QuantConnect.Symbol.CreateOption(_spx, Market.USA, OptionStyle.European, OptionRight.Call, 4250m, new DateTime(2021, 1, 15));
            if (_spxOption != _expectedContract)
            {
                throw new Exception($"Contract {_expectedContract} was not found in the chain");
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_spx, 1), () =>
            {
                MarketOrder(_spxOption, 1);
            });
        }

        public override void OnData(Slice data)
        {
            // Assert delistings, so that we can make sure that we receive the delisting warnings at
            // the expected time. These assertions detect bug #4872
            foreach (var delisting in data.Delistings.Values)
            {
                if (delisting.Type == DelistingType.Warning)
                {
                    if (delisting.Time != new DateTime(2021, 1, 15))
                    {
                        throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
                    }
                }
                if (delisting.Type == DelistingType.Delisted)
                {
                    if (delisting.Time != new DateTime(2021, 1, 16))
                    {
                        throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
                    }
                }
            }
        }

        public override void OnOrderEvent(OrderEvent orderEvent)
        {
            if (orderEvent.Status != OrderStatus.Filled)
            {
                // There's lots of noise with OnOrderEvent, but we're only interested in fills.
                return;
            }

            if (!Securities.ContainsKey(orderEvent.Symbol))
            {
                throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
            }

            var security = Securities[orderEvent.Symbol];
            if (security.Symbol == _spx)
            {
                throw new Exception("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM");
            }
            if (security.Symbol == _expectedContract)
            {
                AssertIndexOptionContractOrder(orderEvent, security);
            }
            else
            {
                throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
            }

            Log($"{orderEvent}");
        }

        private void AssertIndexOptionContractOrder(OrderEvent orderEvent, Security option)
        {
            if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 1)
            {
                throw new Exception($"No holdings were created for option contract {option.Symbol}");
            }
            if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != 0)
            {
                throw new Exception("Holdings were found after a filled option exercise");
            }
            if (orderEvent.Direction == OrderDirection.Sell && !orderEvent.Message.Contains("OTM"))
            {
                throw new Exception("Contract did not expire OTM");
            }
            if (orderEvent.Message.Contains("Exercise"))
            {
                throw new Exception("Exercised option, even though it expires OTM");
            }
        }

        /// <summary>
        /// Ran at the end of the algorithm to ensure the algorithm has no holdings
        /// </summary>
        /// <exception cref="Exception">The algorithm has holdings</exception>
        public override void OnEndOfAlgorithm()
        {
            if (Portfolio.Invested)
            {
                throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
            }
        }

        /// <summary>
        /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
        /// </summary>
        public bool CanRunLocally { get; } = true;

        /// <summary>
        /// This is used by the regression test system to indicate which languages this algorithm is written in.
        /// </summary>
        public Language[] Languages { get; } = { Language.CSharp, Language.Python };

        /// <summary>
        /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
        /// </summary>
        public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
        {
            {"Total Trades", "2"},
            {"Average Win", "0%"},
            {"Average Loss", "-0.01%"},
            {"Compounding Annual Return", "-0.142%"},
            {"Drawdown", "0.000%"},
            {"Expectancy", "-1"},
            {"Net Profit", "-0.010%"},
            {"Sharpe Ratio", "-5.154"},
            {"Probabilistic Sharpe Ratio", "0.016%"},
            {"Loss Rate", "100%"},
            {"Win Rate", "0%"},
            {"Profit-Loss Ratio", "0"},
            {"Alpha", "-0.001"},
            {"Beta", "0"},
            {"Annual Standard Deviation", "0"},
            {"Annual Variance", "0"},
            {"Information Ratio", "-0.374"},
            {"Tracking Error", "0.155"},
            {"Treynor Ratio", "-4.059"},
            {"Total Fees", "$0.00"},
            {"Estimated Strategy Capacity", "$22000.00"},
            {"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
            {"Fitness Score", "0"},
            {"Kelly Criterion Estimate", "0"},
            {"Kelly Criterion Probability Value", "0"},
            {"Sortino Ratio", "-51177.748"},
            {"Return Over Maximum Drawdown", "-14.362"},
            {"Portfolio Turnover", "0"},
            {"Total Insights Generated", "0"},
            {"Total Insights Closed", "0"},
            {"Total Insights Analysis Completed", "0"},
            {"Long Insight Count", "0"},
            {"Short Insight Count", "0"},
            {"Long/Short Ratio", "100%"},
            {"Estimated Monthly Alpha Value", "$0"},
            {"Total Accumulated Estimated Alpha Value", "$0"},
            {"Mean Population Estimated Insight Value", "$0"},
            {"Mean Population Direction", "0%"},
            {"Mean Population Magnitude", "0%"},
            {"Rolling Averaged Population Direction", "0%"},
            {"Rolling Averaged Population Magnitude", "0%"},
            {"OrderListHash", "177477b78d9264384a09f1607e8c7d11"}
        };
    }
}


text:
package org.oep.core.processmgt.model.impl;

/**
 * The extended model implementation for the DocFile2ProcessOrder service. Represents a row in the "oep_processmgt_docfile2processorder" database table, with each column mapped to a property of this class.
 *
 * <p>
 * Helper methods and all application logic should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link org.oep.core.processmgt.model.DocFile2ProcessOrder} interface.
 * </p>
 *
 * @author trungdk
 */
public class DocFile2ProcessOrderImpl extends DocFile2ProcessOrderBaseImpl {
	/*
	 * NOTE FOR DEVELOPERS:
	 *
	 * Never reference this class directly. All methods that expect a doc file2 process order model instance should use the {@link org.oep.core.processmgt.model.DocFile2ProcessOrder} interface instead.
	 */
	public DocFile2ProcessOrderImpl() {
	}
}


text:
import { TestBed, inject } from '@angular/core/testing';
import { HttpModule } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

import { IcLoginComponent } from './icLogin.component';
import { IcLoginService } from './shared/icLogin.service';
import { IC_LOGIN } from './shared/icLogin.model';

describe('a icLogin component', () => {
	let component: IcLoginComponent;

	// register all needed dependencies
	beforeEach(() => {
		TestBed.configureTestingModule({
			imports: [HttpModule],
			providers: [
				{ provide: IcLoginService, useClass: MockIcLoginService },
				IcLoginComponent
			]
		});
	});

	// instantiation through framework injection
	beforeEach(inject([IcLoginComponent], (IcLoginComponent) => {
		component = IcLoginComponent;
	}));

	it('should have an instance', () => {
		expect(component).toBeDefined();
	});

	it('should show authentication on login button click', () => {
		spyOn(component.authService, 'login').and.callThrough();

		component.onLoginClick();

		expect(component.authService.login).toHaveBeenCalled();
	});
});

// Mock of the original icLogin service
class MockIcLoginService extends IcLoginService {
	public login() {
		return null;
	}
}


text:
package gnu.javax.naming.giop;

import java.util.NoSuchElementException;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;

import org.omg.CosNaming.Binding;
import org.omg.CosNaming.BindingIterator;
import org.omg.CosNaming.BindingIteratorHolder;
import org.omg.CosNaming.BindingListHolder;

/**
 * Iterates over name class pairs, obtaining values first from the binding list
 * and then from the binding iterator.
 *
 * @author Audrius Meskauskas
 */
public abstract class GiopNamingEnumeration implements NamingEnumeration
{
  /**
   * The array of bindings, returned at once.
   */
  Binding[] list;

  /**
   * The binding iterator to obtain the subsequent bindings. May be null,
   * if all values are stored in the list.
   */
  BindingIterator iterator;

  /**
   * The batch size.
   */
  int batch;

  /**
   * The position of the element in the binding list, that must be returned
   * during the subsequent call of the next(). If this field is grater or equal
   * to the lenght of the list, the subsequent values must be requested from the
   * iterator.
   */
  int p;

  GiopNamingEnumeration(BindingListHolder bh, BindingIteratorHolder bih, int batchSize)
  {
    list = bh.value;
    iterator = bih.value;
    batch = batchSize;
  }

  /**
   * Convert from the CORBA binding into that this enumeration should return.
   *
   * @param binding
   *          the binding to convert
   * @return the value, that must be returned by the {@link #next()}.
   */
  public abstract Object convert(Binding binding);

  public void close() throws NamingException
  {
    if (iterator != null)
      {
        iterator.destroy();
        iterator = null;
      }
  }

  /**
   * Checks if there are more elements to return.
   *
   * @throws NamingException
   *           never
   */
  public boolean hasMore() throws NamingException
  {
    return hasMoreElements();
  }

  /**
   * Returns the next element.
   *
   * @throws NamingException
   *           never
   */
  public Object next() throws NamingException
  {
    return nextElement();
  }

  /**
   * Checks if there are more elements to return.
   */
  public boolean hasMoreElements()
  {
    if (p < 0)
      return false;
    else if (p < list.length)
      return true;
    else
      return getMore();
  }

  /**
   * Returns the next element.
   */
  public Object nextElement()
  {
    if (p < 0)
      throw new NoSuchElementException();
    else if (p < list.length)
      return convert(list[p++]);
    else if (getMore())
      // getMore updates p
      return convert(list[p++]);
    else
      throw new NoSuchElementException();
  }

  /**
   * Tries to obtain more elements, return true on success. Updates the fields
   * accordingly.
   */
  boolean getMore()
  {
    if (iterator != null)
      {
        BindingListHolder holder = new BindingListHolder();
        boolean rt = iterator.next_n(batch, holder);
        if (rt)
          {
            // The new pack of the bindings arrived.
            p = 0;
            list = holder.value;
            return true;
          }
        else
          {
            iterator.destroy();
            iterator = null;
            p = -1;
            return false;
          }
      }
    else
      return false;
  }
}


text:
{% for link in site.data.navigation.footer-links %}

{{ link.title }}
{% endfor %}


text:
import unittest
from bz.tasks import *

class TestTask(unittest.TestCase):
    def test_task(self):
        def fn():
            return "success"
        self.assertEqual("success", task(fn).run())

    def test_failing_task(self):
        def fn():
            fail("failure")
        result = task(fn).run()
        self.assertTrue(result.is_failure())
        self.assertEqual("failure", result.message)

    def test_then_all_pass(self):
        def fn1():
            return "foo"

        def fn2():
            return "bar"
        composite_task = task(fn1).then(task(fn2))
        result = composite_task.run()
        self.assertEqual("bar", result)

    def test_then_first_fail(self):
        def fn1():
            fail("first task failed")

        def fn2():
            return "bar"
        composite_task = task(fn1).then(task(fn2))
        result = composite_task.run()
        self.assertTrue(result.is_failure)
        self.assertEqual("first task failed", result.message)

    def test_then_second_fail(self):
        def fn1():
            return "foo"

        def fn2():
            fail("second task failed")
        composite_task = task(fn1).then(task(fn2))
        result = composite_task.run()
        self.assertTrue(result.is_failure)
        self.assertEqual("second task failed", result.message)

    def test_then_both_fail(self):
        def fn1():
            fail("first task failed")

        def fn2():
            fail("second task failed")
        composite_task = task(fn1).then(task(fn2))
        result = composite_task.run()
        self.assertTrue(result.is_failure)
        self.assertEqual("first task failed", result.message)

    def test_result_passing(self):
        def fn1():
            return "foo"

        def fn2(*args):
            return str(args[0]) + "bar"
        composite_task = task(fn1).then(task(fn2))
        result = composite_task.run()
        self.assertEqual("foobar", result)

    def test_or_else_both_pass(self):
        def fn1():
            return "foo"

        def fn2():
            return "bar"
        composite_task = task(fn1).or_else(task(fn2))
        result = composite_task.run()
        self.assertEqual("foo", result)

    def test_or_else_first_fail(self):
        def fn1():
            fail("oops")

        def fn2():
            return "bar"
        composite_task = task(fn1).or_else(task(fn2))
        result = composite_task.run()
        self.assertEqual("bar", result)

    def test_or_else_second_fail(self):
        def fn1():
            return "foo"

        def fn2():
            fail("second failed")
        composite_task = task(fn1).or_else(task(fn2))
        result = composite_task.run()
        self.assertEqual("foo", result)

    def test_or_else_both_fail(self):
        def fn1():
            fail("oops")

        def fn2():
            fail("second failed")
        composite_task = task(fn1).or_else(task(fn2))
        result = composite_task.run()
        self.assertTrue(result.is_failure)
        self.assertEqual("second failed", result.message)

    def test_gather(self):
        tasks_ = []

        def fni(i):
            def fn():
                return str(i)
            return fn
        for index in range(0, 10):
            # the ith function returns str(i)
            tasks_.append(task(fni(index)))
        composite_task = gather_tasks(*tasks_)
        import string
        result = string.join(composite_task.run(), '')
        self.assertEqual("0123456789", result)

    def test_gather_failure(self):
        tasks_ = [always(), never("failure")]
        composite_task = gather_tasks(*tasks_)
        result = composite_task.run()
        self.assertTrue(result.is_failure())
        self.assertEqual("failure", result.message)

    def test_then_never(self):
        def fn():
            return "foo"
        composite_task = task(fn).then(never("fail!"))
        result = composite_task.run()
        self.assertTrue(result.is_failure())
        self.assertEqual("fail!", result.message)

    def test_result_passing_by_keyword(self):
        def fn1():
            return {"a": 4, "b": 12}

        def fn2(a, b):
            return a + b
        composite_task = task(fn1).then(task(fn2))
        result = composite_task.run()
        self.assertEqual(16, result)

    def test_always(self):
        self.assertTrue(always().run())

    def test_never(self):
        result = never("failed").run()
        self.assertTrue(result.is_failure())
        self.assertEqual("failed", result.message)

    def test_map(self):
        def fn():
            return "foo"
        result = task(fn).map(lambda r: r*2).run()
        self.assertEqual("foofoo", result)

    def test_map_failures(self):
        def fn():
            return False
        result = task(fn).map(lambda r: str(r), map_failure=True).run()
        self.assertTrue(result.is_failure())
        self.assertEqual("False", result.message)

if __name__ == '__main__':
    unittest.main()


text:
package com.youcan.test.model;

import java.sql.ResultSet;
import java.util.ArrayList;

import com.youcan.core.db.Db;
import com.youcan.test.bean.TestBean;

public class TestModel {
	public TestModel() {
		//do nothing
	}

	/*
	 * 示例程序,功能做了简化
	 */
	public ArrayList<TestBean> getTestList() {
		Db db = null;
		ArrayList<TestBean> testList = null;
		try {
			db = new Db();
			ResultSet rs = db.executeQuery("SELECT uid,name FROM user");
			testList = new ArrayList<TestBean>(db.getNumRows());
			while(rs.next()) {
				TestBean test = null;
				test = new TestBean();
				test.setId(rs.getLong(1));
				test.setName(rs.getString(2));
				testList.add(test);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			Db.close(db);
		}
		return testList;
	}
}


text:
namespace {

using spvtools::ir::Module;
using spvtest::GetIdBound;
using ::testing::Eq;

TEST(ModuleTest, SetIdBound) {
  Module m;
  // It's initialized to 0.
  EXPECT_EQ(0u, GetIdBound(m));

  m.SetIdBound(19);
  EXPECT_EQ(19u, GetIdBound(m));

  m.SetIdBound(102);
  EXPECT_EQ(102u, GetIdBound(m));
}

// Returns a module formed by assembling the given text,
// then loading the result.
inline std::unique_ptr<Module> BuildModule(std::string text) {
  return spvtools::BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text);
}

TEST(ModuleTest, ComputeIdBound) {
  // Emtpy module case.
  EXPECT_EQ(1u, BuildModule("")->ComputeIdBound());
  // Sensitive to result id
  EXPECT_EQ(2u, BuildModule("%void = OpTypeVoid")->ComputeIdBound());
  // Sensitive to type id
  EXPECT_EQ(1000u, BuildModule("%a = OpTypeArray !999 3")->ComputeIdBound());
  // Sensitive to a regular Id parameter
  EXPECT_EQ(2000u, BuildModule("OpDecorate !1999 0")->ComputeIdBound());
  // Sensitive to a scope Id parameter.
  EXPECT_EQ(3000u,
            BuildModule("%f = OpFunction %void None %fntype %a = OpLabel "
                        "OpMemoryBarrier !2999 %b\n")
                ->ComputeIdBound());
  // Sensitive to a semantics Id parameter
  EXPECT_EQ(4000u,
            BuildModule("%f = OpFunction %void None %fntype %a = OpLabel "
                        "OpMemoryBarrier %b !3999\n")
                ->ComputeIdBound());
}

}  // anonymous namespace


text:
"""Creates resource tag(s)"""
from baseCmd import *
from baseResponse import *

class createTagsCmd (baseCmd):
    typeInfo = {}

    def __init__(self):
        self.isAsync = "true"
        """list of resources to create the tags for"""
        """Required"""
        self.resourceids = []
        self.typeInfo['resourceids'] = 'list'
        """type of the resource"""
        """Required"""
        self.resourcetype = None
        self.typeInfo['resourcetype'] = 'string'
        """Map of tags (key/value pairs)"""
        """Required"""
        self.tags = []
        self.typeInfo['tags'] = 'map'
        """identifies client specific tag. When the value is not null, the tag can't be used by cloudStack code internally"""
        self.customer = None
        self.typeInfo['customer'] = 'string'
        self.required = ["resourceids", "resourcetype", "tags", ]

class createTagsResponse (baseResponse):
    typeInfo = {}

    def __init__(self):
        """any text associated with the success or failure"""
        self.displaytext = None
        self.typeInfo['displaytext'] = 'string'
        """true if operation is executed successfully"""
        self.success = None
        self.typeInfo['success'] = 'boolean'


text:
package com.bit.allan.mazahs;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button buttonAudio;
    private Button buttonSocket;
    private Button buttonAbout;
    private Button buttonExit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonAudio=(Button)findViewById(R.id.buttonPhone);
        buttonSocket=(Button)findViewById(R.id.buttonSocket);
        buttonAbout=(Button)findViewById(R.id.buttonAboutUs);
        buttonExit=(Button)findViewById(R.id.buttonExit);

        buttonAudio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AudioRecognizerActivity.class);
                startActivity(intent);
            }
        });

        buttonSocket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SocketActivity.class);
                startActivity(intent);
            }
        });

        buttonExit.setOnClickListener(new View.OnClickListener(){
            @Override
        public void onClick(View v){
                finish();
            }
        });

        buttonAbout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,AboutActivity.class);
                startActivity(intent);
            }
        });
    }

}


text:
package debug

import (
	"testing"

	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/debug/types"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph"
	"github.com/GoogleContainerTools/skaffold/testutil"
)

func TestFindArtifact(t *testing.T) {
	buildArtifacts := []graph.Artifact{
		{ImageName: "image1", Tag: "tag1"},
	}
	tests := []struct {
		description string
		source      string
		returnNil   bool
	}{
		{
			description: "found",
			source:      "image1",
			returnNil:   false,
		},
		{
			description: "not found",
			source:      "image2",
			returnNil:   true,
		},
	}
	for _, test := range tests {
		testutil.Run(t, test.description, func(t *testutil.T) {
			result := findArtifact(test.source, buildArtifacts)

			t.CheckDeepEqual(test.returnNil, result == nil)
		})
	}
}

func TestEnvAsMap(t *testing.T) {
	tests := []struct {
		description string
		source      []string
		result      map[string]string
	}{
		{"nil", nil, map[string]string{}},
		{"empty", []string{}, map[string]string{}},
		{"single", []string{"a=b"}, map[string]string{"a": "b"}},
		{"multiple", []string{"a=b", "c=d"}, map[string]string{"c": "d", "a": "b"}},
		{"embedded equals", []string{"a=b=c", "c=d"}, map[string]string{"c": "d", "a": "b=c"}},
	}
	for _, test := range tests {
		testutil.Run(t, test.description, func(t *testutil.T) {
			result := envAsMap(test.source)

			t.CheckDeepEqual(test.result, result)
		})
	}
}

type testAdapter struct {
	executable *types.ExecutableContainer
}

func (t *testAdapter) GetContainer() *types.ExecutableContainer {
	return t.executable
}

func (t *testAdapter) Apply() {}


text:
'use strict';

/**
 * @author Guille Paz <guille87paz@gmail.com>
 */

var url = 'http://www.gesturekit.com/dashboard/sdk/sendanalytics/';

/**
 * Creates a new instance of Analytics.
 * @constructor
 * @returns {analytics} Returns a new instance of Analytics.
 */
function Analytics() {
    this.init();
}

/**
 * Initialize a new instance of Analytics.
 * @memberof! Analytics.prototype
 * @function
 * @returns {analytics} Returns a new instance of Analytics.
 */
Analytics.prototype.init = function () {
    var that = this;

    this.collection = {};

    this.data = {
        'json': {
            'device_id': window.navigator.userAgent,
            'platform_id': '8',
            'gid': gesturekit._options.gid,
            'reports': []
        },
        'gid': gesturekit._options.gid,
        'version': 1
    };

    gesturekit.on('recognize', function (gesture) {
        that.collection[gesture.name] = that.collection[gesture.name] || [];
        that.collection[gesture.name].push(gesture);
        that.sendGestures();
        that.collection.length = 0;
    });

    return this;
};

/**
 *
 * @memberof! Analytics.prototype
 * @function
 * @returns {analytics} Returns a new instance of Analytics.
 */
Analytics.prototype.sendGestures = function () {
    var that = this,
        gestures = [],
        key,
        xhr = new XMLHttpRequest(),
        status,
        queryString = [],
        gesture;

    for (key in this.collection) {
        gesture = this.collection[key];
        gestures.push({
            'gesture_id': key,
            'score': (gesture.length > 0) ? gesture[0].score : 0,
            'count': gesture.length
        });
    }

    var data = {
        'json': {
            'device_id': '',
            'platform_id': 'pc',
            'gid': gesturekit._options.gid,
            'reports': []
        },
        'gid': gesturekit._options.gid,
        'version': 1
    };

    data.json.reports.push({
        'gestures': gestures,
        'date': new window.Date().getTime() / 1000 | 0
    });

    data.json = JSON.stringify(data.json);

    for (key in data) {
        queryString.push(key + '=' + data[key]);
    }

    queryString = queryString.join('&');

    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send(queryString);

    return this;
};

// Expose Analytics
module.exports = Analytics;


text:
module IncomeTax
  module Countries
    class Switzerland
      class Uri < Canton
        register "Uri", "UR"
        lazy { @tax_years = Marshal.load(File.open("#{__dir__}/data/uri.dat")) }
        municipal_multiplier "99%"
      end
    end
  end
end


text:
package io.apigee.lembos.mapreduce;

import io.apigee.lembos.utils.ConversionUtils;
import io.apigee.lembos.utils.TestUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.WritableComparable;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

/**
 * Unit tests for {@link LembosGroupComparator}.
 */
public class LembosGroupComparatorTest {

    /**
     * Tests the proper error is thrown when the group comparator configuration is missing.  (Should never happen)
     *
     * @throws Exception if anything goes wrong.
     */
    @Test
    public void testMissingConfiguration() throws Exception {
        try {
            new LembosGroupComparator().compare(null, null);

            fail("The line above should had failed");
        } catch (Exception e) {
            assertEquals("Hadoop configuration cannot be null", e.getMessage());
        }
    }

    /**
     * Tests the proper error is thrown when the specified module doesn't expose a 'group' property.
     *
     * @throws Exception if anything goes wrong.
     */
    @Test
    public void testMissingGroupFunction() throws Exception {
        try {
            runGroupComparator("LembosGroupComparatorTest-testMissingGroupFunction", 1, 3);

            fail("The line above should had failed");
        } catch (Exception e) {
            assertEquals("MapReduce function 'group' is not defined", e.getMessage());
        }
    }

    /**
     * Tests the proper error is thrown when the group comparator returns null;
     *
     * @throws Exception if anything goes wrong.
     */
    @Test
    public void testReturningNull() throws Exception {
        try {
            runGroupComparator("LembosGroupComparatorTest-testReturningNull", 1, 3);

            fail("The line above should had failed");
        } catch (Exception e) {
            assertEquals("MapReduce function 'group' cannot return null/undefined", e.getMessage());
        }
    }

    /**
     * Tests the proper error is thrown when the group comparator returns undefined;
     *
     * @throws Exception if anything goes wrong.
     */
    @Test
    public void testReturningUndefined() throws Exception {
        try {
            runGroupComparator("LembosGroupComparatorTest-testReturningUndefined", 1, 3);

            fail("The line above should had failed");
        } catch (Exception e) {
            assertEquals("MapReduce function 'group' cannot return null/undefined", e.getMessage());
        }
    }

    /**
     * Tests the proper error is thrown when the group comparator returns the wrong type;
     *
     * @throws Exception if anything goes wrong.
     */
    @Test
    public void testReturningWrongType() throws Exception {
        try {
            runGroupComparator("LembosGroupComparatorTest-testReturningWrongType", 1, 3);

            fail("The line above should had failed");
        } catch (Exception e) {
            assertEquals("MapReduce function 'group' must return an integer", e.getMessage());
        }
    }

    /**
     * Tests that the group comparator works as expected.
     *
     * @throws Exception if anything goes wrong.
     */
    @Test
    public void testGroupComparator() throws Exception {
        assertEquals(-1, runGroupComparator("LembosGroupComparatorTest-testGroupComparator", 1, 3));
    }

    /**
     * Runs the group comparator.
     *
     * @param moduleName the module name
     * @param key1 the key
     * @param key2 the value
     *
     * @return the partition
     *
     * @throws Exception if anything goes wrong
     */
    private int runGroupComparator(final String moduleName, final Object key1, final Object key2)
            throws Exception {
        final Configuration conf = new Configuration();
        final LembosGroupComparator groupComparator = new LembosGroupComparator();

        conf.set(LembosConstants.MR_MODULE_NAME, moduleName);
        conf.set(LembosConstants.MR_MODULE_PATH, TestUtils.getModulePath(moduleName));

        groupComparator.setConf(conf);

        final WritableComparable<?> writable1 = ConversionUtils.jsToWritableComparable(key1, null);
        final WritableComparable<?> writable2 = ConversionUtils.jsToWritableComparable(key2, null);

        try {
            return groupComparator.compare(writable1, writable2);
        } finally {
            groupComparator.close();
        }
    }

}


text:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { LoginService } from 'app/service/login.service';
import{ UserService} from'app/service/user.service';
import {User} from'app/models/user.model';
@Component({
  selector: 'login',
  templateUrl: './login.component.html'
})
export class LoginComponent {
  user:User;
  users:User[];

  constructor(private loginService: LoginService,private router:Router,private userService:UserService)/*,private router:Router,private userService:UserService)*/ {
   this.userService.getUsers().subscribe(
     users =>{
       this.users = users;
       console.log(this.users);
     },
     error => console.error(error)
   )
   }

  logIn(event: any, user: string, pass: string) {

    event.preventDefault();

    this.loginService.logIn(user, pass).subscribe(
      u => {console.log(u),
        this.router.navigate(['']);
      },
      error => alert('Invalid user or password')
    );
  }

  logOut() {
    this.loginService.logOut().subscribe(
      response => { },
      error => console.log('Error when trying to log out: ' + error)
    );
  }

}


text:
package org.trade.core.model.lifecycle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.statefulj.fsm.FSM;
import org.statefulj.fsm.TooBusyException;
import org.statefulj.fsm.model.State;
import org.trade.core.auditing.AuditingServiceFactory;
import org.trade.core.auditing.events.InstanceStateChangeEvent;
import org.trade.core.model.data.instance.DataElementInstance;
import org.trade.core.model.lifecycle.actions.DataElementInstanceLogAction;
import org.trade.core.utils.events.InstanceEvents;
import org.trade.core.utils.states.InstanceStates;

/**
 * This class implements the lifecycle of a {@link DataElementInstance} using a finite state machine in order to reflect the
 * currents state of the object through its {@link DataElementInstance#state} attribute. The lifecycle can be managed by
 * triggering corresponding events which result in state changes of the managed object, if the underlying
 * state transition is allowed or lead to a corresponding {@link LifeCycleException}, if the transition is not
 * allowed.
 * <p>
 * Created by hahnml on 07.04.2017.
 */
public class DataElementInstanceLifeCycle {

    Logger logger = LoggerFactory.getLogger("org.trade.core.model.lifecycle.DataElementInstanceLifeCycle");

    private FSM<DataElementInstance> fsm = null;

    public DataElementInstanceLifeCycle(DataElementInstance dataElementInstance) {
        this(dataElementInstance, true);
    }

    public DataElementInstanceLifeCycle(DataElementInstance dataElementInstance, boolean initialize) {
        buildFSM();

        if (initialize) {
            init(dataElementInstance);
        }
    }

    private void buildFSM() {
        FSM.FSMBuilder<DataElementInstance> fsmBuilder = FSM.FSMBuilder.newBuilder(DataElementInstance.class);

        fsmBuilder.
                buildState(InstanceStates.CREATED.name(), true)
                .addTransition(InstanceEvents.create.name(), InstanceStates.CREATED.name())
                .addTransition(InstanceEvents.initialize.name(), InstanceStates.INITIALIZED.name(), new DataElementInstanceLogAction(InstanceStates.CREATED.name()))
                .addTransition(InstanceEvents.delete.name(), InstanceStates.DELETED.name(), new DataElementInstanceLogAction(InstanceStates.CREATED.name()))
                .done()
                .buildState(InstanceStates.INITIALIZED.name())
                .addTransition(InstanceEvents.create.name(), InstanceStates.CREATED.name(), new DataElementInstanceLogAction(InstanceStates.INITIALIZED.name()))
                .addTransition(InstanceEvents.archive.name(), InstanceStates.ARCHIVED.name(), new DataElementInstanceLogAction(InstanceStates.INITIALIZED.name()))
                .addTransition(InstanceEvents.delete.name(), InstanceStates.DELETED.name(), new DataElementInstanceLogAction(InstanceStates.INITIALIZED.name()))
                .done()
                .buildState(InstanceStates.ARCHIVED.name())
                .addTransition(InstanceEvents.unarchive.name(), InstanceStates.INITIALIZED.name(), new DataElementInstanceLogAction(InstanceStates.ARCHIVED.name()))
                .addTransition(InstanceEvents.delete.name(), InstanceStates.DELETED.name(), new DataElementInstanceLogAction(InstanceStates.ARCHIVED.name()))
                .done()
                .buildState(InstanceStates.DELETED.name())
                .setEndState(true)
                .done();

        this.fsm = fsmBuilder.build();
    }

    private void init(DataElementInstance dataElementInstance) {
        if (dataElementInstance.getState() == null) {
            try {
                this.fsm.onEvent(dataElementInstance, InstanceEvents.create.name());

                Logger resourceLogger = LoggerFactory.getLogger(dataElementInstance.getClass().getCanonicalName());

                // Log the creation of the resource and trigger a corresponding event
                resourceLogger.info("State of data element instance ({}) changed from '{}' to '{}' on event '{}'.", dataElementInstance
                        .getIdentifier(), null, dataElementInstance.getState(), InstanceEvents.create.name());

                AuditingServiceFactory.createAuditingService().fireEvent(new InstanceStateChangeEvent(dataElementInstance.getIdentifier(),
                        DataElementInstance.class, dataElementInstance, null, dataElementInstance.getState(), InstanceEvents.create
                        .name()));
            } catch (TooBusyException e) {
                e.printStackTrace();
            }
        }
    }

    public InstanceStates triggerEvent(DataElementInstance obj, InstanceEvents event) throws TooBusyException {
        State state = this.fsm.onEvent(obj, event.name());

        return InstanceStates.valueOf(state.getName());
    }
}


text:
<?php
class Pair {
    protected $v1;    // T1
    protected $v2;    // T2
    private function __init() { // default class members
    }
    public static function __staticinit() { // static class members
    }
    public static function constructor__4b76b80 ($v1, $v2) // [T1 v1, T2 v2]
    {
        $me = new self();
        $me->__init();
        $me->v1 = $v1;
        $me->v2 = $v2;
        return $me;
    }
    public function first ()
    {
        return $this->v1;
    }
    public function second ()
    {
        return $this->v2;
    }
    public function equals ($o) // [Object o]
    {
        return (($o instanceof Pair && $this->equal($o::first(), $this->first())) && $this->equal($o::second(), $this->second()));
    }
    public function hashCode ()
    {
        return ($this->first()->hashCode() ^ $this->second()->hashCode());
    }
    protected function equal ($first, $second) // [Object first, Object second]
    {
        if ((($first == null) && ($second == null)))
            return  TRUE ;
        if ((($first == null) || ($second == null)))
            return  FALSE ;
        return $first->equals($second);
    }
}
Pair::__staticinit(); // initialize static vars for this class on load


text:
{-# LANGUAGE DeriveDataTypeable #-}
module ConfigParser where

import Text.JSON
import Text.JSON.Generic
import qualified Data.Map as M

data Pattern = Pattern {
    pattern :: String,
    textToSend :: String,
    nextDispatcher :: String,
    timeout :: Int
} deriving (Eq, Show, Data, Typeable)

data Dispatcher = Dispatcher {
    name :: String,
    dispatch :: [Pattern]
} deriving (Eq, Show, Data, Typeable)

data Config = Config {
    mainDispatcher :: String,
    dispatchers :: [Dispatcher]
} deriving (Eq, Show, Data, Typeable)

data Rules = Rules {
    entryPoint :: String,
    dispatchMap :: M.Map String [Pattern]
} deriving (Eq, Show)

parseRules :: String -> IO Rules
parseRules fileName = do
    file <- readFile fileName
    let jsonConfig = decodeJSON file :: Config
    return $ Rules {entryPoint = (mainDispatcher jsonConfig),
                    dispatchMap = createMap (dispatchers jsonConfig)}
    where
        createMap :: [Dispatcher] -> M.Map String [Pattern]
        createMap = M.fromList . map parseDispatcher
        parseDispatcher :: Dispatcher -> (String, [Pattern])
        parseDispatcher d = (name d, dispatch d)


text:
package deployment

import (
	"fmt"
	"reflect"

	"github.com/golang/glog"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/apis/extensions"
	deploymentutil "k8s.io/kubernetes/pkg/util/deployment"
)

// Rolling back to a revision; no-op if the toRevision is deployment's current revision
func (dc *DeploymentController) rollback(deployment *extensions.Deployment, toRevision *int64) (*extensions.Deployment, error) {
	newRS, allOldRSs, err := dc.getAllReplicaSetsAndSyncRevision(deployment, true)
	if err != nil {
		return nil, err
	}
	allRSs := append(allOldRSs, newRS)
	// If rollback revision is 0, rollback to the last revision
	if *toRevision == 0 {
		if *toRevision = lastRevision(allRSs); *toRevision == 0 {
			// If we still can't find the last revision, gives up rollback
			dc.emitRollbackWarningEvent(deployment, deploymentutil.RollbackRevisionNotFound, "Unable to find last revision.")
			// Gives up rollback
			return dc.updateDeploymentAndClearRollbackTo(deployment)
		}
	}
	for _, rs := range allRSs {
		v, err := deploymentutil.Revision(rs)
		if err != nil {
			glog.V(4).Infof("Unable to extract revision from deployment's replica set %q: %v", rs.Name, err)
			continue
		}
		if v == *toRevision {
			glog.V(4).Infof("Found replica set %q with desired revision %d", rs.Name, v)
			// rollback by copying podTemplate.Spec from the replica set, and increment revision number by 1
			// no-op if the the spec matches current deployment's podTemplate.Spec
			deployment, performedRollback, err := dc.rollbackToTemplate(deployment, rs)
			if performedRollback && err == nil {
				dc.emitRollbackNormalEvent(deployment, fmt.Sprintf("Rolled back deployment %q to revision %d", deployment.Name, *toRevision))
			}
			return deployment, err
		}
	}
	dc.emitRollbackWarningEvent(deployment, deploymentutil.RollbackRevisionNotFound, "Unable to find the revision to rollback to.")
	// Gives up rollback
	return dc.updateDeploymentAndClearRollbackTo(deployment)
}

func (dc *DeploymentController) rollbackToTemplate(deployment *extensions.Deployment, rs *extensions.ReplicaSet) (d *extensions.Deployment, performedRollback bool, err error) {
	if !reflect.DeepEqual(deploymentutil.GetNewReplicaSetTemplate(deployment), rs.Spec.Template) {
		glog.Infof("Rolling back deployment %s to template spec %+v", deployment.Name, rs.Spec.Template.Spec)
		deploymentutil.SetFromReplicaSetTemplate(deployment, rs.Spec.Template)
		// set RS (the old RS we'll rolling back to) annotations back to the deployment;
		// otherwise, the deployment's current annotations (should be the same as current new RS) will be copied to the RS after the rollback.
		//
		// For example,
		// A Deployment has old RS1 with annotation {change-cause:create}, and new RS2 {change-cause:edit}.
		// Note that both annotations are copied from Deployment, and the Deployment should be annotated {change-cause:edit} as well.
		// Now, rollback Deployment to RS1, we should update Deployment's pod-template and also copy annotation from RS1.
		// Deployment is now annotated {change-cause:create}, and we have new RS1 {change-cause:create}, old RS2 {change-cause:edit}.
		//
		// If we don't copy the annotations back from RS to deployment on rollback, the Deployment will stay as {change-cause:edit},
		// and new RS1 becomes {change-cause:edit} (copied from deployment after rollback), old RS2 {change-cause:edit}, which is not correct.
		setDeploymentAnnotationsTo(deployment, rs)
		performedRollback = true
	} else {
		glog.V(4).Infof("Rolling back to a revision that contains the same template as current deployment %s, skipping rollback...", deployment.Name)
		dc.emitRollbackWarningEvent(deployment, deploymentutil.RollbackTemplateUnchanged, fmt.Sprintf("The rollback revision contains the same template as current deployment %q", deployment.Name))
	}
	d, err = dc.updateDeploymentAndClearRollbackTo(deployment)
	return
}

func (dc *DeploymentController) emitRollbackWarningEvent(deployment *extensions.Deployment, reason, message string) {
	dc.eventRecorder.Eventf(deployment, api.EventTypeWarning, reason, message)
}

func (dc *DeploymentController) emitRollbackNormalEvent(deployment *extensions.Deployment, message string) {
	dc.eventRecorder.Eventf(deployment, api.EventTypeNormal, deploymentutil.RollbackDone, message)
}

// updateDeploymentAndClearRollbackTo sets .spec.rollbackTo to nil and update the input deployment
func (dc *DeploymentController) updateDeploymentAndClearRollbackTo(deployment *extensions.Deployment) (*extensions.Deployment, error) {
	glog.V(4).Infof("Cleans up rollbackTo of deployment %s", deployment.Name)
	deployment.Spec.RollbackTo = nil
	return dc.client.Extensions().Deployments(deployment.ObjectMeta.Namespace).Update(deployment)
}


text:
package angulate.uirouter

import scala.scalajs.js
import scala.scalajs.js.RegExp

// Some code derived from scalajs-angular
// Copyright greencatsoft.com under an Apache2 license

// Some code derived from borisyankov/DefinitelyTyped
// MIT license

/**
 * \$urlRouterProvider has the responsibility of watching \$location.
 * When \$location changes it runs through a list of rules one by one until a match is found.
 * \$urlRouterProvider is used behind the scenes anytime you specify a url in a state configuration.
 * All urls are compiled into a UrlMatcher object.
 */
trait UrlRouterProvider extends js.Object {
  /**
   * Disables (or enables) deferring location change interception.
   *
   * If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain
   * the current URL), call this method at configuration time. Then, at run time, call \$urlRouter.listen() after you have
   * configured your own \$locationChangeSuccess event handler.
   *
   * @param defer Indicates whether to defer location change interception. Passing no parameter is equivalent to true.
   */
  def deferIntercept(defer: Boolean): UrlRouterProvider = js.native

  /**
   * Registers a handler for a given url matching.
   * If the handler is a function, it is injectable. It gets invoked if \$location matches. You have the option of inject the match object as \$match.
   * The handler can return
   * - falsy to indicate that the rule didn't match after all, then \$urlRouter will continue trying to find another one that matches.
   * - string which is treated as a redirect and passed to \$location.url()
   * - void or any truthy value tells \$urlRouter that the url was handled.
   * @param whenPath The incoming path that you want to redirect.
   * @param handler The handler function
   */
  def when(whenPath: RegExp, handler: js.Function): UrlRouterProvider = js.native
  /**
   * Registers a handler for a given url matching.
   * @param whenPath The incoming path that you want to redirect.
   * @param toPath a string treated as a redirect, and interpolated according to the syntax of match (i.e. like String.replace() for RegExp, or like a UrlMatcher pattern otherwise)
   */
  def when(whenPath: RegExp, toPath: String): UrlRouterProvider = js.native
  /**
   * Registers a handler for a given url matching.
   * If the handler is a function, it is injectable. It gets invoked if \$location matches. You have the option of inject the match object as \$match.
   * The handler can return
   * - falsy to indicate that the rule didn't match after all, then \$urlRouter will continue trying to find another one that matches.
   * - string which is treated as a redirect and passed to \$location.url()
   * - void or any truthy value tells \$urlRouter that the url was handled.
   * @param whenPath The incoming path that you want to redirect.
   * @param handler The handler function
   */
  def when(whenPath: UrlMatcher, handler: js.Function): UrlRouterProvider = js.native
  /**
   * Registers a handler for a given url matching.
   * @param whenPath The incoming path that you want to redirect.
   * @param toPath a string treated as a redirect, and interpolated according to the syntax of match (i.e. like String.replace() for RegExp, or like a UrlMatcher pattern otherwise)
   */
  def when(whenPath: UrlMatcher, toPath: String): UrlRouterProvider = js.native
  /**
   * Registers a handler for a given url matching.
   * If the handler is a function, it is injectable. It gets invoked if \$location matches. You have the option of inject the match object as \$match.
   * The handler can return
   * - falsy to indicate that the rule didn't match after all, then \$urlRouter will continue trying to find another one that matches.
   * - string which is treated as a redirect and passed to \$location.url()
   * - void or any truthy value tells \$urlRouter that the url was handled.
   * @param whenPath The incoming path that you want to redirect.
   * @param handler The handler function
   */
  def when(whenPath: String, handler: js.Function): UrlRouterProvider = js.native
  /**
   * Registers a handler for a given url matching.
   * @param whenPath The incoming path that you want to redirect.
   * @param toPath a string treated as a redirect, and interpolated according to the syntax of match (i.e. like String.replace() for RegExp, or like a UrlMatcher pattern otherwise)
   */
  def when(whenPath: String, toPath: String): UrlRouterProvider = js.native
  /**
   * Defines a path that is used when an invalid route is requested.
   * @param handler The function rule that returns the url path. The function is passed
   *                two params: \$injector and \$location services, and must return a url string.
   */
  def otherwise(handler: js.Function): UrlRouterProvider = js.native
  /**
   * Defines a path that is used when an invalid route is requested.
   * @param path The url path you want to redirect to
   */
  def otherwise(path: String): UrlRouterProvider = js.native

  /**
   * Defines rules that are used by \$urlRouterProvider to find matches for specific URLs.
   * @param handler Handler function that takes \$injector and \$location services as arguments.
   *                You can use them to return a valid path as a string.
   */
  def rule(handler: js.Function): UrlRouterProvider = js.native

}

/**
 * \$urlRouter service
 */
trait UrlRouterService extends js.Object{
  /**
   * Triggers an update; the same update that happens when the address bar
   * url changes, aka \$locationChangeSuccess.
   *
   * This method is useful when you need to use preventDefault() on the
   * \$locationChangeSuccess event, perform some custom logic (route protection,
   * auth, config, redirection, etc) and then finally proceed with the transition
   * by calling \$urlRouter.sync().
   */
  def sync(): Unit = js.native

  /**
   * A URL generation method that returns the compiled URL for a given
   * `UrlMatcher`, populated with the provided parameters.
   *
   * @param urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.
   * @param params An object of parameter values to fill the matcher's required parameters.
   * @param options Options for href()
   * @return Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`
   */
  def href(urlMatcher: UrlMatcher, params: UrlMatcherConfig, options: HrefOptions): String = js.native
}

/**
 * Options for the href methods
 *
 * @param lossy Default: true - If true, and if there is no url associated with the state provided in the
  *    first parameter, then the constructed href url will be built from the first navigable ancestor (aka
  *    ancestor with a valid url).
 * @param inherit Default: true, If `true` will inherit url parameters from current url.
 * @param relative Default: \$state.\$current, When transitioning with relative path (e.g '{{{^}}}'),
  *    defines which state to be relative from.
 * @param absolute If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
 */
class HrefOptions(lossy: Boolean = true, inherit: Boolean = true, relative: State = js.native, absolute: Boolean = false) extends js.Object {}


text:
<?php
class _s_textarea_control extends WP_Customize_Control {
    public $type = 'textarea';
    public function render_content() {
    ?>

            <?php echo esc_html( $this->label ); ?>
            <textarea rows="5" style="width:100%;" <?php $this->link(); ?>><?php echo esc_textarea( $this->value() ); ?></textarea>

    <?php
    }
}
?>


text:
PullPayment
=============================================

Base contract supporting async send for pull payments. Inherit from this contract and use asyncSend instead of send.

asyncSend(address dest, uint amount) internal
"""""""""""""""""""""""""""""""""""""""""""""""
Adds sent amount to available balance that payee can pull from this contract, called by payer.

withdrawPayments( )
"""""""""""""""""""""""""""""""""""""""""""""""
Sends designated balance to payee calling the contract. Throws error if designated balance is 0, if contract does not hold enough funds to pay the payee, or if the send transaction is not successful.


text:
/**
 * @fileoverview 基础UI控件
 */

function TablePanelBase(){
	this.body = $("
");
	this.table = $("
").append(this.body);
	this.items = [];
}

TablePanelBase.prototype.jQuery = function(){
	return this.table;
}

TablePanelBase.prototype.getAllItems = function(){
	return this.items;
}

TablePanelBase.prototype.getItem = function(i){
	return this.items[i];
}

TablePanelBase.prototype.add = function(o){
	var j = PorUtil.getJQuery(o);
	this.appendItem(j);
	this.items.push(j);
}

TablePanelBase.prototype.addClass = function(c){
	this.jQuery().addClass(c);
}

function HPanel(){
	TablePanelBase.call(this);
	this.tr = $("
");
	this.body.append(this.tr);
}

HPanel.prototype = new TablePanelBase();

HPanel.prototype.appendItem = function(o){
	this.tr.append($("").append(o));
}

function LeftPanel(){
	HPanel.call(this);
	this.tail = $("").width("100%");
	this.tr.append(this.tail);
}

LeftPanel.prototype = new HPanel();

LeftPanel.prototype.appendItem = function(o){
	var td = $("").append(o);
	this.tail.before(td);
}

function VPanel(){
	TablePanelBase.call(this);
}

VPanel.prototype = new TablePanelBase();

VPanel.prototype.appendItem = function(o){
	var td = $("").append(o);
	var tr = $("
").append(td);
	this.body.append(tr);
}

function Table(r,c){
	TablePanelBase.call(this);
	this.setSize(r,c);
}

Table.prototype = new TablePanelBase();

Table.prototype.setSize = function(r,c){
	var rowCount = (typeof r == "number")?r:0;
	this.col_count = (typeof c == "number")?c:0;
	this.rows = [];
	this.cells = [];
	this.removeAllRows();
	this.appendRows(rowCount);
}

Table.prototype.getRows = function(){
	return this.rows;
}

Table.prototype.getRow = function(r){
	return $(this.rows[r]);
}

Table.prototype.getCell = function(r,c){
	return $(this.cells[r][c]);
}

Table.prototype.getTable = function(){
	return this.jQuery();
}

Table.prototype.removeAllRows = function(){
	this.body.empty();
	this.rows = [];
	this.cells = [];
}

Table.prototype.clearRows = function(){
	for(var i=0;i<this.cells.length;i++){
		for(var j=0;j<this.cells[i].length;j++){
			$(this.cells[i][j]).empty();
		}
	}
}

Table.prototype.getColCells = function(c){
	var ret = [];
	for(var i=0;i<this.cells.length;i++){
		ret.push(this.cells[i][c]);
	}
	return ret;
}

Table.prototype.appendRows = function(r){
	if (typeof r != "number") return;
	var origin = this.body.html();
	var h = new Array;
	h.push(origin);
	for (var i=0;i<r;i++){
		h.push("
");
		h.push(this.renderCells());
		h.push("
");
	}
	this.body.html(h.join(''));
	this.rows = $("tr",this.body).get();
	this.cells = [];
	for (var i=0;i<this.rows.length;i++){
		this.cells.push($("td",$(this.rows[i])).get());
	}

}

Table.prototype.removeRows = function(r){
	if (typeof r != "number") return;
	for (var i=0;i<r;i++){
		var aRow = $(this.rows.pop());
		this.body.remove(aRow);
		this.cells.pop();
	}
}

Table.prototype.renderCells = function(row){
	var html = [];
	for(var j=0;j<this.col_count;j++){
		html.push("");
	}
	return html.join('');
}

Table.prototype.getRowCount = function(){
	return this.rows.length;
}

Table.prototype.getColCount = function(){
	return this.col_count;
}

function DivTable(r,c){
	this.divs = [];
	Table.call(this,r,c);
}

DivTable.prototype = new Table();

DivTable.prototype.appendRows = function(r){
	Table.prototype.appendRows.call(this,r);
	this.divs = [];
	for (var i=0;i<this.rows.length;i++){
		this.divs.push($("div",$(this.rows[i])).get());
	}
}

DivTable.prototype.renderCells = function(row){
	var html = [];
	for(var j=0;j<this.col_count;j++){
		html.push("
	");
	}
	return html.join('');
}

DivTable.prototype.getDivCell = function(r,c){
	return $(this.divs[r][c]);
}

DivTable.prototype.getColDivCells = function(c){
	var ret = [];
	for(var i=0;i<this.divs.length;i++){
		ret.push(this.divs[i][c]);
	}
	return ret;
}

DivTable.prototype.removeRows = function(r){
	Table.prototype.removeRows.call(this,r);
	for (var i=0;i<r;i++){
		this.divs.pop();
	}
}

DivTable.prototype.removeAllRows = function(){
	Table.prototype.removeAllRows.call(this);
	this.divs = [];
}

DivTable.prototype.clearRows = function(){
	for(var i=0;i<this.divs.length;i++){
		for(var j=0;j<this.divs[i].length;j++){
			$(this.divs[i][j]).empty();
		}
	}
}

function TwoSidePanel(){
	Table.call(this,1,3);
	this.getCell(0,1).width("100%");
	this.table.width("100%");
}

TwoSidePanel.prototype = new Table();

TwoSidePanel.prototype.setLeft = function(l){
	this.left = PorUtil.getJQuery(l);
	this.getCell(0,0).append(this.left);
}

TwoSidePanel.prototype.setRight = function(r){
	this.right = PorUtil.getJQuery(r);
	this.getCell(0,2).append(this.right);
}

function MessageBar(_id){
	if (_id) {
		Component.call(this,"#"+_id);
		var instance = this;
		this.container().css("display","none").dblclick(function(){
			instance.clearMessage();
		}).addClass("por-MessageBar");
	}
}

MessageBar.prototype = new Component();

MessageBar.prototype.dataWrapper = function(w) {
	if (w!=undefined&&this.dataWrapper()) {
		w.addComponent(this);
	} else {
		return Component.prototype.dataWrapper.call(this,w);
	}
}

MessageBar.prototype.onDataWrapperChange = function(_src,_msg){
	if (_msg){
		switch(_msg.type){
			case PorMessage.MSG_ERROR:
				if (_msg.data&&_msg.data.msg){
					this.setMessage(_msg.data.msg,true,_src);
				}
				break;
			case PorMessage.MSG_CLEAR:
				this.clearMessage();
				break;
			default:
				if (_msg.data&&_msg.data.msg){
					this.setMessage(_msg.data.msg,false,_src);
				}
		}
	}
};

MessageBar.prototype.setMessage = function(msg,is_error,src){
	var d = new Date();
	this.container().find("span").unbind();
	this.container().html("["+d.toLocaleString()+"]--"+msg+"[清除消息]").css("color","").css("display","block");
	if (!!is_error){
		this.container().css("color","red");
		/*
		if (src && typeof src.container == "function") {
			src.container().fadeOut().fadeIn();
		}
		*/
	}
	var instance = this;
	this.container().find("span").click(function(){
		instance.clearMessage();
	});
}

MessageBar.prototype.clearMessage = function(){
	//this.container().find("span").unbind();
	this.setMessage("");
	this.container().css("display","none");
};

MessageBar.prototype.destroy = function() {
	this.container().unbind("dblclick").find("span").unbind();
	if (this._globalfn)
		$("html").unbind("click",this._globalfn);
};

function PopMessageBar(_id) {
	MessageBar.call(this,_id);
	this.popPanel = new PopPanel();
	this.popPanel.content(this.container());
}

PopMessageBar.prototype = new MessageBar();

PopMessageBar.prototype.setMessage = function(msg,is_error){
	if (PorGlobals.currentPop) {
		var instance = this;
		PorGlobals.currentPop.close(function(){
			instance.setMessage(msg,is_error);
		},true);
		return;
	}
	MessageBar.prototype.setMessage.apply(this,arguments);
	this.container().css("display","none");
	if (!!is_error){
		this.popPanel.caption("错误提示");
		this.popPanel.modal(true);
	} else {
		this.popPanel.caption("消息提示");
		this.popPanel.modal(false);
	}
	this.popPanel.height(this.container().height()+5);
	this.popPanel.width(this.container().width()+5);
	this.popPanel.show();
}

PopMessageBar.prototype.clearMessage = function(){
	this.container().find("*").unbind().html("");
	this.popPanel.hide();
}

PopMessageBar.prototype.destroy = function() {
	this.popPanel.destroy();
	this.container().unbind();
	MessageBar.prototype.destroy.call(this);
};

/*
function TitleBar(t){
	Table.call(this,1,1);
	if (t){
		this.setTitle(t);
	}
	this.table.width("100%");
}

TitleBar.prototype = new Table();

TitleBar.prototype.setTitle = function(t){
	this.getCell(0,0).text(t);
}

TitleBar.prototype.getTitle = function(){
	this.getCell(0,0).text();
}
*/
function NavBar(readonly,p,createrow){
	Table.call(this,1,18);
	this.optionCounts = [5,10,20,50,100];

	this.total = 0;
	this.page = 1;

	this.getCell(0,0).attr("nowrap","");

	if (p){
		this.imagePath = p;
	} else {
		this.imagePath = PorGlobals.IMAGES_PATH;
	}
	var _divider = "";
	this.getCell(0,1).append($(_divider));

	this.first = $("").attr("_pos","first").attr("src",this.imagePath + "efgrid_page_first_disabled.gif").attr("title","首页");
	this.pre = $("").attr("_pos","pre").attr("src",this.imagePath + "efgrid_page_previous_disabled.gif").attr("title","上一页");
	this.next = $("").attr("_pos","next").attr("src",this.imagePath + "efgrid_page_next_disabled.gif").attr("title","下一页");
	this.last = $("").attr("_pos","last").attr("src",this.imagePath + "efgrid_page_last_disabled.gif").attr("title","末页");
	this.getCell(0,2).append($("
").css("text-align","center").width("20px").append(this.first)).addClass("por-Button").width("20px").css("cursor","pointer");
	this.getCell(0,3).append($("
").css("text-align","center").width("20px").append(this.pre)).addClass("por-Button").width("20px").css("cursor","pointer");
	this.getCell(0,4).append($("
").css("text-align","center").width("20px").append(this.next)).addClass("por-Button").width("20px").css("cursor","pointer");
	this.getCell(0,5).append($("
").css("text-align","center").width("20px").append(this.last)).addClass("por-Button").width("20px").css("cursor","pointer");

	this.getCell(0,6).append($(_divider));

	this.getCell(0,7).attr("nowrap","").text("每页");
	this.limitSelect = $("<select/>");
	for(var i=0;i<this.optionCounts.length;i++){
		var v = this.optionCounts[i];
		this.limitSelect.append($("<option value="+v+" />").text(v+""));
	}
	this.getCell(0,8).append(this.limitSelect);
	this.getCell(0,9).attr("nowrap","").text("条");

	this.getCell(0,10).append($(_divider));

	this.getCell(0,11).attr("nowrap","").text("跳转到第");
	var host = this;
	this.pageSelect = $("<select/>").change(function(){
		host.setPage(eval(host.pageSelect.val()));
	});
	this.getCell(0,12).append(this.pageSelect);
	this.getCell(0,13).attr("nowrap","").text("页");
	this.goBtn = $("<input type=button value=GO>").addClass("por-Button").attr("title","跳转");
	this.getCell(0,14).append(this.goBtn);

	this.getCell(0,15).append($(_divider));
	if (createrow == undefined){
		createrow = true
	}
	if (readonly!=true&&createrow==true){
		this.newRow = $("").attr("src",this.imagePath + "efgrid_add_row.gif").attr("title","新增一行");
		this.getCell(0,16).append($("
").append(this.newRow).width(16)).css("cursor","pointer");
		this.getCell(0,17).append($(_divider));
	}
	this.limitSelect.find("option").eq(0).attr("selected",true);
	this.limit = eval(this.limitSelect.val());
}

NavBar.prototype = new Table();

NavBar.prototype.setState = function(total,pages,pageIndex,limit){
	this.total = total;
	this.pages = pages;
	this.page = pageIndex+1;
	this.limit = limit;
	this.limitSelect.find("option[@value="+this.limit+"]").attr("selected",true);
	this.checkState();
}

NavBar.prototype.checkState = function(){
	var tP = this.getTotalPage();
	var status =  [ this.page <= 1,
					this.page <= 1,
					this.page >= tP,
					this.page >= tP ];
	this.first.attr("src",this.imagePath + "efgrid_page_first" + (status[0]?"_disabled":"") + ".gif");
	this.pre.attr("src",this.imagePath + "efgrid_page_previous" + (status[1]?"_disabled":"") + ".gif");
	this.next.attr("src",this.imagePath + "efgrid_page_next" + (status[2]?"_disabled":"") + ".gif");
	this.last.attr("src",this.imagePath + "efgrid_page_last" + (status[3]?"_disabled":"") + ".gif");

	if (this.total<0){
		this.getCell(0,0).text("第"+this.page+"页/共"+tP+"页");
	} else {
		this.getCell(0,0).text("共"+this.total+"条 "+"第"+this.page+"页/共"+tP+"页");
	}

	var html = [];
	if (!$.browser.mozilla){
		html.push("<select>");
		this.pageSelect.unbind();
	}
	for (var i = 1 ; i <= tP ; i++){
		html.push("<option value=");
		html.push(i);
		html.push(">");
		html.push(i);
		html.push("</option>");
	}
	if (!$.browser.mozilla){
		html.push("</select>");
		this.getCell(0,12).html(html.join(''));
		this.pageSelect = this.getCell(0,12).find("select");
		var host = this;
		this.pageSelect.change(function(){
			host.setPage(eval(host.pageSelect.val()));
		});
		try {
			var t = $(window).scrollTop();
			this.jQuery().focus();
			$(window).scrollTop(t);
		} catch (e) {

		}

	} else {
		this.pageSelect.html(html.join(''));
	}
	this.pageSelect.find("option").eq(this.page-1).attr("selected",true);
}

NavBar.prototype.getNewRow = function(){
	return this.getCell(0,16);
}

NavBar.prototype.getJumpButton = function(){
	return this.goBtn;
}

NavBar.prototype.setPage = function(p){
	this.page = p;
	this.pageSelect.find("option").eq(this.page-1).attr("selected",true);
}

NavBar.prototype.getPage = function() {
	return this.page>this.pageSelect.val()?this.pageSelect.val():this.page;
}

NavBar.prototype.getTotalPage = function(){
	return this.pages;
}

NavBar.prototype.getOffset = function(){
	return (this.page-1)*this.limit;
}

NavBar.prototype.getLimit = function(){
	return this.getLimitSelect().val();
}

NavBar.prototype.getFirst = function(){
	return this.getCell(0,2);
}

NavBar.prototype.getPrevious = function(){
	return this.getCell(0,3);
}

NavBar.prototype.getNext = function(){
	return this.getCell(0,4);
}

NavBar.prototype.getLast = function(){
	return this.getCell(0,5);
}

NavBar.prototype.isNavButtonEnabled = function(type){
	var img;
	switch(type){
		case "first":
			img = this.first;
			break;
		case "previous":
			img = this.pre;
			break;
		case "next":
			img = this.next;
			break;
		case "last":
			img = this.last;
			break;
		default:
			throw new Error("invalid type["+type+"].");
	}
	return img.attr("src").indexOf("_disabled")<0;
}

NavBar.prototype.getLimitSelect = function(){
	return this.limitSelect;
}

NavBar.prototype.toFirst = function(){
	this.page = 1;
}

NavBar.prototype.toPrevious = function(){
	this.page--;
}

NavBar.prototype.toNext = function(){
	this.page++;
}

NavBar.prototype.toLast = function(){
	this.page = this.getTotalPage();
}


text:
@class PixAccount;

@interface TumblrSlideshowViewController : PixivSlideshowViewController {
	NSString *maxID;
}

@property(readwrite, nonatomic, retain) NSString *maxID;

@end


text:
Collect log output from a tox build

**Role Variables**

.. zuul:rolevar:: zuul_work_dir
   :default: {{ zuul.project.src_dir }}

   Directory tox was run in.

.. zuul:rolevar:: zuul_use_fetch_output
   :default: false

   Whether to synchronize files to the executor work dir, or to copy them
   on the test instance.
   When set to false, the role synchronizes the file to the executor.
   When set to true, the job needs to use the fetch-output role later.


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
			http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		">

	<bean class="com.feilong.entity.ConstructorListInterfaceBeanEntity">
		<constructor-arg name="users">
			<list>
				<ref bean="user1" />
				<ref bean="user2" />
			</list>
		</constructor-arg>
	</bean>

	<bean id="user1" class="com.feilong.entity.InterfaceUserImpl" />
	<bean id="user2" class="com.feilong.entity.InterfaceUserImpl" />
</beans>


text:
using System;

namespace Argolis.Models
{
    /// <summary>
    /// Exception thrown when template for the given resource type is not found
    /// </summary>
    /// <seealso cref="System.Exception" />
    public class MissingTemplateException : Exception
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MissingTemplateException"/> class.
        /// </summary>
        /// <param name="type">The resource type.</param>
        public MissingTemplateException(Type type)
            : base(GetMessage(type))
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MissingTemplateException"/> class.
        /// </summary>
        /// <param name="type">The resource type.</param>
        /// <param name="exception">A more detailed exception.</param>
        public MissingTemplateException(Type type, Exception exception)
            : base(GetMessage(type), exception)
        {
        }

        private static string GetMessage(Type type)
        {
            return $"Template not found for type {type.FullName}";
        }
    }
}


text:
import jinja2
import markupsafe

def get_template(template):

    def include_raw_file(file_name):
        try:
            return markupsafe.Markup(loader.get_source(env, file_name)[0])
        except jinja2.TemplateNotFound:
            # NOTE(amaretskiy): re-raise error to make its message clear
            raise IOError("File not found: %s" % file_name)

    loader = jinja2.PackageLoader("rally.ui", "templates")
    env = jinja2.Environment(loader=loader)
    env.globals["include_raw_file"] = include_raw_file

    return env.get_template(template)


text:
package org.apache.ibatis.reflection.factory;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;

import org.apache.ibatis.reflection.ReflectionException;
import org.apache.ibatis.reflection.Reflector;

/**
 * @author Clinton Begin
 */
public class DefaultObjectFactory implements ObjectFactory, Serializable {

  private static final long serialVersionUID = -8855120656740914948L;

  @Override
  public <T> T create(Class<T> type) {
    return create(type, null, null);
  }

  @SuppressWarnings("unchecked")
  @Override
  public <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
    Class<?> classToCreate = resolveInterface(type);
    // we know types are assignable
    return (T) instantiateClass(classToCreate, constructorArgTypes, constructorArgs);
  }

  private  <T> T instantiateClass(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
    try {
      Constructor<T> constructor;
      if (constructorArgTypes == null || constructorArgs == null) {
        constructor = type.getDeclaredConstructor();
        try {
          return constructor.newInstance();
        } catch (IllegalAccessException e) {
          if (Reflector.canControlMemberAccessible()) {
            constructor.setAccessible(true);
            return constructor.newInstance();
          } else {
            throw e;
          }
        }
      }
      constructor = type.getDeclaredConstructor(constructorArgTypes.toArray(new Class[0]));
      try {
        return constructor.newInstance(constructorArgs.toArray(new Object[0]));
      } catch (IllegalAccessException e) {
        if (Reflector.canControlMemberAccessible()) {
          constructor.setAccessible(true);
          return constructor.newInstance(constructorArgs.toArray(new Object[0]));
        } else {
          throw e;
        }
      }
    } catch (Exception e) {
      String argTypes = Optional.ofNullable(constructorArgTypes).orElseGet(Collections::emptyList)
          .stream().map(Class::getSimpleName).collect(Collectors.joining(","));
      String argValues = Optional.ofNullable(constructorArgs).orElseGet(Collections::emptyList)
          .stream().map(String::valueOf).collect(Collectors.joining(","));
      throw new ReflectionException("Error instantiating " + type + " with invalid types (" + argTypes + ") or values (" + argValues + "). Cause: " + e, e);
    }
  }

  protected Class<?> resolveInterface(Class<?> type) {
    Class<?> classToCreate;
    if (type == List.class || type == Collection.class || type == Iterable.class) {
      classToCreate = ArrayList.class;
    } else if (type == Map.class) {
      classToCreate = HashMap.class;
    } else if (type == SortedSet.class) { // issue #510 Collections Support
      classToCreate = TreeSet.class;
    } else if (type == Set.class) {
      classToCreate = HashSet.class;
    } else {
      classToCreate = type;
    }
    return classToCreate;
  }

  @Override
  public <T> boolean isCollection(Class<T> type) {
    return Collection.class.isAssignableFrom(type);
  }

}


text:
import {devAssert} from '#utils/log';

import {Renderer} from './amp-ad-type-defs';
import {renderCreativeIntoFriendlyFrame} from './friendly-frame-util';

/**
 * @typedef {{
 *   creativeMetadata: ./amp-ad-type-defs.CreativeMetaDataDef,
 * }}
 */
export let CreativeData;

/**
 * Render a validated AMP creative directly in the parent page.
 */
export class FriendlyFrameRenderer extends Renderer {
  /**
   * Constructs a FriendlyFrameRenderer instance. The instance values here are
   * used by TemplateRenderer, which inherits from FriendlyFrameRenderer.
   */
  constructor() {
    super();
  }

  /** @override */
  render(context, element, creativeData) {
    creativeData = /** @type {CreativeData} */ (creativeData);

    const {adUrl, size} = context;
    const {creativeMetadata} = creativeData;

    devAssert(size, 'missing creative size');
    devAssert(adUrl, 'missing ad request url');

    return renderCreativeIntoFriendlyFrame(
      adUrl,
      size,
      element,
      creativeMetadata
    );
  }
}


text:
package slug

import (
	"strings"

	"github.com/avelino/slugify"
)

// Generate slugs similar to GitHub's slugs on markdown parsing
func Generate(text string) string {
	s := strings.ReplaceAll(text, "/", "")
	return slugify.Slugify(strings.TrimSpace(s))
}


text:
		<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#primary_navigation_wrap" aria-controls="primary_navigation_wrap" aria-expanded="false" aria-label="Toggle navigation">

		</button>

		<a class="navbar-brand" href="<?php echo home_url('/'); ?>"><?php bloginfo('name') ?>

			<?php if(has_nav_menu('primary_navigation')): ?>
				<?php wp_nav_menu( array(
					'theme_location'	=> 'primary_navigation',
					'container' 			=> false,
					'items_wrap' 			=> '
%3$s
',
					'depth'           => 5,
					'walker' 					=> new wp_bootstrap_navwalker()
				) ); ?>
			<?php endif; ?>


text:
package com.tianjunwei.aop;

public interface IDaoOperation {

	public void save();

	public void delete();

}


text:
% Matlab script for the pyscho physic try

%% Global Initialization

close all;              % close all figures
clc;                    % clear the command line
fclose('all');          % close all open files
delete(instrfindall);   % Reset Com Port
%delete(timerfindall);  % Delete Timers
digits(6)               % Calculus with 6 digits
if(exist('s','var'))
    if(isa(s,'serial')) % Suppress the serial variable if it exists
        delete(s);
        clear all; %#ok<CLSCR>
    end
end

%% Connection with the arduino

Info = instrhwinfo('serial');
ports = Info.AvailableSerialPorts;
port = ports(end);
%port =  'COM5';

s=serial(port,'BaudRate',57600);

fopen(s);
pause(3);

%% Experimental paramters

f1 = 20;
f2 = 15;

% Amplitude should be below 1, no check in scripts though
a1 = 0.5;
a2 = 0.6;

% Duration given in ms
duration = 1000;
pause_t = 1000;

exp = [f1, f2, a1, a2, duration, pause_t];

%% Send the parameters to the arduino
disp('Sending data to the arduino A0')

fwrite(s,exp,'uint16');
if(fread(s,1) == 115)
    disp('Sending Sucessfull')
else
    warning('Some data may not have been sent properly'); %#ok<WNTAG>
end
%% Wait for the stimuli

total_duration = (2*duration + pause_t)/1000; %total duration in s
pause(total_duration);

%% Get the feedback from th earduino and display the results

disp('Reading the results from the arduino')

readasync(s);

feedback = [];  %Raw data incoming from arduino
timeout = 10^2; %Timeout for the reading

while(j < timeout && length(feedback) < timeout/2)
    feedback = [feedback,native2unicode(fread(s,1))]; %#ok<AGROW,N2UNI>
    j = j + 1;
end

[time, button_pressed] = arduino2matlab(feedback, timeout);

% display the result
sprintf('time elapsed in ms : %d \n',time)
sprintf('button pressed : %s \n', button_pressed)

%% Delete the connection with Matlab, reset the variables
stopasync(s);
delete(s);
clear s;


text:
#ifndef UI_TEXT_GAMESERVER_APPLICATION_HPP
#define UI_TEXT_GAMESERVER_APPLICATION_HPP

#include<iostream>
#include"ui/Observable.hpp"
#include"neuroServer/Application.hpp"
#include"ui/text/CommandShell.hpp"
#include"ui/text/gameServer/Server.hpp"
#include"ui/text/gameServer/ArmyLoader.hpp"
#include"ui/text/gameServer/BoardLoader.hpp"

namespace ui {
namespace text {
namespace gameServer {

	/**
		* @brief The class to start the text ui for the server.
		*/
	class Application {
		public:
			/**
				* @brief Create an application watching the given application.
				*/
			Application(neuroServer::Application & application);
		private:
			neuroServer::Application & application;
			ArmyLoader armyLoader;
			BoardLoader boardLoader;
			Server server;
	};

}
}
}

#endif


text:
package org.jboss.weld.tests.enterprise.lifecycle;

import jakarta.ejb.Local;

@Local
public interface KleinStadt {
    void begruendet();

    void zustandVergessen();

    void zustandVerloren();

}


text:
State of the popup.

    String, default 'closed'

The best way to find out if popup is opened (and since only one popup can be opened at any particular time), to use jQuery to
find popup div and check if it exists:
<textarea class="javascript">
if ($('#w2ui-popup').length > 0) {
    console.log('popup is opened');
}
</textarea>

You can also find out what is the state of the popup if you read status property, which will provide you
with more information about popup states, such as open, closed, resizing, etc. Status can be one of the following:

opening

open

closing

closed

resizing

moving

Use example below to find out how states are transition:
<textarea class="javascript">
$('body').append('

');
setInterval(function () {
    $('#status').html(w2popup.status);
}, 1);

w2popup.open({
    title: 'Text',
    body: 'Move me, then resize, and close',
    showMax: true,
    showClose: true
});
</textarea>


text:
NAME

git-http-push - Push objects over HTTP/DAV to another repository
SYNOPSIS

git http-push [--all] [--dry-run] [--force] [--verbose] <url> <ref> [<ref>...]

DESCRIPTION

Sends missing objects to remote repository, and updates the remote branch.

NOTE: This command is temporarily disabled if your libcurl is older than 7.16, as the combination has been reported not to work and sometimes corrupts repository.
OPTIONS

--all

Do not assume that the remote repository is complete in its current state, and verify all objects in the entire local ref(cqs history exist in the remote repository.

--force

Usually, the command refuses to update a remote ref that is not an ancestor of the local ref used to overwrite it. This flag disables the check. What this means is that the remote repository can lose commits; use it with care.

--dry-run

Do everything except actually send the updates.

--verbose

Report the list of objects being walked locally and the list of objects successfully sent to the remote repository.

-d, -D

Remove <ref> from remote repository. The specified branch cannot be the remote HEAD. If -d is specified the following other conditions must also be met:

h'-04'(buh'+03'c

\(bu 2.3

Remote HEAD must resolve to an object that exists locally

h'-04'(buh'+03'c

\(bu 2.3

Specified branch resolves to an object that exists locally

h'-04'(buh'+03'c

\(bu 2.3

Specified branch is an ancestor of the remote HEAD

<ref>...

The remote refs to update.

SPECIFYING THE REFS

A <ref> specification can be either a single pattern, or a pair of such patterns separated by a colon ":" (this means that a ref name cannot have a colon in it). A single pattern <name> is just a shorthand for <name>:<name>.

Each pattern pair consists of the source side (before the colon) and the destination side (after the colon). The ref to be pushed is determined by finding a match that matches the source side, and where it is pushed is determined by using the destination side.

h'-04'(buh'+03'c

\(bu 2.3

It is an error if <src> does not match exactly one of the local refs.

h'-04'(buh'+03'c

\(bu 2.3

If <dst> does not match any remote ref, either

h'-04'(buh'+03'c

\(bu 2.3

it has to start with "refs/"; <dst> is used as the destination literally in this case.

h'-04'(buh'+03'c

\(bu 2.3

<src> == <dst> and the ref that matched the <src> must not exist in the set of remote refs; the ref matched <src> locally is used as the name of the destination.

Without --force, the <src> ref is stored at the remote only if <dst> does not exist, or <dst> is a proper subset (i.e. an ancestor) of <src>. This check, known as "fast-forward check", is performed in order to avoid accidentally overwriting the remote ref and lose other peoples*(Aq commits from there.

With --force, the fast-forward check is disabled for all refs.

Optionally, a <ref> parameter can be prefixed with a plus + sign to disable the fast-forward check only on that ref.
GIT

Part of the git(1) suite