text:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace WebApplication2
{
	/// <summary>
	/// Summary description for frmEmergencyProcedures.
	/// </summary>
	public partial class frmPSEPSteps : System.Web.UI.Page
	{
		private static string strURL =
			System.Configuration.ConfigurationSettings.AppSettings["local_url"];
		private static string strDB =
			System.Configuration.ConfigurationSettings.AppSettings["local_db"];
		protected System.Web.UI.WebControls.Label Label2;
		public SqlConnection epsDbConn=new SqlConnection(strDB);

		protected void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			Load_Procedures();
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);

		}
		#endregion
		private void Load_Procedures()
		{
			lblContents1.Text="Complete the list below to identify the key steps"
				+ " that are taken for process "
				+ Session["ProcessName"].ToString()
				+ ".";
			lblContents2.Text="";
			if (!IsPostBack)
			{
				DataGrid1.Columns[4].Visible=false;
				loadData();
			}
		}
		private void loadData ()
		{
			SqlCommand cmd=new SqlCommand();
			cmd.CommandType=CommandType.StoredProcedure;
			cmd.CommandText="wms_RetrievePSEPSteps";
			cmd.Connection=this.epsDbConn;
			cmd.Parameters.Add ("@ProcsId",SqlDbType.Int);
			cmd.Parameters["@ProcsId"].Value=Session["ProcsId"].ToString();
			DataSet ds=new DataSet();
			SqlDataAdapter da=new SqlDataAdapter(cmd);
			da.Fill(ds,"StepsAdm");
			Session["ds"] = ds;
			DataGrid1.DataSource=ds;
			DataGrid1.DataBind();
			assignSeq();
		}
		protected void btnAdd_Click(object sender, System.EventArgs e)
		{
			Session["CUpdStep"] = "frmPSEPSteps";
			Response.Redirect (strURL + "frmUpdStep.aspx?"
				+ "&btnAction=" + "Add");
				/*Session["CStepTypes"]="frmPSEPSteps";
				Response.Redirect (strURL + "frmStepTypes.aspx?");*/
		}
		protected void btnBack_Click(object sender, System.EventArgs e)
		{
			updateGrid();
			Exit();
		}
		private void Exit()
		{
			Response.Redirect (strURL + Session["CPSEPSteps"].ToString() + ".aspx?");
		}
		private void assignSeq()
		{
			foreach (DataGridItem i in DataGrid1.Items)
			{
				TextBox tb = (TextBox) (i.Cells[2].FindControl("txtSeq"));
				if (i.Cells[1].Text == " ")
				{
					tb.Text="99";
				}
				else tb.Text=i.Cells[1].Text;
			}
		}
		private void updateGrid()
		{
			foreach (DataGridItem i in DataGrid1.Items)
			{
				TextBox tb = (TextBox) (i.Cells[2].FindControl("txtSeq"));
				{
					SqlCommand cmd=new SqlCommand();
					cmd.CommandType=CommandType.StoredProcedure;
					cmd.CommandText="wms_UpdateProfileSEPStepNo";
					cmd.Connection=this.epsDbConn;
					cmd.Parameters.Add("@Id", SqlDbType.Int);
					cmd.Parameters ["@Id"].Value=i.Cells[0].Text;
					cmd.Parameters.Add("@Seq", SqlDbType.Int);
					cmd.Parameters ["@Seq"].Value=Int32.Parse(tb.Text);
					cmd.Connection.Open();
					cmd.ExecuteNonQuery();
					cmd.Connection.Close();
				}
			}
		}

		private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			updateGrid();
			if (e.CommandName == "Update")
			{
				Session["CUpdStep"] = "frmPSEPSteps";
				Response.Redirect (strURL + "frmUpdStep.aspx?"
					+ "&btnAction=" + "Update"
					+ "&Id=" + e.Item.Cells[0].Text
					+ "&Name=" + e.Item.Cells[3].Text
					+ "&Desc=" + e.Item.Cells[4].Text);
			}
			else if (e.CommandName == "Delete")
			{
				updateGrid();
				SqlCommand cmd=new SqlCommand();
				cmd.CommandType=CommandType.StoredProcedure;
				cmd.CommandText="wms_DeleteStep";
				cmd.Connection=this.epsDbConn;
				cmd.Parameters.Add ("@Id",SqlDbType.Int);
				cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text;
				cmd.Connection.Open();
				cmd.ExecuteNonQuery();
				cmd.Connection.Close();
				loadData();
			}
			/*if (e.CommandName == "Staff")
			{
				updateGrid();
				Session["ProfileSEPStepTypesId"]=e.Item.Cells[0].Text;
				Session["ProfileSEPSName"]=e.Item.Cells[3].Text;
				Session["CSEPSStaff"]="frmPSEPSteps";
				Session["StaffingType"]="Staff";
				Response.Redirect (strURL + "frmProfileSEPSStaff.aspx?");

			}
			else if (e.CommandName == "Resources")
			{
				updateGrid();
				Session["ProfileSEPStepTypesId"]=e.Item.Cells[0].Text;
				Session["ProfileSEPSName"]=e.Item.Cells[3].Text;
				Session["CSEPResTypes"]="frmPSEPSteps";
				Response.Redirect (strURL + "frmProfileSEPSRes.aspx?");
			}
			else if (e.CommandName == "Services")
			{
				updateGrid();
				Session["ProfileSEPStepTypesId"]=e.Item.Cells[0].Text;
				Session["ProfileSEPSName"]=e.Item.Cells[3].Text;
				Session["CSEPServices"]="frmPSEPSteps";
				Response.Redirect (strURL + "frmProfileSEPSSer.aspx?");
			}*/
		}

		protected void btnSignoff_Click(object sender, System.EventArgs e)
		{
			updateGrid();
			Response.Redirect (strURL + "frmEnd.aspx?");
		}
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Exit();
        }
}

}


text:
package com.anteoy.designPatterns.strategy;

public class DuckTest {

    public static void main(String[] args) {
        System.out.println("测试鸭子程序");
        System.out.println("************************");
        Duck duck = null;
//		duck = new MallardDuck();
//		duck = new RedheadDuck();
//		duck = new RubberDuck();
//		duck = new BigYellow();
        duck = new SpaceDuck();

        duck.display();
        duck.quack();
        duck.fly();
        System.out.println("************************");
        System.out.println("测试完毕");
    }

}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PROCESS_START_IN_DIR_HPP
#define BOOST_PROCESS_START_IN_DIR_HPP

#include <boost/process/detail/config.hpp>
#include <boost/process/detail/handler.hpp>
#include <boost/process/locale.hpp>

#if defined (BOOST_POSIX_API)
#include <boost/process/detail/posix/start_dir.hpp>
#elif defined (BOOST_WINDOWS_API)
#include <boost/process/detail/windows/start_dir.hpp>
#endif

#include <boost/process/detail/config.hpp>
#include <string>
#include <boost/filesystem/path.hpp>

/** \file boost/process/start_dir.hpp
 *
Header which provides the start_dir property, which allows to set the directory
the process shall be started in.
\xmlonly
<programlisting>
namespace boost {
  namespace process {
    <emphasis>unspecified</emphasis> <globalname alt="boost::process::start_dir">start_dir</globalname>;
  }
}
</programlisting>
\endxmlonly

 */

namespace boost { namespace process { namespace detail {

struct start_dir_
{
    constexpr start_dir_() {};

    template<typename Char>
    api::start_dir_init<Char> operator()(const std::basic_string<Char> & st) const {return {st}; }
    template<typename Char>
    api::start_dir_init<Char> operator()(std::basic_string<Char> && s) const {return {std::move(s)}; }
    template<typename Char>
    api::start_dir_init<Char> operator()(const Char* s)                const {return {s}; }
    api::start_dir_init<typename boost::filesystem::path::value_type>
                              operator()(const boost::filesystem::path & st) const {return {st.native()}; }

    template<typename Char>
    api::start_dir_init<Char> operator= (const std::basic_string<Char> & st) const {return {st}; }
    template<typename Char>
    api::start_dir_init<Char> operator= (std::basic_string<Char> && s) const {return {std::move(s)}; }
    template<typename Char>
    api::start_dir_init<Char> operator= (const Char* s)                const {return {s}; }
    api::start_dir_init<typename boost::filesystem::path::value_type>
                              operator= (const boost::filesystem::path & st) const {return {st.native()}; }

};

template<> struct is_wchar_t<api::start_dir_init<wchar_t>> : std::true_type {};

template<>
struct char_converter<char, api::start_dir_init<wchar_t>>
{
    static api::start_dir_init<char> conv(const api::start_dir_init<wchar_t> & in)
    {
        return api::start_dir_init<char>{::boost::process::detail::convert(in.str())};
    }
};

template<>
struct char_converter<wchar_t, api::start_dir_init<char>>
{
    static api::start_dir_init<wchar_t> conv(const api::start_dir_init<char> & in)
    {
        return api::start_dir_init<wchar_t>{::boost::process::detail::convert(in.str())};
    }
};

}

/**

To set the start dir, the `start_dir` property is provided.

The valid operations are the following:

\code{.cpp}
start_dir=path
start_dir(path)
\endcode

It can be used with `std::string`, `std::wstring` and `boost::filesystem::path`.

 */
constexpr ::boost::process::detail::start_dir_ start_dir;

}}

#endif


text:
module Babies
  class Item
  end
end


text:
[Deis](http://deis.io)

[DigitalOcean](https://www.digitalocean.com/)

[Melvin Lammerts](http://dokku.net)


text:
<?php
namespace Video\CommonBundle\REST\Canvas;
use Video\CommonBundle\REST\BaseREST;

class CanvasBaseREST extends BaseREST{
	public function init(){
		//设定为canvas的api地址、口令、响应头
		$base_url = $this->container->getParameter('canvas_api_url');
		$access_token = $this->container->getParameter('canvas_api_token');
		$auth_head = $this->container->getParameter('canvas_api_auth_head');
		$error_head = $this->container->getParameter('canvas_api_error_head');
		$this->curlHelper->init($base_url,$access_token,$auth_head,$error_head);
	}
}


text:
![Build Status](https://travis-ci.org/github/github-ldap.png?branch=master)

# Github::Ldap

GitHub-Ldap is a wrapper on top of Net::LDAP to make it human friendly.

## Installation

Add this line to your application's Gemfile:

    gem 'github-ldap'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install github-ldap

## Usage

### Initialization

GitHub-Ldap let you use an external ldap server to authenticate your users with.

There are a few configuration options required to use this adapter:

* host: is the host address where the ldap server lives.
* port: is the port where the ldap server lives.
* hosts: (optional) an enumerable of pairs of hosts and corresponding ports with which to attempt opening connections (default [[host, port]]). Overrides host and port if set.
* encryption: is the encryption protocol, disabled by default. The valid options are `ssl` and `tls`.
* uid: is the field name in the ldap server used to authenticate your users, in ActiveDirectory this is `sAMAccountName`.

Using administrator credentials is optional but recommended. You can pass those credentials with these two options:

* admin_user: is the the ldap administrator user dn.
* admin_password: is the password for the administrator user.

Initialize a new adapter using those required options:

```ruby
  ldap = GitHub::Ldap.new options
```

See GitHub::Ldap#initialize for additional options.

### Querying

Searches are performed against an individual domain base, so the first step is to get a new `GitHub::Ldap::Domain` object for the connection:

```ruby
  ldap = GitHub::Ldap.new options
  domain = ldap.domain("dc=github,dc=com")
```

When we have the domain, we can check if a user can log in with a given password:

```ruby
  domain.valid_login? 'calavera', 'secret'
```

Or whether a user is member of the given groups:

```ruby
  entry = ldap.domain('uid=calavera,dc=github,dc=com').bind
  domain.is_member? entry, %w(Enterprise)
```

### Virtual Attributes

Some LDAP servers have support for virtual attributes, or overlays. These allow to perform queries more efficiently on the server.

To enable virtual attributes you can set the option `virtual_attributes` initializing the ldap connection.
We use our default set of virtual names if this option is just set to `true`.

```ruby
  ldap = GitHub::Ldap.new {virtual_attributes: true}
```

You can also override our defaults by providing your server mappings into a Hash.
The only mapping supported for now is to check virtual membership of individuals in groups.

```ruby
  ldap = GitHub::Ldap.new {virtual_attributes: {virtual_membership: 'memberOf'}}
```

### Testing support

GitHub-Ldap uses [ladle](https://github.com/NUBIC/ladle) for testing. Ladle is not required by default, so you'll need to add it to your gemfile separatedly and require it.

Once you have it installed you can start the testing ldap server in the setup phase for your tests:

```ruby
require 'github/ldap/server'

def setup
  GitHub::Ldap.start_server
end

def teardown
  GitHub::Ldap.stop_server
end
```

GitHub-Ldap includes a set of configured users for testing, but you can provide your own users into a ldif file:

```ruby
def setup
  GitHub::Ldap.start_server \
    user_fixtures: ldif_path
end
```

If you provide your own user fixtures, you'll probably need to change the default user domain, the administrator name and her password:

```ruby
def setup
  GitHub::Ldap.start_server \
    user_fixtures:  ldif_path,
    user_domain:    'dc=evilcorp,dc=com'
    admin_user:     'uid=eviladmin,dc=evilcorp,dc=com',
    admin_password: 'correct horse battery staple'
end
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## Releasing

This section is for gem maintainers to cut a new version of the gem. See
[jch/release-scripts](https://github.com/jch/release-scripts) for original
source of release scripts.

* Create a new branch from `master` named `release-x.y.z`, where `x.y.z` is the version to be released
* Update `github-ldap.gemspec` to x.y.z following [semver](http://semver.org)
* Run `script/changelog` and paste the draft into `CHANGELOG.md`. Edit as needed
* Create pull request to solict feedback
* After merging the pull request, on the master branch, run `script/release`


text:
package workbench.gui.macros;

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import workbench.interfaces.ValidatingComponent;
import workbench.resource.ResourceMgr;

import workbench.gui.WbSwingUtilities;

import workbench.sql.macros.MacroGroup;
import workbench.sql.macros.MacroManager;

import workbench.util.StringUtil;

/**
 *
 * @author Thomas Kellerer
 */
public class AddMacroPanel
	extends JPanel
	implements WindowListener, ValidatingComponent
{
	private int macroClientId;

	public AddMacroPanel(int clientId)
	{
		initComponents();
		this.macroClientId = clientId;
		List<MacroGroup> groups = MacroManager.getInstance().getMacros(macroClientId).getGroups();
		DefaultComboBoxModel model = new DefaultComboBoxModel();
		for (MacroGroup group : groups)
		{
			model.addElement(group);
		}
		groupDropDown.setModel(model);
	}

	public MacroGroup getSelectedGroup()
	{
		return (MacroGroup)groupDropDown.getSelectedItem();
	}

	public String getMacroName()
	{
		return macroName.getText();
	}

	public boolean getExpandWhileTyping()
	{
		return cbExpand.isSelected();
	}

	@Override
	public boolean validateInput()
	{
		String name = macroName.getText();
		if (StringUtil.isBlank(name))
		{
			WbSwingUtilities.showErrorMessageKey(this, "ErrMcrNameReq");
			return false;
		}
		if (getExpandWhileTyping())
		{
			boolean ok = name.matches("\\w+");
			if (!ok)
			{
				WbSwingUtilities.showErrorMessageKey(this, "ErrMcrNmNoSpace");
				return false;
			}
		}
		return true;
	}

	@Override
	public void componentDisplayed()
	{
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents()
  {
		GridBagConstraints gridBagConstraints;

    jLabel1 = new JLabel();
    jLabel2 = new JLabel();
    groupDropDown = new JComboBox();
    macroName = new JTextField();
    cbExpand = new JCheckBox();

    setLayout(new GridBagLayout());

    jLabel1.setText(ResourceMgr.getString("LblMacroGrpName"));     gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.anchor = GridBagConstraints.WEST;
    gridBagConstraints.insets = new Insets(7, 5, 0, 0);
    add(jLabel1, gridBagConstraints);

    jLabel2.setText(ResourceMgr.getString("LblMacroName"));     gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.anchor = GridBagConstraints.WEST;
    gridBagConstraints.insets = new Insets(7, 5, 0, 0);
    add(jLabel2, gridBagConstraints);

    groupDropDown.setModel(new DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
    gridBagConstraints.anchor = GridBagConstraints.WEST;
    gridBagConstraints.insets = new Insets(7, 9, 0, 5);
    add(groupDropDown, gridBagConstraints);

    macroName.setColumns(30);
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
    gridBagConstraints.anchor = GridBagConstraints.WEST;
    gridBagConstraints.insets = new Insets(7, 9, 0, 5);
    add(macroName, gridBagConstraints);

    cbExpand.setText(ResourceMgr.getString("LblExpandMacro"));     cbExpand.setToolTipText(ResourceMgr.getString("d_LblExpandMacro"));     gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    gridBagConstraints.insets = new Insets(4, 1, 0, 0);
    add(cbExpand, gridBagConstraints);
  }// </editor-fold>//GEN-END:initComponents
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private JCheckBox cbExpand;
  private JComboBox groupDropDown;
  private JLabel jLabel1;
  private JLabel jLabel2;
  private JTextField macroName;
  // End of variables declaration//GEN-END:variables

	@Override
	public void windowOpened(WindowEvent e)
	{
		EventQueue.invokeLater(new Runnable()
		{
			@Override
			public void run()
			{
				macroName.requestFocusInWindow();
			}
		});
	}

	@Override
	public void windowClosing(WindowEvent e)
	{
	}

	@Override
	public void windowClosed(WindowEvent e)
	{
	}

	@Override
	public void windowIconified(WindowEvent e)
	{
	}

	@Override
	public void windowDeiconified(WindowEvent e)
	{
	}

	@Override
	public void windowActivated(WindowEvent e)
	{
	}

	@Override
	public void windowDeactivated(WindowEvent e)
	{
	}
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M2.825,19.45V4.55H17.725V11.05L21.175,7.6V16.4L17.725,12.95V19.45Z"/>
</vector>


text:
<?xml version="1.0" encoding="UTF-8" ?>

<!--

This file is part of the Lug package.

(c) Eric GELOEN <geloen.eric@gmail.com>

For the full copyright and license information, please read the LICENSE
file that was distributed with this source code.

-->

<container xmlns="http://symfony.com/schema/dic/services">
    <services>
        <service id="lug.grid.batcher" class="Lug\Bundle\GridBundle\Batch\Batcher">
            <argument type="service" id="lug.grid.batcher.internal" />
        </service>

        <service id="lug.grid.batcher.internal" class="Lug\Component\Grid\Batch\Batcher">
            <argument type="service" id="lug.grid.registry.batch" />
        </service>

        <service id="lug.grid.batch.type.batch" class="Lug\Bundle\GridBundle\Batch\Type\BatchType">
            <tag name="lug.grid.batch" alias="batch" />
        </service>

        <service id="lug.grid.batch.type.delete" class="Lug\Bundle\GridBundle\Batch\Type\DeleteType">
            <argument type="service" id="lug.resource.registry.domain_manager" />
            <argument type="service" id="lug.resource.routing.parameter_resolver" />
            <tag name="lug.grid.batch" alias="delete" />
        </service>
    </services>
</container>


text:
from __future__ import absolute_import

from collections import defaultdict

from amqp.channel import Channel
from amqp.exceptions import NotConfirmed
from amqp.serialization import AMQPWriter, AMQPReader

from amqp.tests.case import Case, Mock

class NoOpenChannel(Channel):

    def _x_open(self):
        pass

class test_Channel(Case):

    def setUp(self):
        self.args = AMQPWriter()
        self.connection = Mock(name='connection')
        self.connection.channels = defaultdict(lambda: None)
        self.channel = NoOpenChannel(self.connection, channel_id=1)

    def test_basic_nack(self, delivery_tag=3172312312):
        self.args.write_longlong(delivery_tag)
        self.args.write_bit(0)
        self.args.write_bit(0)
        with self.assertRaises(NotConfirmed):
            self.channel._basic_nack(AMQPReader(self.args.getvalue()))
        callback = Mock(name='callback')
        self.channel.events['basic_nack'].add(callback)
        self.channel._basic_nack(AMQPReader(self.args.getvalue()))
        callback.assert_called_with(delivery_tag, False, False)


text:
 #######################################################################################################################
 #
 #  Copyright (c) 2022 Advanced Micro Devices, Inc. All Rights Reserved.
 #
 #  Permission is hereby granted, free of charge, to any person obtaining a copy
 #  of this software and associated documentation files (the "Software"), to deal
 #  in the Software without restriction, including without limitation the rights
 #  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 #  copies of the Software, and to permit persons to whom the Software is
 #  furnished to do so, subject to the following conditions:
 #
 #  The above copyright notice and this permission notice shall be included in all
 #  copies or substantial portions of the Software.
 #
 #  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 #  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 #  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 #  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 #  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 #  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 #  SOFTWARE.
 #
 #######################################################################################################################

include_guard()

set_target_properties(addrlib PROPERTIES
    CXX_STANDARD              11
    CXX_STANDARD_REQUIRED     ON
    CXX_EXTENSIONS            OFF
    POSITION_INDEPENDENT_CODE ON
)

if((CMAKE_CXX_COMPILER_ID MATCHES "GNU|[Cc]lang")
)
    if(ADDR_ENABLE_WERROR)
        target_compile_options(addrlib PRIVATE -Werror)
    endif()

    # [GCC] Exceptions
    #   https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_exceptions.html
    #
    # [GCC] Options Controlling C++ Dialect
    #   https://gcc.gnu.org/onlinedocs/gcc-8.1.0/gcc/C_002b_002b-Dialect-Options.html
    #
    # [GCC] Options That Control Optimization
    #   https://gcc.gnu.org/onlinedocs/gcc-8.1.0/gcc/Optimize-Options.html
    target_compile_options(addrlib PRIVATE
        -fno-strict-aliasing  # Disable optimizations that assume strict aliasing rules
        -fno-exceptions       # Disable exception handling support.
        -fno-rtti             # Disable run-time type information support.
        -fcheck-new           # Check if pointer returned by operator new is non-null.
        -fno-math-errno       # Single instruction math operations do not set ERRNO.
    )

    # [GCC] Options to Request or Suppress Warnings
    #   https://gcc.gnu.org/onlinedocs/gcc-8.1.0/gcc/Warning-Options.html
    target_compile_options(addrlib PRIVATE
        -Wall
        -Wextra
        -Wno-unused
        -Wno-unused-parameter
        -Wno-unused-command-line-argument
        -Wno-ignored-qualifiers
        -Wno-missing-field-initializers
        -Wno-self-assign
        -Wno-implicit-fallthrough
    )
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
    # Turns on static analysis only if addrlib is the top level project
    # This allows addrlib developers to fix the problem without impacting clients.
    if (ADDRLIB_IS_TOP_LEVEL)
        target_compile_options(addrlib PRIVATE /analyze)
    endif()

    target_compile_options(addrlib PRIVATE
        /EHsc # Catches only C++ exceptions and assumes
        # functions declared as extern "C" never throw a C++ exception.
        /GR-  # Disables run-time type information.
        /GS-  # Disables detection of buffer overruns.
    )

    target_compile_options(addrlib PRIVATE
        /W4      # Enable warning level 4.
        /WX      # Treat warnings as errors.
        /wd4018  # signed/unsigned mismatch
        /wd4065  # switch statement contains 'default' but no 'case' labels
        /wd4100  # unreferenced formal parameter
        /wd4127  # conditional expression is constant
        /wd4189  # local variable is initialized but not referenced
        /wd4201  # nonstandard extension used : nameless struct/union
        /wd4244  # conversion from 'type1' to 'type2', possible loss of data
        /wd4701  # potentially uninitialized local variable
        /wd6297  # arithmetic overflow: 32-bit value is shifted, then cast to 64-bit value
    )
else()
    message(FATAL_ERROR "addrlib: Compiler ${CMAKE_CXX_COMPILER_ID} is not supported!")
endif()


text:
angular.module('felt.menu.service', [])
// A RESTful factory for retrieving menu items from 'menu.json'

    .factory('Menus', ['$http', function ($http) {

        var path = 'assets/menu.json';
        var data = $http.get(path).then(function (resp) {
            return resp.data;
        });

        var req = $http.get(path);

        var factory = {};

        factory.getMenu = function () {
            return data;
        };

        factory.getReq = function () {
            return req;
        };

        return factory;

    }]);


text:
require "spec_helper"

app_require "fever_api/read_favicons"

describe FeverAPI::ReadFavicons do
  subject { FeverAPI::ReadFavicons.new }

  it "returns a fixed icon list if requested" do
    subject.call("favicons" => nil).should == {
      favicons: [
        {
          id: 0,
          data: "image/gif;base64,R0lGODlhAQABAIAAAObm5gAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="
        }
      ]
    }
  end

  it "returns an empty hash otherwise" do
    subject.call.should == {}
  end
end


text:
(function() {
'use strict';

    // Usage:
    //
    // Creates:
    //

    angular
        .module('app.login')
        .component('login', {
            templateUrl: 'src/client/app/login/login.component.html',
            controller: LoginController,
            controllerAs: 'vm',
            bindings: {}
        });

    LoginController.$inject = ['auth', 'validateService', 'datacontext', 'broadcast'];
    function LoginController(auth, validateService, datacontext, broadcast) {

        var vm = this;

        vm.validate = validateService;
        vm.auth = authenticate;

        ////////////////

        vm.$onInit = function() { };
        vm.$onChanges = function(changesObj) { };
        vm.$onDestory = function() { };

        function authenticate() {
            if (vm.validate.form(vm.loginForm)) {
                var data = {
                    username: vm.user.username,
                    pass: vm.user.pass,
                };
                auth
                    .auth(data)
                    .then(setUserLogged);
            }

            function setUserLogged() {
                datacontext.user.setLogged()
                    .then(success);

                function success() {
                    var user = datacontext.user.getUserLogged();
                    broadcast.userLogged();
                    return user;
                }
            }
        }
    }
})();


text:
package cn.fql.fishbone.model.domain;

import cn.fql.fishbone.model.domain.common.Base;

import java.util.List;

/**
 * Created by fuquanlin on 2016/5/23.
 */
public class Role extends Base{
    private String rolename;
    private List<Permission> permissions;

    public String getRolename() {
        return rolename;
    }

    public void setRolename(String rolename) {
        this.rolename = rolename;
    }

    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }
}


text:
package seed.repository;

import org.bson.types.ObjectId;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import seed.Application;
import seed.domain.ObjectiveList;

import static org.junit.Assert.*;

/**
 * Created by Macsnow on 2017/3/2.
 */

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@SpringBootConfiguration
public class ObjectiveListRepositoryTest {

    @Autowired
    private ObjectiveListRepository objectiveListRepository;

    private ObjectiveList objectiveList1;
    private ObjectiveList objectiveList2;
    private ObjectiveList objectiveList3;
    private Pageable pageable;
    private ObjectId id1;
    @Before
    public void setUp() {
        pageable = new PageRequest(0, 20);
        objectiveList1 = new ObjectiveList("tech");
        objectiveList2 = new ObjectiveList("health");
        objectiveList3 = new ObjectiveList("tech");
        objectiveList1.setDescription("objective for tech");
        objectiveList2.setDescription("objective for health");
        objectiveList3.setDescription("another objective for tech");
        id1 = objectiveListRepository.insert(objectiveList1).getId();
        objectiveListRepository.insert(objectiveList2);
        objectiveListRepository.insert(objectiveList3);
    }

    @Test
    public void read() {
        assertNotNull(objectiveListRepository.findById(id1));
        System.out.print(objectiveListRepository.findByTitleIgnoreCase("tech", pageable).size());
        assertTrue(objectiveListRepository.findByTitleIgnoreCase("tech", pageable).size() > 1);
        assertFalse(objectiveListRepository.findByTitleIgnoreCase("tech", pageable).get(0).getId() ==
                      objectiveListRepository.findByTitleIgnoreCase("tech", pageable).get(1).getId());
    }

    @Test
    public void update() {
        ObjectiveList objectiveList = objectiveListRepository.findById(id1).get();
        objectiveList.setTitle("life");
        objectiveListRepository.save(objectiveList);
        assertEquals("life", objectiveListRepository.findById(id1).get().getTitle());
    }

    @After
    public void tearDown() {
        objectiveListRepository.deleteAll();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.VisualStudioTools.Project;
using Task = System.Threading.Tasks.Task;

namespace Microsoft.VisualStudioTools {
    static class TaskExtensions {
        /// <summary>
        /// Suppresses warnings about unawaited tasks and ensures that unhandled
        /// errors will cause the process to terminate.
        /// </summary>
        public static async void DoNotWait(this Task task) {
            await task;
        }

        /// <summary>
        /// Waits for a task to complete. If an exception occurs, the exception
        /// will be raised without being wrapped in a
        /// <see cref="AggregateException"/>.
        /// </summary>
        public static void WaitAndUnwrapExceptions(this Task task) {
            task.GetAwaiter().GetResult();
        }

        /// <summary>
        /// Waits for a task to complete. If an exception occurs, the exception
        /// will be raised without being wrapped in a
        /// <see cref="AggregateException"/>.
        /// </summary>
        public static T WaitAndUnwrapExceptions<T>(this Task<T> task) {
            return task.GetAwaiter().GetResult();
        }

        /// <summary>
        /// Silently handles the specified exception.
        /// </summary>
        public static Task SilenceException<T>(this Task task) where T : Exception {
            return task.ContinueWith(t => {
                try {
                    t.Wait();
                } catch (AggregateException ex) {
                    ex.Handle(e => e is T);
                }
            });
        }

        /// <summary>
        /// Silently handles the specified exception.
        /// </summary>
        public static Task<U> SilenceException<T, U>(this Task<U> task) where T : Exception {
            return task.ContinueWith(t => {
                try {
                    return t.Result;
                } catch (AggregateException ex) {
                    ex.Handle(e => e is T);
                    return default(U);
                }
            });
        }
    }
}


text:
package com.getui.logful.sample;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.getui.logful.LoggerFactory;
import com.igexin.sdk.PushConsts;

public class GetuiPushReceiver extends BroadcastReceiver {

    private static final String TAG = "GetuiPushReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            case PushConsts.GET_MSG_DATA:
                byte[] payload = bundle.getByteArray("payload");
                if (payload != null) {
                    String data = new String(payload);
                    LoggerFactory.parseTransmission(data);
                }
                break;
            case PushConsts.GET_CLIENTID:
                String cid = bundle.getString("clientid");
                Log.v(TAG, "Getui sdk cid: " + cid);
                break;
            default:
                break;
        }
    }

}


text:
#include "bgp/bgp_show_handler.h"

#include "bgp/bgp_server.h"
#include "bgp/bgp_show_handler.h"
#include "bgp/routing-instance/routing_instance.h"
#include "bgp/routing-instance/route_aggregator.h"
#include "bgp/routing-instance/route_aggregate_types.h"

using std::string;
using std::vector;

static bool FillRouteAggregateInfo(Address::Family family,
                                const string search_string,
                                AggregateRouteEntriesInfo &info,
                                RoutingInstance *rtinstance) {
    const BgpTable *table =
        static_cast<const BgpTable *>(rtinstance->GetTable(family));
    if (!table)
        return false;
    if (!search_string.empty() &&
        (table->name().find(search_string) == string::npos) &&
        (search_string != "deleted" || !table->IsDeleted())) {
        return false;
    }

    IRouteAggregator *iroute_aggregator = rtinstance->route_aggregator(family);
    if (!iroute_aggregator)
        return false;
    return iroute_aggregator->FillAggregateRouteInfo(rtinstance, &info);
}

// Specialization of BgpShowHandler<>::CallbackCommon.
template <>
bool BgpShowHandler<ShowRouteAggregateReq, ShowRouteAggregateReqIterate,
    ShowRouteAggregateResp, AggregateRouteEntriesInfo>::CallbackCommon(
    const BgpSandeshContext *bsc, Data *data) {
    uint32_t page_limit = bsc->page_limit() ? bsc->page_limit() : kPageLimit;
    uint32_t iter_limit = bsc->iter_limit() ? bsc->iter_limit() : kIterLimit;
    RoutingInstanceMgr *rim = bsc->bgp_server->routing_instance_mgr();

    RoutingInstanceMgr::const_name_iterator it =
        rim->name_clower_bound(data->next_entry);
    for (uint32_t iter_count = 0; it != rim->name_cend(); ++it, ++iter_count) {
        RoutingInstance *rinstance = it->second;
        AggregateRouteEntriesInfo info;
        if (FillRouteAggregateInfo(Address::INET, data->search_string, info,
                                rinstance)) {
            data->show_list.push_back(info);
        }
        if (FillRouteAggregateInfo(Address::INET6, data->search_string, info,
                                rinstance)) {
            data->show_list.push_back(info);
        }

        if (data->show_list.size() >= page_limit)
            break;
        if (iter_count >= iter_limit)
            break;
    }

    // All done if we've looked at all instances.
    if (it == rim->name_cend() || ++it == rim->name_cend())
        return true;

    // Return true if we've reached the page limit, false if we've reached the
    // iteration limit.
    bool done = data->show_list.size() >= page_limit;
    SaveContextToData(it->second->name(), done, data);
    return done;
}

// Specialization of BgpShowHandler<>::FillShowList.
template <>
void BgpShowHandler<ShowRouteAggregateReq, ShowRouteAggregateReqIterate,
    ShowRouteAggregateResp, AggregateRouteEntriesInfo>::FillShowList(
        ShowRouteAggregateResp *resp,
        const vector<AggregateRouteEntriesInfo> &show_list) {
    resp->set_aggregate_route_entries(show_list);
}

// Handler for ShowRouteAggregateReq.
void ShowRouteAggregateReq::HandleRequest() const {
    RequestPipeline::PipeSpec ps(this);
    RequestPipeline::StageSpec s1;
    TaskScheduler *scheduler = TaskScheduler::GetInstance();

    s1.taskId_ = scheduler->GetTaskId("bgp::RouteAggregate");
    s1.cbFn_ = boost::bind(&BgpShowHandler<
        ShowRouteAggregateReq,
        ShowRouteAggregateReqIterate,
        ShowRouteAggregateResp,
        AggregateRouteEntriesInfo>::Callback, _1, _2, _3, _4, _5);
    s1.allocFn_ = BgpShowHandler<
        ShowRouteAggregateReq,
        ShowRouteAggregateReqIterate,
        ShowRouteAggregateResp,
        AggregateRouteEntriesInfo>::CreateData;
    s1.instances_.push_back(0);
    ps.stages_.push_back(s1);
    RequestPipeline rp(ps);
}

//
// Handler for ShowRouteAggregateReqIterate.
//
void ShowRouteAggregateReqIterate::HandleRequest() const {
    RequestPipeline::PipeSpec ps(this);
    RequestPipeline::StageSpec s1;
    TaskScheduler *scheduler = TaskScheduler::GetInstance();

    s1.taskId_ = scheduler->GetTaskId("bgp::RouteAggregate");
    s1.cbFn_ = boost::bind(&BgpShowHandler<
        ShowRouteAggregateReq,
        ShowRouteAggregateReqIterate,
        ShowRouteAggregateResp,
        AggregateRouteEntriesInfo>::CallbackIterate, _1, _2, _3, _4, _5);
    s1.allocFn_ = BgpShowHandler<
        ShowRouteAggregateReq,
        ShowRouteAggregateReqIterate,
        ShowRouteAggregateResp,
        AggregateRouteEntriesInfo>::CreateData;
    s1.instances_.push_back(0);
    ps.stages_.push_back(s1);
    RequestPipeline rp(ps);
}


text:
<?php

/**
 * TColorPicker class.
 *
 * TColorPicker displays a text box for color input purpose.
 * Next to the textbox there's a button filled with the current chosen color.
 * Users can write a color name directly in the text box as an hex triplet (also known as HTML notation, eg: #FF00FF).
 * Alternatively, if the ShowColorPicker property is enabled (it is by default), users can click the button
 * to have a color picker UI appear. A color chan be chosen directly by clicking on the color picker.
 *
 * TColorPicker has three different color picker UI Modes:
 *  # Simple - Grid with 12 simple colors.
 *  # Basic - Grid with the most common 70 colors. This is the default mode.
 *  # Full - Full-featured color picker.
 *
 * The CssClass property can be used to override the CSS class name
 * for the color picker panel. The ColorStyle property sets the packages
 * styles available. E.g. default.
 *
 * If the Mode property is set to Full, the color picker panel will
 * display an "Ok" and "Cancel" buttons. You can customize the button labels setting the OKButtonText
 * and CancelButtonText properties.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @version $Id: TColorPicker.php 2996 2011-06-20 15:24:57Z ctrlaltca@gmail.com $
 * @package System.Web.UI.WebControls
 * @since 3.0
 */
class TColorPicker extends TTextBox
{
	const SCRIPT_PATH = 'prado/colorpicker';

	private $_clientSide;

	/**
	 * @return boolean whether the color picker should pop up when the button is clicked.
	 */
	public function getShowColorPicker()
	{
		return $this->getViewState('ShowColorPicker',true);
	}

	/**
	 * Sets whether to pop up the color picker when the button is clicked.
	 * @param boolean whether to show the color picker popup
	 */
	public function setShowColorPicker($value)
	{
		$this->setViewState('ShowColorPicker',TPropertyValue::ensureBoolean($value),true);
	}

	/**
	 * @param TColorPickerMode color picker UI mode
	 */
	public function setMode($value)
	{
	   $this->setViewState('Mode', TPropertyValue::ensureEnum($value, 'TColorPickerMode'), TColorPickerMode::Basic);
	}

	/**
	 * @return TColorPickerMode current color picker UI mode. Defaults to TColorPickerMode::Basic.
	 */
	public function getMode()
	{
	   return $this->getViewState('Mode', TColorPickerMode::Basic);
	}

	/**
	 * @param string set the color picker style
	 */
	public function setColorPickerStyle($value)
	{
	   $this->setViewState('ColorStyle', $value, 'default');
	}

	/**
	 * @return string current color picker style
	 */
	public function getColorPickerStyle()
	{
	   return $this->getViewState('ColorStyle', 'default');
	}

	/**
	 * @return string text for the color picker OK button. Default is "OK".
	 */
	public function getOKButtonText()
	{
		return $this->getViewState('OKButtonText', 'OK');
	}

	/**
	 * @param string text for the color picker OK button
	 */
	public function setOKButtonText($value)
	{
		$this->setViewState('OKButtonText', $value, 'OK');
	}

	/**
	 * @return string text for the color picker Cancel button. Default is "Cancel".
	 */
	public function getCancelButtonText()
	{
		return $this->getViewState('CancelButtonText', 'Cancel');
	}

	/**
	 * @param string text for the color picker Cancel button
	 */
	public function setCancelButtonText($value)
	{
		$this->setViewState('CancelButtonText', $value, 'Cancel');
	}

	/**
	 * @return TColorPickerClientSide javascript event options.
	 */
	public function getClientSide()
	{
		if($this->_clientSide===null)
			$this->_clientSide = $this->createClientSide();
		return $this->_clientSide;
	}

	/**
	 * @return TColorPickerClientSide javascript validator event options.
	 */
	protected function createClientSide()
	{
		return new TColorPickerClientSide;
	}

	/**
	 * Get javascript color picker options.
	 * @return array color picker client-side options
	 */
	protected function getPostBackOptions()
	{
		$options = parent::getPostBackOptions();
		$options['ClassName'] = $this->getCssClass();
		$options['ShowColorPicker'] = $this->getShowColorPicker();
		if($options['ShowColorPicker'])
		{
			$mode = $this->getMode();
			if($mode == TColorPickerMode::Full) $options['Mode'] = $mode;
			else if($mode == TColorPickerMode::Simple) $options['Palette'] = 'Tiny';
			$options['OKButtonText'] = $this->getOKButtonText();
			$options['CancelButtonText'] = $this->getCancelButtonText();
		}
		$options = array_merge($options,$this->getClientSide()->getOptions()->toArray());
		return $options;
	}

	/**
	 * @param string asset file in the self::SCRIPT_PATH directory.
	 * @return string asset file url.
	 */
	protected function getAssetUrl($file='')
	{
		$base = $this->getPage()->getClientScript()->getPradoScriptAssetUrl();
		return $base.'/'.self::SCRIPT_PATH.'/'.$file;
	}

	/**
	 * Publish the color picker Css asset files.
	 */
	public function onPreRender($param)
	{
		parent::onPreRender($param);
		$this->publishColorPickerAssets();
	}

	/**
	 * Publish the color picker assets.
	 */
	protected function publishColorPickerAssets()
	{
		$cs = $this->getPage()->getClientScript();
		$key = "prado:".get_class($this);
		$imgs['button.gif'] = $this->getAssetUrl('button.gif');
		$imgs['background.png'] = $this->getAssetUrl('background.png');
		$options = TJavaScript::encode($imgs);
		$code = "Prado.WebUI.TColorPicker.UIImages = {$options};";
		$cs->registerEndScript($key, $code);
		$cs->registerPradoScript("colorpicker");
		$url = $this->getAssetUrl($this->getColorPickerStyle().'.css');
		if(!$cs->isStyleSheetFileRegistered($url))
			$cs->registerStyleSheetFile($url, $url);
	}

	/**
	 * Renders additional body content.
	 * This method overrides parent implementation by adding
	 * additional color picker button.
	 * @param THtmlWriter writer
	 */
	public function renderEndTag($writer)
	{
		parent::renderEndTag($writer);

		$color = $this->getText();
		$writer->addAttribute('class', 'TColorPicker_button');
		$writer->renderBeginTag('span');

		$writer->addAttribute('id', $this->getClientID().'_button');
		$writer->addAttribute('src', $this->getAssetUrl('button.gif'));
		if($color !== '')
			$writer->addAttribute('style', "background-color:{$color};");
		$writer->addAttribute('width', '20');
		$writer->addAttribute('height', '20');
		$writer->addAttribute('alt', '');
		$writer->renderBeginTag('img');
		$writer->renderEndTag();
		$writer->renderEndTag();
	}

	/**
	 * Gets the name of the javascript class responsible for performing postback for this control.
	 * This method overrides the parent implementation.
	 * @return string the javascript class name
	 */
	protected function getClientClassName()
	{
		return 'Prado.WebUI.TColorPicker';
	}
}

/**
 * TColorPickerMode class.
 * TColorPickerMode defines the enumerable type for the possible UI mode
 * that a {@link TColorPicker} control can take.
 *
 * The following enumerable values are defined:
 * # Simple - Grid with 12 simple colors.
 * # Basic - Grid with the most common 70 colors. This is the default mode.
 * # Full - Full-featured color picker.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @version $Id: TColorPicker.php 2996 2011-06-20 15:24:57Z ctrlaltca@gmail.com $
 * @package System.Web.UI.WebControls
 * @since 3.0.4
 */
class TColorPickerMode extends TEnumerable
{
	const Simple='Simple';
	const Basic='Basic';
	const Full='Full';
}

/**
 * TColorPickerClientSide class.
 *
 * Client-side javascript code options.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @version $Id: TColorPicker.php 2996 2011-06-20 15:24:57Z ctrlaltca@gmail.com $
 * @package System.Web.UI.WebControls
 * @since 3.1
 */
class TColorPickerClientSide extends TClientSideOptions
{
	/**
	 * @return string javascript code for when a color is selected.
	 */
	public function getOnColorSelected()
	{
		return $this->getOption('OnColorSelected');
	}

	/**
	 * @param string javascript code for when a color is selected.
	 */
	public function setOnColorSelected($javascript)
	{
		$this->setFunction('OnColorSelected', $javascript);
	}
}


text:
package net.digitalid.utility.conversion.exceptions;

import javax.annotation.Nonnull;

import net.digitalid.utility.annotations.method.Pure;
import net.digitalid.utility.validation.annotations.type.Immutable;

/**
 * The connection exception constitutes the upper bound of the converter's generic exception.
 */
@Immutable
public abstract class ConnectionException extends ConversionException {

    /* -------------------------------------------------- Message -------------------------------------------------- */

    @Pure
    @Override
    public @Nonnull String getMessage() {
        return "The conversion failed due to an interrupted connection or violated constraints.";
    }

    /* -------------------------------------------------- Cause -------------------------------------------------- */

    @Pure
    @Override
    public abstract @Nonnull Exception getCause();

}


text:
import NTPolySwig as nt

# MPI Module
from mpi4py import MPI
comm = MPI.COMM_WORLD

class TestOperation(nt.RealOperation):
    """
    This is the function we will map on to the matrix.
    """
    # Notice how you overload the call operator.
    def __call__(self):
        # This object contains a triplet called data for you to modify.
        if (self.data.index_row >= self.data.index_column):
            self.data.point_value *= 2
            return True
        return False

##########################################################################
if __name__ == "__main__":
    from sys import argv
    rank = comm.Get_rank()

    # Process The Input Parameters
    for i in range(1, len(argv), 2):
        argument = argv[i]
        argument_value = argv[i + 1]
        if argument == '--input_matrix':
            input_matrix = argument_value
        elif argument == '--output_matrix':
            output_matrix = argument_value
        elif argument == '--process_slices':
            process_slices = int(argument_value)

    # Setup the process grid.
    nt.ConstructGlobalProcessGrid(process_slices)
    if nt.GetGlobalIsRoot():
        nt.ActivateLogger()

    # Read in the matrices from file.
    Input = nt.Matrix_ps(input_matrix)
    Output = nt.Matrix_ps(Input.GetActualDimension())

    # Map
    op = TestOperation()
    nt.MatrixMapper.Map(Input, Output, op)

    # Print the density matrix to file.
    Output.WriteToMatrixMarket(output_matrix)

    # Cleanup
    if nt.GetGlobalIsRoot():
        nt.DeactivateLogger()
    nt.DestructGlobalProcessGrid()


text:
/* 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 org.activiti.engine.impl.bpmn.parser.handler;

import org.activiti.engine.impl.bpmn.behavior.WebServiceActivityBehavior;
import org.activiti.engine.impl.bpmn.parser.BpmnParse;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.constants.BpmnXMLConstants;
import org.flowable.bpmn.model.BaseElement;
import org.flowable.bpmn.model.ImplementationType;
import org.flowable.bpmn.model.SendTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Joram Barrez
 */
public class SendTaskParseHandler extends AbstractExternalInvocationBpmnParseHandler<SendTask> {

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

    @Override
    public Class<? extends BaseElement> getHandledType() {
        return SendTask.class;
    }

    @Override
    protected void executeParse(BpmnParse bpmnParse, SendTask sendTask) {

        ActivityImpl activity = createActivityOnCurrentScope(bpmnParse, sendTask, BpmnXMLConstants.ELEMENT_TASK_SEND);

        activity.setAsync(sendTask.isAsynchronous());
        activity.setExclusive(!sendTask.isNotExclusive());

        if (StringUtils.isNotEmpty(sendTask.getType())) {
            if ("mail".equalsIgnoreCase(sendTask.getType())) {
                activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createMailActivityBehavior(sendTask));
            } else if ("mule".equalsIgnoreCase(sendTask.getType())) {
                activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createMuleActivityBehavior(sendTask, bpmnParse.getBpmnModel()));
            } else if ("camel".equalsIgnoreCase(sendTask.getType())) {
                activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createCamelActivityBehavior(sendTask, bpmnParse.getBpmnModel()));
            }

            // for web service
        } else if (ImplementationType.IMPLEMENTATION_TYPE_WEBSERVICE.equalsIgnoreCase(sendTask.getImplementationType()) &&
                StringUtils.isNotEmpty(sendTask.getOperationRef())) {

            WebServiceActivityBehavior webServiceActivityBehavior = bpmnParse.getActivityBehaviorFactory().createWebServiceActivityBehavior(sendTask, bpmnParse.getBpmnModel());
            activity.setActivityBehavior(webServiceActivityBehavior);

        } else {
            LOGGER.warn("One of the attributes 'type' or 'operation' is mandatory on sendTask {}", sendTask.getId());
        }
    }

}


text:
import { ElementRef, Input, ContentChild, Component, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Header, Footer, SharedModule } from 'primeng/api';

var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
let Card = class Card {
    constructor(el) {
        this.el = el;
    }
    getBlockableElement() {
        return this.el.nativeElement.children[0];
    }
};
Card.ctorParameters = () => [
    { type: ElementRef }
];
__decorate([
    Input()
], Card.prototype, "header", void 0);
__decorate([
    Input()
], Card.prototype, "subheader", void 0);
__decorate([
    Input()
], Card.prototype, "style", void 0);
__decorate([
    Input()
], Card.prototype, "styleClass", void 0);
__decorate([
    ContentChild(Header)
], Card.prototype, "headerFacet", void 0);
__decorate([
    ContentChild(Footer)
], Card.prototype, "footerFacet", void 0);
Card = __decorate([
    Component({
        selector: 'p-card',
        template: `

               <ng-content select="p-header"></ng-content>

{{header}}

{{subheader}}

                    <ng-content></ng-content>

                    <ng-content select="p-footer"></ng-content>

    `
    })
], Card);
let CardModule = class CardModule {
};
CardModule = __decorate([
    NgModule({
        imports: [CommonModule],
        exports: [Card, SharedModule],
        declarations: [Card]
    })
], CardModule);

/**
 * Generated bundle index. Do not edit.
 */

export { Card, CardModule };
//# sourceMappingURL=primeng-card.js.map


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Carrotware.CMS.UI.Plugins.EventCalendarModule {

    public partial class EventCalendarDisplay {

        /// <summary>
        /// ddlMonth control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.DropDownList ddlMonth;

        /// <summary>
        /// ddlYear control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.DropDownList ddlYear;

        /// <summary>
        /// Calendar1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Carrotware.Web.UI.Controls.Calendar Calendar1;

        /// <summary>
        /// btnLast control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnLast;

        /// <summary>
        /// btnNext control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnNext;

        /// <summary>
        /// dgEvents control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.GridView dgEvents;

        /// <summary>
        /// rpCat control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Repeater rpCat;
    }
}


text:
#import <IDEKit/IDEInspectorProperty.h>

@class NSNumber;

@interface IDEInspectorEnumerationProperty : IDEInspectorProperty
{
    NSNumber *unusedEnumerationValue;
}

+ (Class)propertyClassForPropertyDefinition:(id)arg1;
- (void).cxx_destruct;
- (long long)unusedEnumerationValue;

@end


text:
var providers = [];

////////// External API //////////

Reload = {};

// Packages that support migration should register themselves by
// calling this function. When it's time to migrate, callback will
// be called with one argument, the "retry function." If the package
// is ready to migrate, it should return [true, data], where data is
// its migration data, an arbitrary JSON value (or [true] if it has
// no migration data this time). If the package needs more time
// before it is ready to migrate, it should return false. Then, once
// it is ready to migrating again, it should call the retry
// function. The retry function will return immediately, but will
// schedule the migration to be retried, meaning that every package
// will be polled once again for its migration data. If they are all
// ready this time, then the migration will happen. name must be set if there
// is migration data.
//
Reload._onMigrate = function (name, callback) {
  if (!callback) {
    // name not provided, so first arg is callback.
    callback = name;
    name = undefined;
  }
  providers.push({name: name, callback: callback});
};

// Called by packages when they start up.
// Returns the object that was saved, or undefined if none saved.
//
Reload._migrationData = function (name) {
  return undefined;
};

// Migrating reload: reload this page (presumably to pick up a new
// version of the code or assets), but save the program state and
// migrate it over. This function returns immediately. The reload
// will happen at some point in the future once all of the packages
// are ready to migrate.
//
var reloading = false;
Reload._reload = function () {
  if (reloading)
    return;
  reloading = true;

  Meteor._debug('reload requested');
};


text:
#ifndef ZEPHYR_INCLUDE_DEBUG_GDBSTUB_H_
#define ZEPHYR_INCLUDE_DEBUG_GDBSTUB_H_

/* Map from CPU excpetions to GDB  */
#define GDB_EXCEPTION_INVALID_INSTRUCTION   4UL
#define GDB_EXCEPTION_BREAKPOINT            5UL
#define GDB_EXCEPTION_MEMORY_FAULT          7UL
#define GDB_EXCEPTION_DIVIDE_ERROR          8UL
#define GDB_EXCEPTION_INVALID_MEMORY        11UL
#define GDB_EXCEPTION_OVERFLOW              16UL

#endif


text:
package org.sleuthkit.autopsy.commonfilesearch;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.Action;
import org.openide.nodes.Children;
import org.openide.nodes.Sheet;
import org.openide.util.lookup.Lookups;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeInstance;
import org.sleuthkit.autopsy.datamodel.DisplayableItemNode;
import org.sleuthkit.autopsy.datamodel.DisplayableItemNodeVisitor;
import org.sleuthkit.autopsy.datamodel.NodeProperty;

/**
 * Used by the Common Files search feature to encapsulate instances of a given
 * MD5s matched in the search.  These nodes will be children of Md5Nodes.
 *
 * Use this type for files which are not in the current case, but from the
 * Central Repo.  Contrast with SleuthkitCase which should be used
 * when the FileInstance was found in the case presently open in Autopsy.
 */
public class CentralRepoCommonAttributeInstanceNode extends DisplayableItemNode {

    private final CorrelationAttributeInstance crFile;

    CentralRepoCommonAttributeInstanceNode(CorrelationAttributeInstance content) {
        super(Children.LEAF, Lookups.fixed(content));
        this.crFile = content;
        this.setDisplayName(new File(this.crFile.getFilePath()).getName());
    }

    public CorrelationAttributeInstance getCorrelationAttributeInstance(){
        return this.crFile;
    }

    @Override
    public Action[] getActions(boolean context){
        List<Action> actionsList = new ArrayList<>();

        actionsList.addAll(Arrays.asList(super.getActions(true)));

        return actionsList.toArray(new Action[actionsList.size()]);
    }

    @Override
    public <T> T accept(DisplayableItemNodeVisitor<T> visitor) {
        return visitor.visit(this);
    }

    @Override
    public boolean isLeafTypeNode() {
        return true;
    }

    @Override
    public String getItemType() {
        //objects of type FileNode will co-occur in the treetable with objects
        //  of this type and they will need to provide the same key
        return CaseDBCommonAttributeInstanceNode.class.getName();
    }

    @Override
    protected Sheet createSheet(){
        Sheet sheet = new Sheet();
        Sheet.Set sheetSet = sheet.get(Sheet.PROPERTIES);

        if(sheetSet == null){
            sheetSet = Sheet.createPropertiesSet();
            sheet.put(sheetSet);
        }

        final CorrelationAttributeInstance centralRepoFile = this.getCorrelationAttributeInstance();

        final String fullPath = centralRepoFile.getFilePath();
        final File file = new File(fullPath);

        final String caseName = centralRepoFile.getCorrelationCase().getDisplayName();

        final String name = file.getName();
        final String parent = file.getParent();

        final String dataSourceName = centralRepoFile.getCorrelationDataSource().getName();

        final String NO_DESCR = Bundle.CommonFilesSearchResultsViewerTable_noDescText();

        sheetSet.put(new NodeProperty<>(org.sleuthkit.autopsy.commonfilesearch.Bundle.CommonFilesSearchResultsViewerTable_filesColLbl(), org.sleuthkit.autopsy.commonfilesearch.Bundle.CommonFilesSearchResultsViewerTable_filesColLbl(), NO_DESCR, name));
        sheetSet.put(new NodeProperty<>(org.sleuthkit.autopsy.commonfilesearch.Bundle.CommonFilesSearchResultsViewerTable_pathColLbl(), org.sleuthkit.autopsy.commonfilesearch.Bundle.CommonFilesSearchResultsViewerTable_pathColLbl(), NO_DESCR, parent));
        sheetSet.put(new NodeProperty<>(org.sleuthkit.autopsy.commonfilesearch.Bundle.CommonFilesSearchResultsViewerTable_hashsetHitsColLbl(), org.sleuthkit.autopsy.commonfilesearch.Bundle.CommonFilesSearchResultsViewerTable_hashsetHitsColLbl(), NO_DESCR, ""));
        sheetSet.put(new NodeProperty<>(org.sleuthkit.autopsy.commonfilesearch.Bundle.CommonFilesSearchResultsViewerTable_dataSourceColLbl(), org.sleuthkit.autopsy.commonfilesearch.Bundle.CommonFilesSearchResultsViewerTable_dataSourceColLbl(), NO_DESCR, dataSourceName));
        sheetSet.put(new NodeProperty<>(org.sleuthkit.autopsy.commonfilesearch.Bundle.CommonFilesSearchResultsViewerTable_mimeTypeColLbl(), org.sleuthkit.autopsy.commonfilesearch.Bundle.CommonFilesSearchResultsViewerTable_mimeTypeColLbl(), NO_DESCR, ""));
        sheetSet.put(new NodeProperty<>(org.sleuthkit.autopsy.commonfilesearch.Bundle.CommonFilesSearchResultsViewerTable_caseColLbl1(), org.sleuthkit.autopsy.commonfilesearch.Bundle.CommonFilesSearchResultsViewerTable_caseColLbl1(), NO_DESCR, caseName));

        return sheet;
    }
}


text:
namespace TowerDefense.Main.Towers.Projectiles
{
    using System.Windows.Media.Imaging;
    using TowerDefense.Interfaces;
    using TowerDefense.Utils;

    public class SlowTowerProjectile : Projectile
    {
        public override BitmapSource BitmapSource
        {
            get
            {
                return ImageFactory.CreateImage("ball1.png");
            }
        }

        public override int Speed
        {
            get
            {
                return 400;
            }
        }

        public override int Damage
        {
            get
            {
                return 150;
            }
        }

        public SlowTowerProjectile(Point center, ITarget target)
            : base(center, target)
        {
        }
    }
}


text:
from logger import Logger

from .reader import XMLDeviceReader
from .identifiers import Identifiers

class Device:
	""" Device
	Represents a device.
	"""

	def __init__(self, description_file=None, logger=None):
		if logger == None:
			self.log = Logger()
		else:
			self.log = logger

		self.ids = None
		self.properties = []
		if description_file == None:
			self.ids = Identifiers(None, self.log)
			return

		# proper handling of Parsers
		if isinstance(description_file, XMLDeviceReader):
			self.properties = list(description_file.properties)
			self.log = description_file.log
			self.ids = Identifiers(description_file.id, self.log)
		else:
			self.properties = list(description_file)

		if self.ids == None:
			self.ids = Identifiers(None, self.log)

		# if flash or ram is missing, it is a bad thing and unsupported
		if self.getProperty('flash') == None:
			self.log.error("No FLASH found")
			return None
		if self.getProperty('ram') == None:
			self.log.error("No RAM found")
			self.log.error("XPCC does not support Assembler-only programming!")
			return None
		# eeprom is optional on AVR and not available on ARM devices
		if (self.getProperty('eeprom') == None) and ('avr' == self.id.platform):
			self.log.warn("No EEPROM found")

	def getMergedDevice(self, other):
		"""
		Merges the values of both devices and add a dictionary of differences
		"""
		assert isinstance(other, Device)
		self.log.info("Merging '%s'  with  '%s'" % (self.ids.string, other.ids.string))

		# update the ids in both
		self.ids.extend(other.ids)

		# go through all properties and merge each one
		for self_property in self.properties:
			for other_property in other.properties:
				if self_property.name == other_property.name:
					self_property = self_property.getMergedProperty(other_property)

		self.properties.sort(key=lambda k : k.name)

		return self;

	@property
	def id(self):
		return self.ids.intersection

	def getProperty(self, name):
		for prop in self.properties:
			if prop.name == name:
				return prop

		return None

	def __repr__(self):
		return self.__str__()

	def __str__(self):
		return ("Device(\t%s,\n\n%s )\n" % (self.ids.string, \
			",\n\n".join([str(p) for p in self.properties]))) \
			.replace("\n", "\n\t")


text:
local Fl = require "facil"

-- @return true on success
--         nil, error:string otherwise
local function show(id)
    return Fl.show(id)
end

--- Returns detailed description (string) help for status command.
local function help()
        return [[
fl show TASK

Shows content of the TASK.
]]
end

return {
    handler = show,
    help = help
}


text:
package io.really.protocol

import _root_.io.really.Result._
import akka.actor.ActorRef
import io.really._
import _root_.io.really.rql.RQL
import play.api.data.validation.ValidationError
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.libs.json.Writes._

/*
 * JSON Formats for Really Protocol
 */

object ProtocolFormats {
  private val Body = "body"
  private val Tag = "tag"
  private val R = "r"
  private val Revision = "rev"
  private val Meta = "meta"
  private val Fields = "fields"
  private val Event = "evt"
  private val OpBy = "opBy"

  /*
   * JSON Reads for Request
   */
  object RequestReads {
    val tagReads = (__ \ 'tag).read[Long]
    val traceIdReads = (__ \ 'traceId).readNullable[String]
    val cmdReads = (__ \ 'cmd).read[String].map(_.toLowerCase)
    val accessTokenReads = (__ \ 'accessToken).read[String]
    val rReads = (__ \ 'r).read[R]
    val rObjectReads = rReads.filter(ValidationError("validate.error.require.object"))(_.isObject)
    val rCollectionReads = rReads.filter(ValidationError("validate.error.require.collection"))(_.isCollection)
    val revReads = (__ \ 'rev).read[Long]

    /*
     * JSON Reads for [[io.really.Request.Subscribe]] Request
     */
    object Subscribe {
      val bodyReads = (__ \ 'body).read[SubscriptionBody]

      def read(ctx: RequestContext, replyTo: ActorRef) = (bodyReads) map (body => Request.SubscribeOnObjects(ctx, body, replyTo))
    }

    /*
     * JSON Reads for [[io.really.Request.Unsubscribe]] Request
     */
    object Unsubscribe {
      val bodyReads = (__ \ 'body).read[UnsubscriptionBody]

      def read(ctx: RequestContext, replyTo: ActorRef) = (bodyReads) map (body => Request.UnsubscribeFromObjects(ctx, body, replyTo))
    }

    /*
     * JSON Reads for [[io.really.Request.Get]] Request
     */
    object Get {
      val cmdOptsReads = (__ \ 'cmdOpts).readNullable[GetOpts].defaultsTo(GetOpts())
      def read(ctx: RequestContext, replyTo: ActorRef) = (rObjectReads and cmdOptsReads)((r, cmdOpts) => Request.Get(ctx, r, cmdOpts))
    }

    /*
     * JSON Reads for [[io.really.Request.Update]] Request
     */
    object Update {
      val bodyReads = (__ \ 'body).read[UpdateBody]

      def read(ctx: RequestContext, replyTo: ActorRef) =
        (rObjectReads and revReads and bodyReads)((r, rev, body) => Request.Update(ctx, r, rev, body))
    }

    /**
     * JSON Reads for [[_root_.io.really.Request.Read]] Request
     */
    object Read {
      val cmdOptsReads = (__ \ 'cmdOpts).readNullable[ReadOpts].defaultsTo(ReadOpts(Set.empty, RQL.EmptyQuery, DEFAULT_QUERY_LIMIT)) //todo: d
      def read(ctx: RequestContext, replyTo: ActorRef) = (rCollectionReads and cmdOptsReads)((r, cmdOpts) => Request.Read(ctx, r, cmdOpts, replyTo))
    }

    /*
     * JSON Reads for [[io.really.Request.Create]] Request
     */
    object Create {
      val bodyReads = (__ \ 'body).read[JsObject]

      def read(ctx: RequestContext, replyTo: ActorRef) =
        (rCollectionReads and bodyReads)((r, body) => Request.Create(ctx, r, body))
    }

    /*
     * JSON Reads for [[io.really.Request.Delete]] Request
     */
    object Delete {
      def read(ctx: RequestContext, replyTo: ActorRef) = (rObjectReads) map (r => Request.Delete(ctx, r))
    }

    def apply(cmd: String) = scala.util.Try(cmd match {
      case "create" => Create.read _
      case "get" => Get.read _
      case "read" => Read.read _
      case "update" => Update.read _
      case "subscribe" => Subscribe.read _
      case "unsubscribe" => Unsubscribe.read _
      case "delete" => Delete.read _
    })

  }

  /*
   * Represent JSON Writes for Responses
   */
  object ResponseWrites {

    /*
     * Represent JSON Writes for Subscribe Response
     */
    implicit val subscribeResultWrites = new Writes[SubscribeResult] {
      def writes(r: SubscribeResult): JsValue =
        Json.obj(Body -> Json.obj("subscriptions" -> r.subscriptions))
    }

    /*
    * Represent JSON Writes for Unsubscribe Response
    */
    implicit val unsubscribeResultWrites = new Writes[UnsubscribeResult] {
      def writes(r: UnsubscribeResult): JsValue =
        Json.obj(Body -> Json.obj("unsubscriptions" -> r.unsubscriptions))
    }

    /*
     * Represent JSON Writes for [[io.really.Response.Get]] Response
     */
    implicit val getResultWrites = (
      (__ \ R).write[R] and
      (__ \ Body).write[JsObject] and
      (__ \ Meta \ Fields).write[Set[String]]
    )(unlift(GetResult.unapply))

    /*
     * Represent JSON Writes for [[io.really.Response.Update]] Response
     */
    implicit val updateResultWrites = (
      (__ \ R).write[R] and
      (__ \ Revision).write[Revision]
    )(unlift(UpdateResult.unapply))

    /*
     * Represent JSON Writes for [[io.really.Response.Read]] Response
     */
    implicit val readResultWrites = (
      (__ \ R).write[R] and
      (__ \ Body).write[ReadResponseBody] and
      (__ \ Meta \ "subscription").writeNullable[String]
    )(unlift(ReadResult.unapply))

    /*
     * Represent JSON Writes for [[io.really.Response.Create]] Response
     */
    implicit val createResultWrites = (
      (__ \ R).write[R] and
      (__ \ Body).write[JsObject]
    )(unlift(CreateResult.unapply))

    /*
     * Represent JSON Writes for [[io.really.Response.Delete]] Response
     */
    implicit val deleteWrites = new Writes[DeleteResult] {
      def writes(result: DeleteResult): JsValue =
        Json.obj(R -> result.r)
    }

    /*
     * Represent JSON Writes for [[io.really.Response]]
     * may generate different schema, depending on the concrete type
     */
    implicit val resultWrites = new Writes[Result] {
      def writes(r: Result): JsValue = r match {
        case response: SubscribeResult =>
          Json.toJson(response)
        case response: UnsubscribeResult =>
          Json.toJson(response)
        case response: GetResult =>
          Json.toJson(response)
        case response: UpdateResult =>
          Json.toJson(response)
        case response: ReadResult =>
          Json.toJson(response)
        case response: CreateResult =>
          Json.toJson(response)
        case response: DeleteResult =>
          Json.toJson(response)
      }
    }
  }

  /*
   * Represent JSON Writes for CommandErrors
   */
  object CommandErrorWrites {
    implicit val commandErrorWrites = (
      (__ \ "r").writeNullable[R] and
      (__ \ "error").write[ProtocolError.Error]
    )(unlift(CommandError.unapply))
  }

  /*
   * Represent JSON Writes for Push Messages
   */
  object PushMessageWrites {

    /*
     * Represent Created Push Message
     */
    object Created {
      def toJson(r: R, createdObj: JsObject) =
        Json.obj(
          R -> r,
          Event -> "created",
          Body -> createdObj
        )
    }

    /*
     * Represent Deleted Push Message
     */
    object Deleted {
      def toJson(r: R, userInfo: UserInfo) =
        Json.obj(
          R -> r,
          Event -> "deleted",
          Meta -> Json.obj(
            OpBy -> userInfo
          )
        )
    }

    /*
     * Represent Updated Push Message
     */
    object Updated {
      def toJson(r: R, rev: Revision, ops: List[FieldUpdatedOp], userInfo: UserInfo) =
        Json.obj(
          R -> r,
          Revision -> rev,
          Event -> "updated",
          Body -> Json.toJson(ops)(FieldUpdatedOp.FieldUpdatedOpListWrites),
          Meta -> Json.obj(
            OpBy -> userInfo
          )
        )
    }

  }

}


text:
<?php

declare(strict_types=1);

namespace Sphp\Tests\Validators;

use PHPUnit\Framework\TestCase;
use Sphp\Validators\StringLength;
use Sphp\Exceptions\InvalidArgumentException;

class StringLengthTest extends TestCase {

  public function testRangeValidation(): void {
    $validator = new StringLength(0, 2);
    $this->assertTrue($validator->isRangeValidator());
    $this->assertFalse($validator->isLowerBoundValidator());
    $this->assertFalse($validator->isValid('foobar'));
    $this->assertTrue($validator->isValid(''));
    $this->assertTrue($validator->isValid(' a'));
    $validator->setRangeValidation(1, 1);
    $this->assertTrue($validator->isValid('a'));
    $this->assertFalse($validator->isValid('ab'));
    $this->assertFalse($validator->isValid(2));
  }

  /**
   * @return StringLength
   */
  public function testLowerBoundValidation(): void {
    //$this->assertSame($validator, $validator->setLowerBoundValidation(2));

    $validator = new StringLength(2, null);
    $this->assertTrue($validator->isLowerBoundValidator());
    $this->assertFalse($validator->isRangeValidator());
    $this->assertFalse($validator->isValid(''));
    $this->assertTrue($validator->isValid('  '));
    $this->assertTrue($validator->isValid('     '));
  }

  public function testUpperBoundValidation() {
    $validator = new StringLength(null, 5);
    $this->assertSame($validator, $validator->setUpperBoundValidation(5));
    $this->assertTrue($validator->isUpperBoundValidator());
    $this->assertFalse($validator->isLowerBoundValidator());
    $this->assertFalse($validator->isRangeValidator());
    $this->assertTrue($validator->isValid(''));
    $this->assertFalse($validator->isValid('foobar'));
    $this->expectException(InvalidArgumentException::class);
    $validator->setUpperBoundValidation(-1);
  }

  public function testInvalidConstructor() {
    $this->expectException(InvalidArgumentException::class);
    new StringLength(-1, 5);
  }

  public function testEmptyConstructor() {
    $this->expectException(InvalidArgumentException::class);
    new StringLength();
  }

  public function testInvalidRangeSet() {
    $this->expectException(InvalidArgumentException::class);
    (new StringLength(1, 2))->setRangeValidation(1, 0);
  }

}


text:
Module::Module()
    : mName("")
{

}

std::string Module::getName() const
{
    return mName;
}

void Module::setName(const std::string& name)
{
    mName = name;
}


text:
/*
 * DO NOT EDIT THIS FILE! Automatically generated
 */

#include "base/debug.hh"

namespace Debug {

SimpleFlag Quiesce("Quiesce", "None");

} // namespace Debug


text:
<?php

/**
 * FirefoxOSUserAgentHandler
 *
 *
 * @category   WURFL
 * @package	WURFL_Handlers
 * @copyright  ScientiaMobile, Inc.
 * @license	GNU Affero General Public License
 * @version	$id$
 */
class WURFL_Handlers_FirefoxOSHandler extends WURFL_Handlers_Handler {

	protected $prefix = "FIREFOXOS";

	public static $constantIDs = array(
		'generic_firefox_os',
		'firefox_os_ver1',
		'firefox_os_ver1_1',
		'firefox_os_ver1_2',
		'firefox_os_ver1_3',
		'firefox_os_ver1_3_tablet',
        'firefox_os_ver1_4',
        'firefox_os_ver1_4_tablet',
        'firefox_os_ver2_0',
        'firefox_os_ver2_0_tablet',
        'firefox_os_ver2_1',
        'firefox_os_ver2_1_tablet',
        'firefox_os_ver2_2',
        'firefox_os_ver2_2_tablet',
	);

	public static $firefoxOSMap = array(
		'18.0' => '1.0',
		'18.1' => '1.1',
		'26.0' => '1.2',
		'28.0' => '1.3',
        '30.0' => '1.4',
        '32.0' => '2.0',
        '33.0' => '2.1',
        '34.0' => '2.1',
        '37.0' => '2.2',
	);

	public function canHandle($userAgent) {
		return (WURFL_Handlers_Utils::checkIfContains($userAgent, 'Firefox/') && WURFL_Handlers_Utils::checkIfContainsAnyOf($userAgent, array('Mobile', 'Tablet')));
	}

	public function applyConclusiveMatch($userAgent) {

		// Mozilla/5.0 (Mobile; rv:18.0) Gecko/18.0 Firefox/18.0
		// Mozilla/5.0 (Mobile; ZTEOPEN; rv:18.1) Gecko/18.1 Firefox/18.1
		// Mozilla/5.0 (Tablet; rv:26.0) Gecko/26.0 Firefox/26.0
		if (preg_match('#\brv:\d+\.\d+(.)#', $userAgent, $matches, PREG_OFFSET_CAPTURE)) {
			$tolerance = $matches[1][1] + 1;
			return $this->getDeviceIDFromRIS($userAgent, $tolerance);
		}
		return WURFL_Constants::NO_MATCH;
	}

	public function applyRecoveryMatch($userAgent) {

		$version_string = str_replace('.', '_', self::getFirefoxOSVersion($userAgent));

		// Replace X_0 to X because the WURFL IDs are of the type "firefox_os_verX" and not "firefox_os_verX_0"
		$version_string = str_replace('_0', '', $version_string);

		// Calculate WURFL ID
		$deviceID = 'firefox_os_ver'.$version_string;

		// Tablet specific recovery logic
		if (strpos($userAgent, 'Tablet') !== false) {
			if (in_array($deviceID.'_tablet', self::$constantIDs)) {
				return $deviceID.'_tablet';
			}
			return 'firefox_os_ver1_3_tablet';

		}

		if (in_array($deviceID, self::$constantIDs)) {
			return $deviceID;
		}

		return 'generic_firefox_os';
	}

	// Function to extract Firefox OS version from Gecko/Firefox Browser version in the User-Agent
	public static function getFirefoxOSVersion($ua) {

		// Find Firefox Browser/Gecko version
		if (preg_match('#\brv:(\d+\.\d+)#', $ua, $matches) && array_key_exists($matches[1], self::$firefoxOSMap)) {
			return self::$firefoxOSMap[$matches[1]];
		}
		// Set appropriate default values if not in OS mapping
		if (strpos($ua, 'Tablet') !== false) {
			// Firefox OS 1.3 is the lowest version of Firefox OS to have a tablet WURFL ID
			return "1.3";
		}

		return "1.0";

	}
}


text:
package net.openhft.chronicle.hash.serialization.impl;

import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.hash.serialization.BytesReader;
import net.openhft.chronicle.hash.serialization.ListMarshaller;
import net.openhft.chronicle.hash.serialization.SetMarshaller;
import net.openhft.chronicle.hash.serialization.StatefulCopyable;
import net.openhft.chronicle.wire.WireIn;
import net.openhft.chronicle.wire.WireOut;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * {@link BytesReader} implementation for String, for the primary ChronicleMap's key or value type
 * {@link StringSizedReader} + {@link StringUtf8DataAccess} are more efficient (because don't
 * store the size twice), so this reader is useful in conjunction with {@link ListMarshaller} or
 * {@link SetMarshaller}.
 *
 * @see CharSequenceBytesWriter
 */
public class StringBytesReader implements BytesReader<String>, StatefulCopyable<StringBytesReader> {

    /**
     * Cache field
     */
    private transient StringBuilder sb;

    public StringBytesReader() {
        initTransients();
    }

    private void initTransients() {
        sb = new StringBuilder();
    }

    @NotNull
    @Override
    public String read(Bytes in, @Nullable String using) {
        if (in.readUtf8(sb)) {
            return sb.toString();
        } else {
            throw new NullPointerException("BytesReader couldn't read null");
        }
    }

    @Override
    public StringBytesReader copy() {
        return new StringBytesReader();
    }

    @Override
    public void readMarshallable(@NotNull WireIn wireIn) {
        // no fields to read
        initTransients();
    }

    @Override
    public void writeMarshallable(@NotNull WireOut wireOut) {
        // no fields to write
    }
}


text:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by nate on 4/10/16.
 */
public abstract class Model {
    protected static final Connection c = connect();

    public Model() {
    }

    private static Connection connect() {
        try {
            return DriverManager.getConnection("jdbc:sqlite:data.db");
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}