text:
package org.apache.felix.ipojo.test.composite.provides;

import java.util.Properties;

import org.apache.felix.ipojo.ComponentFactory;
import org.apache.felix.ipojo.ComponentInstance;
import org.apache.felix.ipojo.Factory;
import org.apache.felix.ipojo.architecture.Architecture;
import org.apache.felix.ipojo.junit4osgi.OSGiTestCase;
import org.apache.felix.ipojo.test.composite.component.TotoProvider;
import org.apache.felix.ipojo.test.composite.component.TotoProviderGlue;
import org.apache.felix.ipojo.test.composite.service.Tota;
import org.apache.felix.ipojo.test.composite.util.Utils;
import org.osgi.framework.ServiceReference;

public class TestComp8 extends OSGiTestCase {

    private ComponentFactory tataFactory;
    private ComponentFactory totoFactory;
    private ComponentFactory tataFactory2;

    private ComponentInstance totoProv, totoProv2;
    private ComponentInstance under;

    public void setUp() {
        tataFactory = (ComponentFactory) Utils.getFactoryByName(getContext(), "tata");
        totoFactory = (ComponentFactory) Utils.getFactoryByName(getContext(), "toto");
        tataFactory2 = (ComponentFactory) Utils.getFactoryByName(getContext(), "comp-6");
        tataFactory2.stop();

        Properties props = new Properties();
        props.put("instance.name","toto provider");
        try {
            totoProv = totoFactory.createComponentInstance(props);
        } catch(Exception e) {
            e.printStackTrace();
        }

        Properties props3 = new Properties();
        props3.put("instance.name","toto provider 2");
        try {
            totoProv2 = totoFactory.createComponentInstance(props3);
        } catch(Exception e) {
            e.printStackTrace();
        }

        totoProv.stop();
        totoProv2.stop();

        Factory factory = Utils.getFactoryByName(getContext(), "comp-8");
        Properties props2 = new Properties();
        props2.put("instance.name","ff");
        try {
            under = factory.createComponentInstance(props2);
        } catch(Exception e) {
            e.printStackTrace();
        }
        tataFactory.stop();

    }

    public void tearDown() {
        tataFactory.start();
        totoProv.dispose();
        totoProv = null;
        totoProv2.dispose();
        totoProv2 = null;
        tataFactory2.start();

        // Reset counters
        TotoProvider.toto = 0;
        TotoProvider.toto_2 = 0;
        TotoProvider.toto_3 = 0;
        TotoProvider.toto_4 = 0;
        TotoProvider.toto1 = 0;
        TotoProviderGlue.toto = 0;
        TotoProviderGlue.toto_2 = 0;
        TotoProviderGlue.toto_3 = 0;
        TotoProviderGlue.toto_4 = 0;
        TotoProviderGlue.toto1 = 0;
    }

    public void testSimple() {
        // Neither factory nor instance
        assertTrue("Assert under state - 1", under.getState() == ComponentInstance.INVALID);
        assertNull("Assert no tota service - 1", getContext().getServiceReference(Tota.class.getName()));

        // Start the importer
        totoProv.start();
        assertTrue("Assert under state - 2", under.getState() == ComponentInstance.INVALID);
        assertNull("Assert no tota service - 2", getContext().getServiceReference(Tota.class.getName()));

        // Start the factory
        tataFactory.start();
        assertTrue("Assert under state - 3", under.getState() == ComponentInstance.VALID);
        assertNotNull("Assert tota service - 3", getContext().getServiceReference(Tota.class.getName()));
        ServiceReference ref = getContext().getServiceReference(Tota.class.getName());
        Tota tota = (Tota) getContext().getService(ref);
        invokeAll(tota);
        // Check toto
        Properties props = tota.getProps();
        Integer toto = (Integer) props.get("toto");
        Integer toto_2 = (Integer) props.get("toto_2");
        Integer toto_3 = (Integer) props.get("toto_3");
        Integer toto_4 = (Integer) props.get("toto_4");
        Integer gtoto = (Integer) props.get("gtoto");
        Integer gtoto_2 = (Integer) props.get("gtoto_2");
        Integer gtoto_3 = (Integer) props.get("gtoto_3");
        Integer gtoto_4 = (Integer) props.get("gtoto_4");
        assertEquals("Assert toto - 3 ("+toto.intValue()+")", toto.intValue(), 1);
        assertEquals("Assert toto_2 - 3", toto_2.intValue(), 1);
        assertEquals("Assert toto_3 - 3", toto_3.intValue(), 0);
        assertEquals("Assert toto_4 - 3", toto_4.intValue(), 0);
        assertEquals("Assert gtoto - 3 ("+gtoto.intValue()+")", gtoto.intValue(), 1);
        assertEquals("Assert gtoto_2 - 3", gtoto_2.intValue(), 1);
        assertEquals("Assert gtoto_3 - 3", gtoto_3.intValue(), 1);
        assertEquals("Assert gtoto_4 - 3", gtoto_4.intValue(), 0);
        //Check tata
        props = tota.getPropsTata();
        Integer tata = (Integer) props.get("tata");
        Integer tataStr = (Integer) props.get("tataStr");
        Integer tataStrs = (Integer) props.get("tataStrs");
        Integer tata_2 = (Integer) props.get("tata_2");
        Integer tata_3 = (Integer) props.get("tata_3");
        Integer tata1 = (Integer) props.get("tata1");
        Integer tata1_1 = (Integer) props.get("tata1_1");
        Integer tata5 = (Integer) props.get("tata5");
        Integer tata5_1 = (Integer) props.get("tata5_1");
        Integer tata5_2 = (Integer) props.get("tata5_2");
        assertEquals("Assert tata - 3", tata.intValue(), 1);
        assertEquals("Assert tataStr - 3", tataStr.intValue(), 1);
        assertEquals("Assert tataStrs - 3", tataStrs.intValue(), 0);
        assertEquals("Assert tata_2 - 3", tata_2.intValue(), 1);
        assertEquals("Assert tata_3 - 3", tata_3.intValue(), 1);
        assertEquals("Assert tata1 - 3", tata1.intValue(), 1);
        assertEquals("Assert tata1_1 - 3", tata1_1.intValue(), 1);
        assertEquals("Assert tata5 - 3", tata5.intValue(), 1);
        assertEquals("Assert tata5_1 - 3", tata5_1.intValue(), 1);
        assertEquals("Assert tata5_2 - 3", tata5_2.intValue(), 1);
        getContext().ungetService(ref);
        tota = null;

        // Start a second import
        totoProv2.start();
        assertTrue("Assert under state - 4", under.getState() == ComponentInstance.VALID);
        assertNotNull("Assert tota service - 4", getContext().getServiceReference(Tota.class.getName()));
        ref = getContext().getServiceReference(Tota.class.getName());
        tota = (Tota) getContext().getService(ref);
        invokeAll(tota);
        // Check toto
        props = tota.getProps();
        toto = (Integer) props.get("toto");
        toto_2 = (Integer) props.get("toto_2");
        toto_3 = (Integer) props.get("toto_3");
        toto_4 = (Integer) props.get("toto_4");
        gtoto = (Integer) props.get("gtoto");
        gtoto_2 = (Integer) props.get("gtoto_2");
        gtoto_3 = (Integer) props.get("gtoto_3");
        gtoto_4 = (Integer) props.get("gtoto_4");
        assertEquals("Assert toto - 4", toto.intValue(), 2);
        assertEquals("Assert toto_2 - 4", toto_2.intValue(), 2);
        assertEquals("Assert toto_3 - 4", toto_3.intValue(), 0);
        assertEquals("Assert toto_4 - 4", toto_4.intValue(), 0);
        assertEquals("Assert gtoto - 4 ("+gtoto.intValue()+")", gtoto.intValue(), 2);
        assertEquals("Assert gtoto_2 - 4", gtoto_2.intValue(), 2);
        assertEquals("Assert gtoto_3 - 4", gtoto_3.intValue(), 2);
        assertEquals("Assert gtoto_4 - 4", gtoto_4.intValue(), 0);
        //Check tata
        props = tota.getPropsTata();
        tata = (Integer) props.get("tata");
        tataStr = (Integer) props.get("tataStr");
        tataStrs = (Integer) props.get("tataStrs");
        tata_2 = (Integer) props.get("tata_2");
        tata_3 = (Integer) props.get("tata_3");
        tata1 = (Integer) props.get("tata1");
        tata1_1 = (Integer) props.get("tata1_1");
        tata5 = (Integer) props.get("tata5");
        tata5_1 = (Integer) props.get("tata5_1");
        tata5_2 = (Integer) props.get("tata5_2");
        assertEquals("Assert tata - 4", tata.intValue(), 2);
        assertEquals("Assert tataStr - 4", tataStr.intValue(), 2);
        assertEquals("Assert tataStrs - 4", tataStrs.intValue(), 0);
        assertEquals("Assert tata_2 - 4", tata_2.intValue(), 2);
        assertEquals("Assert tata_3 - 4", tata_3.intValue(), 2);
        assertEquals("Assert tata1 - 4", tata1.intValue(), 2);
        assertEquals("Assert tata1_1 - 4", tata1_1.intValue(), 2);
        assertEquals("Assert tata5 - 4", tata5.intValue(), 2);
        assertEquals("Assert tata5_1 - 4", tata5_1.intValue(), 2);
        assertEquals("Assert tata5_2 - 4", tata5_2.intValue(), 2);

        getContext().ungetService(ref);
        tota = null;

        tataFactory.stop();
        assertTrue("Assert under state - 5", under.getState() == ComponentInstance.INVALID);
        assertNull("Assert no tota service - 5", getContext().getServiceReference(Tota.class.getName()));

        totoProv2.stop();
        tataFactory.start();
        assertTrue("Assert under state - 6", under.getState() == ComponentInstance.VALID);
        assertNotNull("Assert tota service - 6", getContext().getServiceReference(Tota.class.getName()));
        ref = getContext().getServiceReference(Tota.class.getName());
        tota = (Tota) getContext().getService(ref);
        invokeAll(tota);
        // Check toto
        props = tota.getProps();
        toto = (Integer) props.get("toto");
        toto_2 = (Integer) props.get("toto_2");
        toto_3 = (Integer) props.get("toto_3");
        toto_4 = (Integer) props.get("toto_4");
        gtoto = (Integer) props.get("gtoto");
        gtoto_2 = (Integer) props.get("gtoto_2");
        gtoto_3 = (Integer) props.get("gtoto_3");
        gtoto_4 = (Integer) props.get("gtoto_4");
        assertEquals("Assert toto - 6", toto.intValue(), 3);
        assertEquals("Assert toto_2 - 6", toto_2.intValue(), 3);
        assertEquals("Assert toto_3 - 6", toto_3.intValue(), 0);
        assertEquals("Assert toto_4 - 6", toto_4.intValue(), 0);
        assertEquals("Assert gtoto - 6 ("+gtoto.intValue()+")", gtoto.intValue(), 3);
        assertEquals("Assert gtoto_2 - 6", gtoto_2.intValue(), 3);
        assertEquals("Assert gtoto_3 - 6", gtoto_3.intValue(), 3);
        assertEquals("Assert gtoto_4 - 6", gtoto_4.intValue(), 0);
        //Check tata
        props = tota.getPropsTata();
        tata = (Integer) props.get("tata");
        tataStr = (Integer) props.get("tataStr");
        tataStrs = (Integer) props.get("tataStrs");
        tata_2 = (Integer) props.get("tata_2");
        tata_3 = (Integer) props.get("tata_3");
        tata1 = (Integer) props.get("tata1");
        tata1_1 = (Integer) props.get("tata1_1");
        tata5 = (Integer) props.get("tata5");
        tata5_1 = (Integer) props.get("tata5_1");
        tata5_2 = (Integer) props.get("tata5_2");
        assertEquals("Assert tata - 6", tata.intValue(), 1);
        assertEquals("Assert tataStr - 6", tataStr.intValue(), 1);
        assertEquals("Assert tataStrs - 6", tataStrs.intValue(), 0);
        assertEquals("Assert tata_2 - 6", tata_2.intValue(), 1);
        assertEquals("Assert tata_3 - 6", tata_3.intValue(), 1);
        assertEquals("Assert tata1 - 6", tata1.intValue(), 1);
        assertEquals("Assert tata1_1 - 6", tata1_1.intValue(), 1);
        assertEquals("Assert tata5 - 6", tata5.intValue(), 1);
        assertEquals("Assert tata5_1 - 6", tata5_1.intValue(), 1);
        assertEquals("Assert tata5_2 - 6", tata5_2.intValue(), 1);
        getContext().ungetService(ref);
        tota = null;

        // Is arch exposed
        assertNotNull("Test arch", Utils.getServiceReferenceByName(getContext(), Architecture.class.getName(), "ff"));

        totoProv.stop();

        assertTrue("Assert under state - 7", under.getState() == ComponentInstance.INVALID);
        assertNotNull("Test arch-2", Utils.getServiceReferenceByName(getContext(), Architecture.class.getName(), "ff"));
        assertNull("Assert no tota service - 7", getContext().getServiceReference(Tota.class.getName()));

        under.dispose();
        under = null;
    }

    private void invoke(Tota tota) {
        tota.tata();

        assertEquals("Assert invoke tataint", tota.tataInt(2), 2);
        assertEquals("Assert invoke tataLong", tota.tataLong(2), 2);
        assertEquals("Assert invoke tataDouble", tota.tataDouble(2), 2);
        assertEquals("Assert invoke tataChar", tota.tataChar('a'), 'a');
        assertTrue("Assert invoke tataBoolean", tota.tataBoolean(true));
        assertEquals("Assert invoke tataByte", tota.tataByte((byte)2), 2);
        assertEquals("Assert invoke tataShort", tota.tataShort((short)5), 5);
        assertEquals("Assert invoke tataFloat", tota.tataFloat(5), 5);

    }

    private void invokeArrays(Tota tota) {

        int[] a = new int[] {1,2,3};
        assertEquals("Assert invoke tataint[]", tota.tataInts(a), a);

        long[] b = new long[] {1,2,3};
        assertEquals("Assert invoke tataLong[]", tota.tataLongs(b), b);

        double[] c = new double[] {1,2,3};
        assertEquals("Assert invoke tataDouble[]", tota.tataDoubles(c), c);

        char[] d = new char[] {'a','b', 'c'};
        assertEquals("Assert invoke tataChar[]", tota.tataChars(d), d);

        boolean[] e = new boolean[] {true, false};
        assertEquals("Assert invoke tataBoolean[]", tota.tataBooleans(e), e);

        byte[] f = new byte[] {(byte) 1};
        assertEquals("Assert invoke tataByte[]", tota.tataBytes(f), f);

        short[] g = new short[] {(short) 1};
        assertEquals("Assert invoke tataShort[]", tota.tataShorts(g), g);

        float[] h = new float[] {5,6,7};
        assertEquals("Assert invoke tataFloat[]", tota.tataFloats(h), h);

    }

    private void invokeStr(Tota tota) {
        tota.tataStr();
    }

    private void invokeTata(Tota tota) {
        tota.tata(1,2);
        tota.tata("tototototo");
    }

    private void invokeTata1(Tota tota) {
        assertEquals("Assert tata1", tota.tata1("foo"), "foo");
        assertEquals("Assert tata1 - 2", tota.tata1(new char[] {'a','b','c'}), "abc");
    }

    private void invokeTata5(Tota tota) {
        assertEquals("Assert tata5 -1", tota.tata5("foo",1), "foo"+1);
        assertEquals("Assert tata5 - 2", tota.tata5(new String[] {"a","b","c"}, 1), "31");
        assertEquals("Assert tata5 - 3", tota.tata5("foo", new int[] {1,2,3}), "foo3");
    }

    private void invokeAdd(Tota tota) {
        assertEquals("Assert add", tota.add(1,1,1), 3);
    }

    private void invokeToto(Tota tota) {
        tota.toto();
        assertEquals("Assert toto", tota.toto("foo"), "foo");
        tota.toto(1,2);
    }

    private void invokeAll(Tota tota) {
        invoke(tota);
        invokeArrays(tota);
        invokeStr(tota);
        invokeTata(tota);
        invokeTata1(tota);
        invokeTata5(tota);
        invokeAdd(tota);
        invokeToto(tota);
    }

}


text:
from __future__ import print_function

# todo upgrade to keras 2.0
from keras.models import Sequential
from keras.layers import Reshape
from keras.layers import Merge
from keras.layers.core import Layer, Dense, Dropout, Activation, Flatten, Reshape, Permute
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import Convolution3D, MaxPooling3D, ZeroPadding3D
from keras.layers.convolutional import Convolution2D, MaxPooling2D, UpSampling2D, ZeroPadding2D
from keras.layers.convolutional import Convolution1D, MaxPooling1D
from keras.layers.recurrent import LSTM
from keras.layers.advanced_activations import LeakyReLU
from keras.optimizers import Adam , SGD
from keras.layers.embeddings import Embedding
from keras.utils import np_utils
from keras import losses
# from keras.regularizers import ActivityRegularizer
from keras import backend as K

def segnet( nClasses=2 , optimizer=None, activationName='softmax', loss=losses.categorical_crossentropy, metrics = ['accuracy'], img_rows=96, img_cols=96 ):

    input_height = img_rows
    input_width = img_cols
    kernel = 3
    filter_size = 64
    pad = 1
    pool_size = 2
    nChannels = 1 #3 originally

    model = Sequential()
    model.add(Layer(input_shape=(input_height , input_width, nChannels )))

    # encoder
    model.add(ZeroPadding2D(padding=(pad,pad)))
    model.add(Convolution2D( filter_size, (kernel, kernel), padding='valid'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(pool_size, pool_size)))

    model.add(ZeroPadding2D(padding=(pad,pad)))
    model.add(Convolution2D( 128, (kernel, kernel), padding='valid'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(pool_size, pool_size)))

    model.add(ZeroPadding2D(padding=(pad,pad)))
    model.add(Convolution2D(256, (kernel, kernel), padding='valid'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(pool_size, pool_size)))

    model.add(ZeroPadding2D(padding=(pad,pad)))
    model.add(Convolution2D(512, (kernel, kernel), padding='valid'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))

    # decoder
    model.add( ZeroPadding2D(padding=(pad,pad)))
    model.add( Convolution2D(512, (kernel, kernel), padding='valid'))
    model.add( BatchNormalization())

    model.add( UpSampling2D(size=(pool_size,pool_size)))
    model.add( ZeroPadding2D(padding=(pad,pad)))
    model.add( Convolution2D(256, (kernel, kernel), padding='valid'))
    model.add( BatchNormalization())

    model.add( UpSampling2D(size=(pool_size,pool_size)))
    model.add( ZeroPadding2D(padding=(pad,pad)))
    model.add( Convolution2D(128, (kernel, kernel), padding='valid'))
    model.add( BatchNormalization())

    model.add( UpSampling2D(size=(pool_size,pool_size)))
    model.add( ZeroPadding2D(padding=(pad,pad)))
    model.add( Convolution2D(filter_size, (kernel, kernel), padding='valid'))
    model.add( BatchNormalization())

    model.add(Convolution2D( nClasses , (1, 1), padding='valid',))

    model.outputHeight = model.output_shape[-3]
    model.outputWidth = model.output_shape[-2]
    print("Dimensions" + str(model.output_shape) )
    #model.add( Reshape(( model.output_shape[-3]*model.output_shape[-2], nClasses ), input_shape=( model.output_shape[-3], model.output_shape[-2], nClasses )))
    #print("Dimensions (reshape)" + str(model.output_shape) )
    #model.add(Permute((2, 1)))
    #print("Dimensions (permutation)" + str(model.output_shape) )
    model.add( Activation(activationName) )
    print("Dimensions (activation)" + str(model.output_shape) )
    #model.add( Reshape(( model.output_shape[-3]*model.output_shape[-2], nClasses ), input_shape=( model.output_shape[-2], model.output_shape[-1], nClasses )))

    if optimizer is None:
        model.compile(loss=loss, optimizer=Adam(lr=1e-5) , metrics=metrics )
    else:
        model.compile(loss=loss, optimizer=optimizer , metrics=metrics )

    return model

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by Tobias on 2015-03-11.
 */

"use strict";
define([], function() {
    var session = angular.module('session', []);
    session.factory('sessionFactory', ['$window', function ($window) {
        return {
            saveItem: function(key, value){
                $window.sessionStorage.setItem(key, JSON.stringify(value));
            },
            getItem: function(key){
              return JSON.parse($window.sessionStorage.getItem(key));
            },
            deleteItem: function(key){
                $window.sessionStorage.removeItem(key);
            }
        };

    }]);
});


text:
schema: default
title: Road Centerline
organization: City of Columbus
notes: Regional Centerline File
resources:
  - name: 'Centerline '
    url: >-
      http://maps.columbus.gov/arcgis/rest/services/CityServices/KeyLayers/MapServer/1
    format: api
  - name: Centerline
    url: >-
      http://data.columbus.opendata.arcgis.com/datasets/e6b61f4130d4429abf4b74a3f0b6fba7_1.csv
    format: csv
  - name: Centerline
    url: >-
      http://data.columbus.opendata.arcgis.com/datasets/e6b61f4130d4429abf4b74a3f0b6fba7_1.zip
    format: shp
  - name: Centerline
    url: >-
      http://data.columbus.opendata.arcgis.com/datasets/e6b61f4130d4429abf4b74a3f0b6fba7_1.kml
    format: kml
license: 'https://creativecommons.org/licenses/by/4.0/'
category:
  - Transportation
maintainer: City of Columbus Department of Public Service
maintainer_email: columbusgis@columbus.gov
---


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using ImageSearchAPILib;
using System.Runtime.InteropServices;
using System.Web;
using System.IO;
using System.Drawing.Imaging;

namespace TwitterImageSearchAPI
{
    public partial class TwitterImageSearchAPI :
        UserControl,
        IImageSearchAPI
    {
        List<ImageData> images = new List<ImageData>();

        public TwitterImageSearchAPI()
        {
            InitializeComponent();

            Params = DefaultParams;
        }

        public string APIName { get { return "Twitter"; } }

        /// <summary>
        /// 0: int 検索方法 0:mixed 1:recent 2:popular
        /// 1: int 検索数 count
        /// 2: bool いつからを使うか
        /// 3: int いつから(年) YYYY-MM-DD
        /// 4: int いつから(月)
        /// 5: int いつから(日)
        /// 6: bool since_idを使うか
        /// 7: int since_id
        /// 8: bool max_idを使うか
        /// 9: int max_id
        /// </summary>

        string[] SearchMethods =
        {
            "mixed",
            "recent",
            "popular",
        };

        public object[] Params
        {
            get
            {
                return new object[]
                {
                    comboBox1.SelectedIndex,
                    numericUpDown1.Value,
                    dateTimePicker1.Checked,
                    dateTimePicker1.Value.Year,
                    dateTimePicker1.Value.Month,
                    dateTimePicker1.Value.Day,
                    checkBox1.Checked,
                    numericUpDown2.Value,
                    checkBox2.Checked,
                    numericUpDown3.Value,
                };
            }
            set
            {
                comboBox1.SelectedIndex = (int)value[0];
                numericUpDown1.Value = (decimal)value[1];
                dateTimePicker1.Checked = (bool)value[2];
                dateTimePicker1.Value = new DateTime((int)value[3], (int)value[4], (int)value[5]);
                checkBox1.Checked = (bool)value[6];
                numericUpDown2.Value = (decimal)value[7];
                checkBox2.Checked = (bool)value[8];
                numericUpDown3.Value = (decimal)value[9];
            }
        }

        public object[] DefaultParams
        {
            get
            {
                return new object[]
                {
                    0,
                    (decimal)100,
                    false,
                    2007,
                    1,
                    1,
                    false,
                    (decimal)1,
                    false,
                    (decimal)10000,
                };
            }
        }

        public ImageData[] ImageDatas
        {
            get { return images.ToArray(); }
        }

        public event EventHandler SearchError = delegate { };
        public event EventHandler SearchFinished = delegate { };
        public event ImageLoadedEventHandler ImageLoaded = delegate { };

        CoreTweet.Tokens tokens = null;

        public void Search(string query)
        {
            images.Clear();
            Task.Factory.StartNew(() =>
            {
                // トークンを取得
                if (tokens == null)
                {
                    tokens = CoreTweet.Tokens.Create(
                         SecretSetting.Default.ConsumerKey,
                         SecretSetting.Default.ConsumerSecret,
                         SecretSetting.Default.AccessToken,
                         SecretSetting.Default.AccessTokenSecret
                         );

                    if (tokens == null)
                    {
                        SearchError(this, EventArgs.Empty);
                        return;
                    }
                }

                // Httpエンコード
                var word = HttpUtility.HtmlEncode(query);

                // 検索し、結果を取得
                var dic = new Dictionary<string, object>();
                dic.Add("q", "filter:images " + word);
                dic.Add("include_entities", true);
                dic.Add("count", (int)numericUpDown1.Value);
                if (comboBox1.SelectedIndex > 0)
                {
                    dic.Add("result_type", SearchMethods[comboBox1.SelectedIndex]);
                }
                if (dateTimePicker1.Checked)
                {
                    var date = string.Format("{0:0000}-{1:00}-{2:00}", dateTimePicker1.Value.Year, dateTimePicker1.Value.Month, dateTimePicker1.Value.Day);
                    dic.Add("until", date);
                }
                if (checkBox1.Checked) dic.Add("since_id", numericUpDown2.Value);
                if (checkBox2.Checked) dic.Add("max_id", numericUpDown3.Value);
                CoreTweet.SearchResult result = null;
                try
                {
                    result = tokens.Search.Tweets(dic);
                }
                catch
                {
                    SearchError(this, EventArgs.Empty);
                    return;
                }

                Parallel.For(0, result.Count, i =>
                {
                    try
                    {
                        var res = result[i];
                        if (res.Entities.Media != null)
                        {
                            foreach (var m in res.Entities.Media)
                            {
                                var wc = new System.Net.WebClient();
                                Stream stream = wc.OpenRead(m.MediaUrl.AbsoluteUri);

                                var idx = m.MediaUrl.LocalPath.LastIndexOf('/');
                                if (idx < 0) idx = 0;
                                var sub = m.MediaUrl.LocalPath.Substring(idx + 1);

                                var idx1 = sub.LastIndexOf(":large");
                                var idx2 = sub.LastIndexOf("-large");
                                if (idx1 > 0)
                                {
                                    sub = sub.Substring(0, idx1);
                                }
                                else if (idx2 > 0)
                                {
                                    sub = sub.Substring(0, idx2);
                                }
                                var bitmap = new System.Drawing.Bitmap(stream);
                                if (sub.LastIndexOf('.') == -1)
                                {
                                    sub += "." + GetFileFormat(bitmap);
                                }

                                var image = new ImageData()
                                {
                                    Bitmap = bitmap,
                                    FileName = sub,
                                    SourceURL = m.ExpandedUrl.AbsoluteUri,
                                };
                                lock (images)
                                {
                                    images.Add(image);
                                    ImageLoaded(this, new ImageLoadedEventArgs() { Index = images.Count - 1, ImageData = image });
                                }
                                stream.Close();
                            }
                        }
                    }
                    catch { }
                });
                SearchFinished(this, EventArgs.Empty);
            });
        }

        static string GetFileFormat(Image img)
        {
            try
            {
                foreach (ImageCodecInfo ici in ImageCodecInfo.GetImageDecoders())
                {
                    if (ici.FormatID == img.RawFormat.Guid)
                        //該当するFormatDescriptionを返します。
                        if (ici.FormatDescription == "BMP") return "bmp";
                        else if (ici.FormatDescription == "JPEG") return "jpg";
                        else if (ici.FormatDescription == "GIF") return "gif";
                        else if (ici.FormatDescription == "TIFF") return "tif";
                        else if (ici.FormatDescription == "PNG") return "png";
                        else return ici.FormatDescription;
                }
                return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            numericUpDown2.Enabled = checkBox1.Checked;
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            numericUpDown3.Enabled = checkBox2.Checked;
        }
    }
}


text:
using MagicalLifeAPI.Asset;
using MagicalLifeAPI.Components.Generic.Renderable;
using MagicalLifeAPI.GUI;
using MagicalLifeAPI.World.Base;
using MagicalLifeMod.Core;
using ProtoBuf;
using System.Collections.Generic;

namespace MagicalLifeAPI.World.Items
{
    /// <summary>
    /// Represents a log in the world.
    /// </summary>
    [ProtoContract]
    public class Log : Item
    {
        private static readonly string ItemName = "Log";

        public Log(int count)
            : base(ItemName, new List<string>(), 50, count, TextureLoader.LogTexture1, 5, DescriptionValues.DisplayName)
        {
            this.InitializeComponents();
        }

        private void InitializeComponents()
        {
            ComponentHasTexture visualComponent = this.GetExactComponent<ComponentHasTexture>();
            visualComponent.Visuals.Add(new StaticTexture(AssetManager.NameToIndex[TextureLoader.LogTexture1], RenderLayer.Items));
        }

        protected Log()
        {
            //Protobuf-net constructor.
        }

        public override Item GetDeepCopy(int amount)
        {
            return new Log(amount);
        }
    }
}


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

<meta name="Generator"
	content="Port80 Eclipse HTML Editor Plugin; 12/20/2002">
<link rel="stylesheet" type="text/css" href="../default.css">
<title>Log Pane</title>

Log Pane

The log pane displays the conversation between JFTP and the FTP
		site you are connected to. The log pane displays messages in various
		colors for various types of messages. The table below explains the
		meanings of these colors:

			Message Color
			Message Type
			Message Description

			Blue
			FTP commands
			FTP commands sent by JFTP requesting the FTP server to take
				the specified action. Please note that all commands are prefixed
				with "<COMMAND>"

			Green
			FTP replies
			All replies received from the FTP server. Please note that
				all positive replies are prefixed with "<REPLY>".

			Red
			Errors
			All negative replies and other errors, such as, network
				failures, occurred during the FTP process.

			Orange
			Status messages
			Status messages. All status messages will be prefixed with
				"<STATUS>".


text:
module Azure::ARM::DataLakeStore
  module Models
    #
    # The encryption configuration for the account.
    #
    class EncryptionConfig

      include MsRestAzure

      # @return [EncryptionConfigType] The type of encryption configuration
      # being used. Currently the only supported types are 'UserManaged' and
      # 'ServiceManaged'. Possible values include: 'UserManaged',
      # 'ServiceManaged'
      attr_accessor :type

      # @return [KeyVaultMetaInfo] The Key vault information for connecting to
      # user managed encryption keys.
      attr_accessor :key_vault_meta_info

      #
      # Mapper for EncryptionConfig class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          required: false,
          serialized_name: 'EncryptionConfig',
          type: {
            name: 'Composite',
            class_name: 'EncryptionConfig',
            model_properties: {
              type: {
                required: true,
                serialized_name: 'type',
                type: {
                  name: 'Enum',
                  module: 'EncryptionConfigType'
                }
              },
              key_vault_meta_info: {
                required: false,
                serialized_name: 'keyVaultMetaInfo',
                type: {
                  name: 'Composite',
                  class_name: 'KeyVaultMetaInfo'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
from .item import Manufactured, Mineral
from math import ceil

class Machine:
    """
    Class for machines that can be used for
    transforming and/or producing other items.

    Note: Machines are also Items, but that's separate
    """

    name = None

    def __init__(self, item):
        self.item = item

    def __repr__(self):
        return self.item.name  # pragma: no cover

    @classmethod
    def serialize(cls, item, serial_data):
        raise NotImplementedError

    def test_item(self, item):
        """
        Test if an item is valid for this machine

        :param item: Item to test
        :type item: Item
        """
        if item.machine_cls != self.name:
            raise ValueError("Item and machine types do not match!")

    def max_production(self, item):
        raise NotImplementedError

    def how_many(self, item, qty):
        """
        Compute how many mining machines are required to achieve a
        given production target.

        :param item: Item to be produced
        :type item: Item

        :param qty: Flow in units/minute to be produced
        :type qty: float

        :return: How many machines are necessary
        :rtype: int
        """
        return ceil(qty / self.max_production(item))

class Miner(Machine):
    """
    Mining machines.
    """

    name = "mining"

    def __init__(self, item, speed, power):
        super().__init__(item)
        self.speed = speed
        self.power = power

    @classmethod
    def serialize(cls, item, serial_data):
        return cls(item, serial_data['speed'], serial_data['power'])

    def max_production(self, item):
        """
        Compute the maximum rate at which the given item can be mined

        :param item: Mineral to be mined
        :type item: Mineral

        :return: Maximum production rate (items/minute)
        :rtype: float
        """

        self.test_item(item)
        if item.hardness >= self.power:
            raise ValueError("{} is not powerful enough to mine {}"
                             .format(self.item.name, item.name))

        return (self.power - item.hardness) * self.speed * 60 / item.time

class BaseManufacture(Machine):

    name = None

    def __init__(self, item, speed):
        super().__init__(item)
        self.speed = speed

    @classmethod
    def serialize(cls, item, serial_data):
        return cls(item, serial_data['speed'])

    def max_production(self, item):
        """
        Compute the maximum rate at which the given item can be made

        :param item: Item to be produced
        :type item: Manufactured

        :return: Maximum production rate (items/minute)
        :rtype: float
        """
        self.test_item(item)
        return self.speed * item.produced * 60 / item.time

class Assembler(BaseManufacture):
    """
    Assembling machines.
    """
    name = "assembling"

class Furnace(BaseManufacture):
    """
    Furnaces.
    """
    name = "smelting"

class ChemicalPlant(BaseManufacture):
    """
    Chemical Plants.
    """
    name = "chemistry"

class RocketSile(BaseManufacture):
    """
    The rocket Silo
    """
    name = "rocket"


text:
class ManagementD3D;

struct EntityBufferInfo;

class CubeFactory
{
public:
	static HRESULT createCube( ManagementD3D* p_managementD3D,
		EntityBufferInfo** out_cube );

private:
	static HRESULT createVertices( ManagementD3D* p_managementD3D,
		EntityBufferInfo* inout_cube );
	static HRESULT createIndices( ManagementD3D* p_managementD3D,
		EntityBufferInfo* inout_cube );
};


text:
package org.springframework.boot.actuate.info;

import org.springframework.aot.hint.BindingReflectionHintsRegistrar;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.boot.actuate.info.Info.Builder;
import org.springframework.boot.actuate.info.JavaInfoContributor.JavaInfoContributorRuntimeHints;
import org.springframework.boot.info.JavaInfo;
import org.springframework.context.annotation.ImportRuntimeHints;

/**
 * An {@link InfoContributor} that exposes {@link JavaInfo}.
 *
 * @author Jonatan Ivanov
 * @since 2.6.0
 */
@ImportRuntimeHints(JavaInfoContributorRuntimeHints.class)
public class JavaInfoContributor implements InfoContributor {

	private final JavaInfo javaInfo;

	public JavaInfoContributor() {
		this.javaInfo = new JavaInfo();
	}

	@Override
	public void contribute(Builder builder) {
		builder.withDetail("java", this.javaInfo);
	}

	static class JavaInfoContributorRuntimeHints implements RuntimeHintsRegistrar {

		private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();

		@Override
		public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
			this.bindingRegistrar.registerReflectionHints(hints.reflection(), JavaInfo.class);
		}

	}

}


text:
<?php

namespace App\Interfaces;

interface PostInterface
{
    public function all();
    public function find($id);
    public function create($data);
    public function getAtHome();
    public function modified($data);
    public function getNewPost();
}


text:
title: SalonTarget
description: Senior Software Engineer (Contractor - 6 Months)
date: "2014-01-01T19:47:09+02:00"
jobDate: 2014
work: [Senior Software Engineer (Contractor - 6 Months)]
techs: [NodeJS, PHP, React, Twilio, MySQL, MongoDB, Mongoose, Digital Ocean]
thumbnail: salon_target/st.png
projectUrl: https://www.salontarget.com/
---

- Focused on NodeJS, MySQL, Express, and Backbone to deliver a new product interface and architecture

- Senior Full Stack Software Engineer responsible for implementing a new technology stack and integrating with legacy systems

- Designed and implemented a NodeJS API utilizing numerous libraries including Express, Mongoose, MailGun, and Mocha Unit Testing

- Implemented a full continuous integration system, ensuring high quality and thoroughly tested software releases


text:
namespace Computers.Core.Models.HardDrive
{
    public abstract class HardDrive : IHardDrive
    {
        public abstract int Capacity { get; }

        public abstract void SaveData(int address, string newData);

        public abstract string LoadData(int address);
    }
}


text:
require File.dirname(__FILE__) + "/helper"

class ModulusNodeTest < NodeTestCase
  def test_to_sexp
    node = ModulusNode.new(NumberNode.new(5), NumberNode.new(10))
    assert_sexp([:modulus, [:lit, 5], [:lit, 10]], node)
  end
end


text:
[![Build status](https://ci.appveyor.com/api/projects/status/5uocynec8e3maeeq?svg=true&branch=master)](https://ci.appveyor.com/project/ishiland/python-geosupport) [![PyPI version](https://img.shields.io/pypi/v/python-geosupport.svg)](https://pypi.python.org/pypi/python-geosupport/) [![Python 2.7 | 3.4+](https://img.shields.io/badge/python-2.7%20%7C%203.4+-blue.svg)](https://www.python.org/downloads/release/python-360/)

Python bindings for NYC Planning's [Geosupport Desktop Edition](https://www1.nyc.gov/site/planning/data-maps/open-data/dwn-gde-home.page).

### [Read the docs](https://python-geosupport.readthedocs.io/en/latest/)

## Quickstart

```python
# Import the library and create a `Geosupport` object.
from geosupport import Geosupport
g = Geosupport()

# Call the address processing function by name
result = g.address(house_number=125, street_name='Worth St', borough_code='Mn')
```

`result` is a dictionary with the output from Geosupport. For example:

```
{
    '2010 Census Block': '1012',
    '2010 Census Tract': '31',
    'Assembly District': '65',
    'Atomic Polygon': '112',
    'B10SC - First Borough and Street Code': '14549001010',
    'BOE Preferred B7SC': '14549001',
    'BOE Preferred Street Name': 'WORTH STREET',
    'BOROUGH BLOCK LOT (BBL)': {
        'BOROUGH BLOCK LOT (BBL)': '1001680032',
        'Borough Code': '1',
        'Tax Block': '00168',
        'Tax Lot': '0032'
    },
    'Blockface ID': '0212261942',
    ...
}
```

## License

This project is licensed under the MIT License - see the [license.txt](license.txt) file for details

## Contributors
Thanks to [Jeremy Neiman](https://github.com/docmarionum1) for a major revision incorporating all Geosupport functions and parameters.

If you see an issue or would like to contribute, pull requests are welcome.


text:
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAdminUser

from apps.core.views import poster
from . import tasks

@api_view(['POST'])
@permission_classes([IsAdminUser])
def publish_view(request):
    return poster(tasks.fetch_and_publish)

@api_view(['POST'])
@permission_classes([IsAdminUser])
def blank_publish_view(request):
    """Save posts into db w/o publishing."""
    return poster(lambda: tasks.fetch_and_publish(blank=True, force=True))


text:
This project is a sample project to show how the library works.
Without being uploaded, having a real premium package, public key, and ad Id, the project isn't really functionnal
but shows at least the way you have to implement it.

See the library's [Readme.md](https://github.com/MagicMicky/FreemiumLibrary) for more information


text:
<?php

declare(strict_types=1);

namespace Sylius\Component\Addressing\Model;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Sylius\Component\Resource\Model\ToggleableTrait;
use Symfony\Component\Intl\Countries;

class Country implements CountryInterface, \Stringable
{
    use ToggleableTrait;

    /** @var mixed */
    protected $id;

    /**
     * Country code ISO 3166-1 alpha-2.
     *
     * @var string|null
     */
    protected $code;

    /**
     * @var Collection|ProvinceInterface[]
     *
     * @psalm-var Collection<array-key, ProvinceInterface>
     */
    protected $provinces;

    public function __construct()
    {
        /** @var ArrayCollection<array-key, ProvinceInterface> $this->provinces */
        $this->provinces = new ArrayCollection();
    }

    public function __toString(): string
    {
        return (string) ($this->getName() ?? $this->getCode());
    }

    public function getId()
    {
        return $this->id;
    }

    public function getCode(): ?string
    {
        return $this->code;
    }

    public function setCode(?string $code): void
    {
        $this->code = $code;
    }

    public function getName(?string $locale = null): ?string
    {
        return Countries::getName($this->code, $locale);
    }

    public function getProvinces(): Collection
    {
        return $this->provinces;
    }

    public function hasProvinces(): bool
    {
        return !$this->provinces->isEmpty();
    }

    public function addProvince(ProvinceInterface $province): void
    {
        if (!$this->hasProvince($province)) {
            $this->provinces->add($province);
            $province->setCountry($this);
        }
    }

    public function removeProvince(ProvinceInterface $province): void
    {
        if ($this->hasProvince($province)) {
            $this->provinces->removeElement($province);
            $province->setCountry(null);
        }
    }

    public function hasProvince(ProvinceInterface $province): bool
    {
        return $this->provinces->contains($province);
    }
}


text:
<?php

namespace Wallabag\CoreBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Wallabag\CoreBundle\Entity\SiteCredential;

class LoadSiteCredentialData extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        $credential = new SiteCredential($this->getReference('admin-user'));
        $credential->setHost('example.com');
        $credential->setUsername('foo');
        $credential->setPassword('bar');

        $manager->persist($credential);

        $manager->flush();
    }

    /**
     * {@inheritdoc}
     */
    public function getOrder()
    {
        return 50;
    }
}


text:
<?php

include("assets/core/config/part_set_timezone.php");
include("connectDatabase.inc");
include("part_session.php");
include("requestVariableSanitizer.inc");
include("class_category_user_group_validator.php");
include("class_config_reader.php");

$groupId = sanitize_string($_REQUEST['groupId']);
$s = sanitize_string($_REQUEST['s']);
$d = sanitize_string($_REQUEST['d']);
$month = sanitize_string($_REQUEST['month']);
$year = sanitize_string($_REQUEST['year']);
$dateOrder = sanitize_string($_REQUEST['dateOrder']);
$titleOrder = sanitize_string($_REQUEST['titleOrder']);
$statusOrder = sanitize_string($_REQUEST['statusOrder']);
$orderBy = sanitize_string($_REQUEST['orderBy']);
$change = sanitize_string($_REQUEST['change']);

if (trim($groupId) == "" || trim($_SESSION['username']) == "") {exit;}

changeDirection($groupId, $s, $d, $month, $year, $dateOrder, $titleOrder, $statusOrder, $orderBy, $change);

function changeDirection($groupId, $s, $d, $month, $year, $dateOrder, $titleOrder, $statusOrder, $orderBy, $change) {

	//validate group and requesting user access rights
	if ($_SESSION['userLevel'] != 1 && $_SESSION['userLevel'] != 2 && $_SESSION['userLevel'] != 3 && $_SESSION['userLevel'] != 4) {

		//if the user is not an admin, validate that the user is allowed to access the requested group
		$result = mysql_query("SELECT parentId FROM groupsMembers WHERE parentId = '{$groupId}' AND username = '{$_SESSION['username']}' AND (memberLevel = '1' OR memberLevel = '2') AND status = 'approved'");

		if (mysql_num_rows($result) > 0) {

			$isGroupAdmin = 1;

		}

	}

	$max_per_page = 25;

	if (trim($s) == "") {

		$s = 0;

	}

	if (trim($month) != "") {

		$monthQuery = " AND EXTRACT(MONTH FROM startDate) = '$month'";

	}

	if (trim($year) != "") {

		$yearQuery = " AND EXTRACT(YEAR FROM startDate) = '$year'";

	}

	if ($orderBy == $change) {

		if ($change == "date") {if ($dateOrder == "desc") {$dateOrder = "asc";} else {$dateOrder = "desc";} $changeDate = "date";}
		if ($change == "title") {if ($titleOrder == "desc") {$titleOrder = "asc";} else {$titleOrder = "desc";} $changeTitle = "title";}
		if ($change == "status") {if ($statusOrder == "desc") {$statusOrder = "asc";} else {$statusOrder = "desc";} $changeStatus = "status";}

	}

	if ($orderBy == "date") {$orderBySQL = "startDate"; $directionSQL = strtoupper($dateOrder); $changeDate = "date";}
	if ($orderBy == "title") {$orderBySQL = "title"; $directionSQL = strtoupper($titleOrder); $changeTitle = "title";}
	if ($orderBy == "status") {$orderBySQL = "publishState"; $directionSQL = strtoupper($statusOrder); $changeStatus = "status";}

	$result = mysql_query("SELECT id FROM events WHERE groupId = '{$groupId}'$monthQuery$yearQuery");
	$totalRows = mysql_num_rows($result);

	$showTotalPages = ceil($totalRows / $max_per_page);

	if ($d == "b") {

		$s -= $max_per_page;

		if ($s < 0) {

			$s = 0;

		}

	}

	if ($d == "n") {

		if ($s + $max_per_page < $totalRows) {

			$s += $max_per_page;

		}

	}

	if ($totalRows > 0) {

		$showCurrentPage = floor($s / $max_per_page) + 1;

	} else {

		$showCurrentPage = 0;

	}

	$result = mysql_query("SELECT *, DATE_FORMAT(startDate, '%m/%d/%Y %h:%i %p') AS newStartDate, DATE_FORMAT(expireDate, '%m/%d/%Y %h:%i %p') AS newExpireDate FROM events WHERE groupId = '{$groupId}'$monthQuery$yearQuery ORDER BY $orderBySQL $directionSQL LIMIT $s, $max_per_page");
	$count = mysql_num_rows($result);

	if ($count < 1 && $totalRows > 0 && $s > 0) {

		$s -= $max_per_page;
		return changeDirection($groupId, $s, '', $month, $year, $dateOrder, $titleOrder, $statusOrder, $orderBy, $change);

	} else {

		if ($_SESSION['userLevel'] == 1 || $_SESSION['userLevel'] == 2 || $_SESSION['userLevel'] == 3 || $isGroupAdmin == 1) {

			print "<form id=\"multipleEventsAction\">";

		}

		print "
";

		if ($_SESSION['userLevel'] == 1 || $_SESSION['userLevel'] == 2 || $_SESSION['userLevel'] == 3 || $isGroupAdmin == 1) {

			print "

";

		}

		print "
Date
";
		print "
Title
";
		print "
Status
";

		if ($_SESSION['userLevel'] == 1 || $_SESSION['userLevel'] == 2 || $_SESSION['userLevel'] == 3 || $isGroupAdmin == 1) {

			print "

";

		}

		print "
";

		while ($row = mysql_fetch_object($result)) {

			$showTitle = htmlentities($row->title);
			$showStatus = htmlentities($row->publishState);

			if ($row->private == 1) {

				$showPrivate = "[private] ";

			} else {

				$showPrivate = "";

			}

			//define which publish options to display
			if ($_SESSION['userLevel'] == 1 || $_SESSION['userLevel'] == 2 || $_SESSION['userLevel'] == 3 || $isGroupAdmin == 1) {

				$showPublishOptions = "id');\" onclick=\"return confirm('Are you sure you want to change the publishing status of this document?');\">id\">";

				if ($row->publishState == "Published") {

					$showPublishOptions .= " $showStatus";

				} else {

					$showPublishOptions .= " $showStatus";

				}

			} else {

				$showPublishOptions = $showStatus;

			}

			//define which document editor options to display
			if ($row->publishState == "Published") {

				//validate user access level for published content
				if ($_SESSION['userLevel'] == 1 || $_SESSION['userLevel'] == 2 || $_SESSION['userLevel'] == 3 || $isGroupAdmin == 1) {

					$showDocumentEditorOptions = "id&groupId=$groupId\"> $showPrivate$showTitle";

				} else {

					$showDocumentEditorOptions = "$showPrivate$showTitle";

				}

			} else {

				//display the editor for unpublished content
				$showDocumentEditorOptions = "id&groupId=$groupId\"> $showPrivate$showTitle";

			}

			print "
id\" class=\"event_container\">";

			if ($_SESSION['userLevel'] == 1 || $_SESSION['userLevel'] == 2 || $_SESSION['userLevel'] == 3 || $isGroupAdmin == 1) {

				print "
<input style=\"vertical-align:middle;\" type=\"checkbox\" id=\"multipleId[]\" name=\"multipleId[]\" value=\"$row->id\">
";

			}

			print "
id\" target=\"_blank\"> $row->newStartDate - $row->newExpireDate
";
			print "
$showDocumentEditorOptions
";
			print "
$showPublishOptions
";

			if ($_SESSION['userLevel'] == 1 || $_SESSION['userLevel'] == 2 || $_SESSION['userLevel'] == 3 || $isGroupAdmin == 1) {

				print "
id', '$s', '$dateOrder', '$titleOrder', '$statusOrder', '$orderBy');\" onClick=\"return confirm('Are you sure you want to delete this event?');\"> Delete
";

			}

			print "
";

		}

		if (mysql_num_rows($result) == 0) {

			print "
";
			print "There are no events scheduled during the selected date.";
			print "
";

		}

		if ($_SESSION['userLevel'] == 1 || $_SESSION['userLevel'] == 2 || $_SESSION['userLevel'] == 3 || $isGroupAdmin == 1) {

			print "
";
			print "
<input id=\"check_all\" name=\"check_all\" type=\"checkbox\" onclick=\"$('#multipleEventsAction :checkbox').attr('checked', this.checked);\">

Select All

Switch Status

Delete
";
			print "
";

		}

		print "
";
		print "
$totalRows Events

Page: $showCurrentPage of $showTotalPages

Previous

Next

";
		print "
";

		if ($_SESSION['userLevel'] == 1 || $_SESSION['userLevel'] == 2 || $_SESSION['userLevel'] == 3 || $isGroupAdmin == 1) {

			print "<input type=\"hidden\" id=\"groupId\" name=\"groupId\" value=\"$groupId\">";
			print "<input type=\"hidden\" id=\"s\" name=\"s\" value=\"$s\">";
			print "<input type=\"hidden\" id=\"dateOrder\" name=\"dateOrder\" value=\"$dateOrder\">";
			print "<input type=\"hidden\" id=\"titleOrder\" name=\"titleOrder\" value=\"$titleOrder\">";
			print "<input type=\"hidden\" id=\"statusOrder\" name=\"statusOrder\" value=\"$statusOrder\">";
			print "<input type=\"hidden\" id=\"orderBy\" name=\"orderBy\" value=\"$orderBy\">";
			print "</form>";

		}

	}

}

?>


text:
<?php

/** */
namespace CoreTest\Entity;

use PHPUnit\Framework\TestCase;

use Core\Entity\AbstractEntity;

/**
 * Test the Abstract Entity
 *
 * @author Carsten Bleek <bleek@cross-solution.de>
 * @group  Core
 * @group  Core.Entity
 * @covers \Core\Entity\AbstractEntity
 */
class AbstractEntityTest extends TestCase
{
    protected $target;

    protected function setUp(): void
    {
        $this->target = new ConcreteEntity();
    }

    public function testSettingValidAttributes()
    {
        $input = "myValue";
        $this->target->setValidAttribute($input);
        $this->assertSame($this->target->getValidAttribute(), $input);
    }

    public function testGettingValidAttributes()
    {
        $input = "myValue";
        $this->target->setValidAttribute($input);
        $this->assertSame($this->target->getValidAttribute(), $input);
    }

    /**
     * @expectedException \Core\Entity\Exception\OutOfBoundsException
     */
    public function testSettingInvalidAttributes()
    {
        $input = "myValue";
        @$this->target->invalidAttribute=$input;
    }

    /**
     * @expectedException \Core\Entity\Exception\OutOfBoundsException
     */
    public function testGettingInvalidAttributes()
    {
        $input = "myValue";
        $this->assertSame(@$this->target->invalidAttribute, $input);
    }
}

class ConcreteEntity extends AbstractEntity
{
    protected $validAttribute;

    public function setValidAttribute($validAttribute)
    {
        $this->validAttribute=$validAttribute;
        return $this;
    }

    public function getValidAttribute()
    {
        return $this->validAttribute;
    }
}


text:
package com.basdek.mailchimp_v3.operations.lists.mergefields

import com.basdek.mailchimp_v3.dto.MailChimpListMergeField
import com.basdek.mailchimp_v3.{MailChimpResultFuture, Config, SimpleAuthenticate}
import com.basdek.mailchimp_v3.operations.Operation
import com.ning.http.client.Response
import dispatch._, Defaults._
import org.json4s._, native.JsonMethods._, native.Serialization.{write => jsonWrite}

/**
  * Implementation of the POST /lists/{listId}/merge-fields operation.
  *
  * @param cfg A Config instance.
  * @param listId The id of the list where you want to add a MergeField.
  * @param data An instance of the MailChimpListMergeField DTO object.
  */
class AddMergeFieldOperation
  (val cfg: Config, listId: String, data: MailChimpListMergeField)
  extends Operation with SimpleAuthenticate {

  private def transformer(res: Response) : MailChimpListMergeField = {
    val responseBody = res.getResponseBody
    parse(responseBody).extract[MailChimpListMergeField]
  }

  def execute : MailChimpResultFuture = {
    val req = addAuth(:/(s"${cfg.apiEndpoint}/lists/$listId/merge-fields").POST.secure)
      .setBody(jsonWrite(data))
      .setContentType("application/json", "utf-8")
    httpToResult(req, transformer)
  }
}


text:
set -e

cell='test'
web_port=15001
grpc_port=15991

script_root=`dirname "${BASH_SOURCE}"`
source $script_root/env.sh

# Start vtgate.
$VTROOT/bin/vtgate \
  -log_dir $VTDATAROOT/tmp \
  -port $web_port \
  -grpc_port $grpc_port \
  -cell $cell \
  -cells_to_watch $cell \
  -tablet_types_to_wait MASTER,REPLICA \
  -gateway_implementation discoverygateway \
  -service_map 'grpc-vtgateservice' \
  -pid_file $VTDATAROOT/tmp/vtgate.pid \
  > $VTDATAROOT/tmp/vtgate.out 2>&1 &

echo "Access vtgate at http://$hostname:$web_port/debug/status"

disown -a


text:
namespace Zu.ChromeDevTools.Runtime
{
    using Newtonsoft.Json;

    /// <summary>
    /// Issued when object should be inspected (for example, as a result of inspect() command line API
    /// call).
    /// </summary>
    public sealed class InspectRequestedEvent : IEvent
    {
        /// <summary>
        /// Gets or sets the object
        /// </summary>
        [JsonProperty("object")]
        public RemoteObject Object
        {
            get;
            set;
        }
        /// <summary>
        /// Gets or sets the hints
        /// </summary>
        [JsonProperty("hints")]
        public object Hints
        {
            get;
            set;
        }
        /// <summary>
        /// Identifier of the context where the call was made.
        /// </summary>
        [JsonProperty("executionContextId", DefaultValueHandling = DefaultValueHandling.Ignore)]
        public long? ExecutionContextId
        {
            get;
            set;
        }
    }
}


text:
layout: nil
title: SHARE
---
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta content="nodeclipse,Nodeclipse,node.js,eclipse pulgin,ide,node,debug,phantomjs,jjs,nashorn,vert.x,maven,gradle,android" name="keywords">
    <link type="image/x-icon" rel="icon" href="favicon.ico">
    <link type="image/x-icon" rel="shortcut icon" href="favicon.ico">
    <link rel="stylesheet" href="pipe.css">
	<title>Nodeclipse, Enide -- Node.JS development in Eclipse</title>

	{% include navigation-links.html %}

        <form class="donate-img" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
            <input type="hidden" name="cmd" value="_xclick">
            <input type="hidden" name="business" value="lambgao@aliyun.com">
            <input type="hidden" name="lc" value="C2">
            <input type="hidden" name="button_subtype" value="services">
            <input type="hidden" name="no_note" value="0">
            <input type="hidden" name="currency_code" value="USD">
            <input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHostedGuest">
            <input id="goPaypal" type="image" src="img/paypal-donate.jpg" border="0" name="submit" alt="PayPal——最安全便捷的在线支付方式!">

        </form>

Donate via Paypal

Donate via Alipay. 使用支付宝钱包进行捐赠,请扫描上面的二维码

    {% include enide-2015-downloads.html %}


text:
import React from 'react';

import './Alerts.css';

export const Success = ({ title, body }) => {
  return (

      {title && (

          {title}

      )}

        {body}

  );
};


text:
package yyl.rabbitcloud.liveroom;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by yyl on 2017/7/2.
 */

public class LiveRoomViewPagerAdapter extends PagerAdapter {

    private List<View> mViewList;
    private String[] titles;

    public LiveRoomViewPagerAdapter(String[] titles) {
        this.titles = titles;
    }

    public void setViewList(List<View> viewList) {
        mViewList = viewList;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mViewList == null? 0:mViewList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        container.addView(mViewList.get(position));
        return mViewList.get(position);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(mViewList.get(position));
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (titles != null) {
            return titles[position];
        } else {
            return "";
        }
    }
}


text:
var AppRouter = Backbone.Router.extend({

    routes: {
        ""                               : "home",
		"graph/:graph/:parameters"	     : "graph"
    },

    home: function (id) {
        if (!this.homeView) {
            this.homeView = new HomeView();
        }
        $('#content').html(this.homeView.el);
    },

	graph: function (graph, parameters) {
		var obj = new Graph({_graph: graph, _parameters: parameters});
        obj.fetch({
			success: function(){
				$(".header").hide();
				$(".footer").hide();
				$("#content").html(new GraphView({model: obj}).el);
			},
			error: function(e){
				$("#content").html(new ErrorView().el);
			}
		});
    }

});

utils.loadTemplate(['HomeView', 'ErrorView', 'GraphView'], function() {
    app = new AppRouter();
    Backbone.history.start();
});


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace GetListSelection
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            object r = MainForm.GetSelectionFromList(new string[] { "One", "Two", "Three", "" },
                "My Caption", "My Message", true, "My Other Value", "My Empty Value");
            if (r == null)
            {
                MessageBox.Show("Returned null");
            }
            else
            {
                MessageBox.Show(String.Format("Returned '{0}'", r));
            }
        }
    }
}


text:
@interface Play : NSObject {
  NSString *artist;
  NSString *track;
  NSString *mbid;
  NSString *small_image;
  NSString *signature;
  NSDate *timestamp;
}

@property (nonatomic, copy) NSString *artist;
@property (nonatomic, copy) NSString *track;
@property (nonatomic, copy) NSString *mbid;
@property (nonatomic, copy) NSString *small_image;
@property (nonatomic, copy) NSString *signature;
@property (nonatomic, retain) NSDate *timestamp;

@end


text:
<?php
namespace Radar\Adr\Handler;

use Arbiter\ActionFactory;
use Aura\Router\Map;
use Aura\Router\RouterContainer;
use Radar\Adr\Route;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequestFactory;

class RoutingHandlerTest extends \PHPUnit_Framework_TestCase
{
    protected $map;
    protected $matcher;
    protected $routingHandler;

    protected function setUp()
    {
        $actionr = new RouterContainer();
        $actionr->setMapFactory(function () { return new Map(new Route()); } );

        $this->map = $actionr->getMap();
        $this->matcher = $actionr->getMatcher();
        $this->routingHandler = new RoutingHandler($this->matcher, new ActionFactory());
    }

    protected function newRequest($path)
    {
        $_SERVER['REQUEST_URI'] = $path;
        return ServerRequestFactory::fromGlobals();
    }

    public function testFound()
    {
        $this->map->get('Radar\Adr\Fake\Action', '/fake/{id}', 'FakeDomain');
        $request = $this->newRequest('/fake/88');
        $response = new Response();
        $returnedResponse = $this->routingHandler->__invoke(
            $request,
            $response,
            [$this, 'assertFound']
        );
        $this->assertSame($response, $returnedResponse);
    }

    public function assertFound($request, $response)
    {
        $action = $request->getAttribute('radar/adr:action');
        $id = $request->getAttribute('id');
        $this->assertSame('88', $id);
        return $response;
    }

    public function testNotFound()
    {
        $this->map->get('Radar\Adr\Fake\Action', '/fake/{id}', 'FakeDomain');
        $request = $this->newRequest('/wrong/path');
        $response = new Response();
        $returnedResponse = $this->routingHandler->__invoke(
            $request,
            $response,
            [$this, 'assertNotFound']
        );
        $this->assertSame($response, $returnedResponse);
    }

    public function assertNotFound($request, $response)
    {
        $action = $request->getAttribute('radar/adr:action');
        $this->assertSame(
            'Radar\Adr\Responder\RoutingFailedResponder',
            $action->getResponder()
        );

        $expect = $this->matcher->getFailedRoute();
        $actual = call_user_func($action->getDomain());
        $this->assertSame($expect, $actual);

        return $response;
    }

    public function testCustomNotFound()
    {
        $routingHandler = new RoutingHandler(
            $this->matcher,
            new ActionFactory(),
            'Radar\Adr\Fake\FakeRoutingFailedResponder'
        );

        $this->map->get('Radar\Adr\Fake\Action', '/fake/{id}', 'FakeDomain');
        $request = $this->newRequest('/wrong/path');
        $response = new Response();
        $returnedResponse = $routingHandler->__invoke(
            $request,
            $response,
            [$this, 'assertCustomNotFound']
        );
    }

    public function assertCustomNotFound($request, $response)
    {
        $action = $request->getAttribute('radar/adr:action');
        $this->assertSame(
            'Radar\Adr\Fake\FakeRoutingFailedResponder',
            $action->getResponder()
        );

        $expect = $this->matcher->getFailedRoute();
        $actual = call_user_func($action->getDomain());
        $this->assertSame($expect, $actual);

        return $response;
    }
}


text:
package com.ivoryworks.pgma;

import android.os.RemoteException;
import android.os.SystemClock;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SdkSuppress;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.widget.ListView;
import android.widget.TextView;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion = 18)
public class MediaEffectsFragmentTest {
    private UiDevice mDevice;

    @Before
    public void setup() {
        mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

        Tools.goToHome(mDevice);
        Tools.startPGMA(mDevice);

        // open Navigation drawer
        Tools.clickNavigationDrawerItem(mDevice, "Media Effects");
    }

    @Test
    public void testOrientation() {
        try {
            Tools.orientation(mDevice);
        } catch (RemoteException e) {
            assertFalse(true);
        }
    }

    @Test
    public void testEffects() {
        mDevice.pressMenu();
        try {
            mDevice.findObject(new UiSelector().text("EFFECT_AUTOFIX")).clickAndWaitForNewWindow();
        } catch (UiObjectNotFoundException e) {
            e.printStackTrace();
        }
        SystemClock.sleep(5000);
    }

    private boolean clickListTextAndWait(String text) {
        try {
            findTextInListView(text).clickAndWaitForNewWindow();
        } catch (UiObjectNotFoundException e) {
            return false;
        }
        return true;
    }

    private UiObject findTextInListView(String itemName) throws UiObjectNotFoundException {
        UiScrollable scroller = new UiScrollable(new UiSelector().className(ListView.class.getName()));
        // スクロール方向指定
        scroller.setAsVerticalList();
        return scroller.getChildByText(new UiSelector().className(TextView.class.getName()), itemName);
    }
}


text:
#include "siof_types.h"

extern SomeNonPODObject extern_global_object;
SomeNonPODObject global_object;
extern int access_to_non_pod();
void safe_streams();

struct SomeOtherNonPODObject {
  SomeOtherNonPODObject() {
    global_object.some_method(); // OK, same translation unit
    extern_global_object.some_method(); // bad, different translation unit
  };

  SomeOtherNonPODObject(int i) {
    global_object.some_method(); // OK, same translation unit
    safe_streams(); // OK, that function is SIOF safe
  };
};

SomeOtherNonPODObject another_global_object_bad;
SomeOtherNonPODObject another_global_object2_bad(access_to_non_pod());
SomeOtherNonPODObject another_global_object3_bad(access_to_templated_non_pod());
SomeOtherNonPODObject another_global_object4_good(42);

int pod_accesses_non_pod_bad = access_to_non_pod();

struct X {
  static int static_pod_accesses_non_pod_bad;
};

int X::static_pod_accesses_non_pod_bad = access_to_non_pod();

SomeNonPODObject initWithStatic_good = getFunctionStaticNonPOD();
SomeNonPODObject initWithGlobal_bad = getGlobalNonPOD();

SomeNonPODObject initWithGlobalAllowListed_good = getGlobalNonPODAllowListed();

SomeNonPODObject initWithGlobalAllowListedNamespaced_good =
    allow_listed::getGlobalNonPOD();

SomeNonPODObject initWithGlobalAllowListedTemplated_good =
    allow_listed::TemplatedObject<int>::getGlobalNonPOD();

// not declared constexpr but actually constexpr
extern SomeConstexprObject& getGlobalConstexpr();
SomeConstexprObject initWithConstexpr_good = getGlobalConstexpr();
SomeConstexprObject initArrayWithConstexprs_good[] = {
    getGlobalConstexpr(), getGlobalConstexpr(), getGlobalConstexpr()};

extern SomeTemplatedConstexprObject<int>& getGlobalTemplatedConstexpr();
SomeTemplatedConstexprObject<int> initWithTemplatedConstexpr_good =
    getGlobalTemplatedConstexpr();


text:
data.enemies[RESOURCE_ID] = {

  onTurn = function(battle, enemy, playerParty)
    --print(enemy.name .. " - onTurn - slime looks confused")
    local randoTarget = battle:getRandomHeroAlive()
    --randoTarget.hp = randoTarget.hp - 5
    --print(enemy.name .. ' attacks ' .. randoTarget.name .. ' ' .. randoTarget.hp .. '/' .. randoTarget.maxHp )

    return data.skills['base.skills.attack'].onSelect(enemy, randoTarget)

--    return {
--      target = randoTarget,
--      dialogText = enemy.name .. ' attacks ' .. randoTarget.name .. ' ' .. randoTarget.hp .. '/' .. randoTarget.maxHp
--    }

  end

}


text:
FROM scratch
EXPOSE 3232
ADD search /
CMD ["/search"]


text:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

          <title>org.saddle.vec.VecStatsImplicits</title>
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link type="text/css" media="screen" rel="stylesheet" href="../../../lib/template.css" />

org.saddle.vec

VecStatsImplicits

        trait

        VecStatsImplicits extends AnyRef

Enrich Vec with stats

          Linear Supertypes

AnyRef, Any

          Known Subclasses

Vec

<input accesskey="/" type="text" />

              Ordering

Alphabetic

By inheritance

              Inherited

Hide All

Show all

VecStatsImplicits

AnyRef

Any

            Visibility

Public

All

Type Members

        type

        Vec2Stats[A] = (Vec[A]) ⇒ VecStats[A]

Value Members

        final
        def

        !=(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

Any

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        final
        def

        ==(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

Any

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        def

        clone(): AnyRef

Attributes

protected[lang]

Definition Classes

AnyRef

Annotations

                @throws()

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        def

        finalize(): Unit

Attributes

protected[lang]

Definition Classes

AnyRef

Annotations

                @throws()

        final
        def

        getClass(): java.lang.Class[_]

Definition Classes

AnyRef → Any

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        notify(): Unit

Definition Classes

AnyRef

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        def

        toString(): String

Definition Classes

AnyRef → Any

        implicit
        def

        vecToDoubleExpStats(s: Vec[Double]): VecExpandingStats[Double]

        implicit
        def

        vecToDoubleRollingStats(s: Vec[Double]): VecRollingStats[Double]

        implicit
        def

        vecToDoubleStats(s: Vec[Double]): VecStats[Double]

        implicit
        def

        vecToIntExpStats(s: Vec[Int]): VecExpandingStats[Int]

        implicit
        def

        vecToIntRollingStats(s: Vec[Int]): VecRollingStats[Int]

        implicit
        def

        vecToIntStats(s: Vec[Int]): VecStats[Int]

        implicit
        def

        vecToLongExpStats(s: Vec[Long]): VecExpandingStats[Long]

        implicit
        def

        vecToLongRollingStats(s: Vec[Long]): VecRollingStats[Long]

        implicit
        def

        vecToLongStats(s: Vec[Long]): VecStats[Long]

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws()

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws()

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws()

Inherited from AnyRef

Inherited from Any


text:
/**
 * 11.1.42 OrderBy Annotation
 * Table 39
 */
package io.github.jeddict.jpa.orderby;

import jakarta.persistence.Basic;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jGauravGupta
 */
@Entity
public class Student {

    @Id
    private Long id;

    @Basic
    private String firstName;

    @Basic
    private String lastname;

    @ManyToMany(mappedBy = "students")
    private List<Course> courses;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public List<Course> getCourses() {
        if (courses == null) {
            courses = new ArrayList<>();
        }
        return courses;
    }

    public void setCourses(List<Course> courses) {
        this.courses = courses;
    }

    public void addCourse(Course course) {
        getCourses().add(course);
    }

    public void removeCourse(Course course) {
        getCourses().remove(course);
    }

}


text:
package org.openqa.selenium.remote.http;

import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
import static com.google.common.net.MediaType.JSON_UTF_8;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.net.HttpURLConnection.HTTP_CLIENT_TIMEOUT;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.nio.charset.StandardCharsets.UTF_16;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;

import com.google.common.collect.ImmutableMap;

import org.junit.Test;
import org.openqa.selenium.ScriptTimeoutException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.json.Json;
import org.openqa.selenium.remote.Dialect;
import org.openqa.selenium.remote.ErrorCodes;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.remote.Response;

public class JsonHttpResponseCodecTest {

  private final JsonHttpResponseCodec codec = new JsonHttpResponseCodec();

  @Test
  public void convertsResponses_success() {
    Response response = new Response();
    response.setStatus(ErrorCodes.SUCCESS);
    response.setValue(ImmutableMap.of("color", "red"));

    HttpResponse converted = codec.encode(HttpResponse::new, response);
    assertThat(converted.getStatus()).isEqualTo(HTTP_OK);
    assertThat(converted.getHeader(CONTENT_TYPE)).isEqualTo(JSON_UTF_8.toString());

    Response rebuilt = new Json().toType(new String(converted.getContent(), UTF_8), Response.class);

    assertThat(rebuilt.getStatus()).isEqualTo(response.getStatus());
    assertThat(rebuilt.getState()).isEqualTo(new ErrorCodes().toState(response.getStatus()));
    assertThat(rebuilt.getSessionId()).isEqualTo(response.getSessionId());
    assertThat(rebuilt.getValue()).isEqualTo(response.getValue());
  }

  @Test
  public void convertsResponses_failure() {
    Response response = new Response();
    response.setStatus(ErrorCodes.NO_SUCH_ELEMENT);
    response.setValue(ImmutableMap.of("color", "red"));

    HttpResponse converted = codec.encode(HttpResponse::new, response);
    assertThat(converted.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR);
    assertThat(converted.getHeader(CONTENT_TYPE)).isEqualTo(JSON_UTF_8.toString());

    Response rebuilt = new Json().toType(new String(converted.getContent(), UTF_8), Response.class);

    assertThat(rebuilt.getStatus()).isEqualTo(response.getStatus());
    assertThat(rebuilt.getState()).isEqualTo(new ErrorCodes().toState(response.getStatus()));
    assertThat(rebuilt.getSessionId()).isEqualTo(response.getSessionId());
    assertThat(rebuilt.getValue()).isEqualTo(response.getValue());
  }

  @Test
  public void roundTrip() {
    Response response = new Response();
    response.setStatus(ErrorCodes.SUCCESS);
    response.setValue(ImmutableMap.of("color", "red"));

    HttpResponse httpResponse = codec.encode(HttpResponse::new, response);
    Response decoded = codec.decode(httpResponse);

    assertThat(decoded.getStatus()).isEqualTo(response.getStatus());
    assertThat(decoded.getSessionId()).isEqualTo(response.getSessionId());
    assertThat(decoded.getValue()).isEqualTo(response.getValue());
  }

  @Test
  public void decodeNonJsonResponse_200() {
    HttpResponse response = new HttpResponse();
    response.setStatus(HTTP_OK);
    response.setContent("{\"foobar\"}".getBytes(UTF_8));

    Response decoded = codec.decode(response);
    assertThat(decoded.getStatus().longValue()).isEqualTo(0);
    assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}");
  }

  @Test
  public void decodeNonJsonResponse_204() {
    HttpResponse response = new HttpResponse();
    response.setStatus(HTTP_NO_CONTENT);

    Response decoded = codec.decode(response);
    assertThat(decoded.getStatus()).isNull();
    assertThat(decoded.getValue()).isNull();
  }

  @Test
  public void decodeNonJsonResponse_4xx() {
    HttpResponse response = new HttpResponse();
    response.setStatus(HTTP_BAD_REQUEST);
    response.setContent("{\"foobar\"}".getBytes(UTF_8));

    Response decoded = codec.decode(response);
    assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.UNKNOWN_COMMAND);
    assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}");
  }

  @Test
  public void decodeNonJsonResponse_5xx() {
    HttpResponse response = new HttpResponse();
    response.setStatus(HTTP_INTERNAL_ERROR);
    response.setContent("{\"foobar\"}".getBytes(UTF_8));

    Response decoded = codec.decode(response);
    assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.UNHANDLED_ERROR);
    assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}");
  }

  @Test
  public void decodeJsonResponseMissingContentType() {
    Response response = new Response();
    response.setStatus(ErrorCodes.SUCCESS);
    response.setValue(ImmutableMap.of("color", "red"));

    HttpResponse httpResponse = new HttpResponse();
    httpResponse.setStatus(HTTP_OK);
    httpResponse.setContent(new Json().toJson(response).getBytes(UTF_8));

    Response decoded = codec.decode(httpResponse);
    assertThat(decoded.getStatus()).isEqualTo(response.getStatus());
    assertThat(decoded.getSessionId()).isEqualTo(response.getSessionId());
    assertThat(decoded.getValue()).isEqualTo(response.getValue());
  }

  @Test
  public void decodeUtf16EncodedResponse() {
    HttpResponse httpResponse = new HttpResponse();
    httpResponse.setStatus(200);
    httpResponse.setHeader(CONTENT_TYPE, JSON_UTF_8.withCharset(UTF_16).toString());
    httpResponse.setContent("{\"status\":0,\"value\":\"水\"}".getBytes(UTF_16));

    Response response = codec.decode(httpResponse);
    assertThat(response.getValue()).isEqualTo("水");
  }

  @Test
  public void decodeJsonResponseWithTrailingNullBytes() {
    HttpResponse response = new HttpResponse();
    response.setStatus(HTTP_OK);
    response.setContent("{\"status\":0,\"value\":\"foo\"}\0\0".getBytes(UTF_8));

    Response decoded = codec.decode(response);
    assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.SUCCESS);
    assertThat(decoded.getValue()).isEqualTo("foo");
  }

  @Test
  public void shouldConvertElementReferenceToRemoteWebElement() {
    HttpResponse response = new HttpResponse();
    response.setStatus(HTTP_OK);
    response.setContent(new Json().toJson(ImmutableMap.of(
        "status", 0,
        "value", ImmutableMap.of(Dialect.OSS.getEncodedElementKey(), "345678"))).getBytes(UTF_8));

    Response decoded = codec.decode(response);
    assertThat(((RemoteWebElement) decoded.getValue()).getId()).isEqualTo("345678");
  }

  @Test
  public void shouldAttemptToConvertAnExceptionIntoAnActualExceptionInstance() {
    Response response = new Response();
    response.setStatus(ErrorCodes.ASYNC_SCRIPT_TIMEOUT);
    WebDriverException exception = new ScriptTimeoutException("I timed out");
    response.setValue(exception);

    HttpResponse httpResponse = new HttpResponse();
    httpResponse.setStatus(HTTP_CLIENT_TIMEOUT);
    httpResponse.setContent(new Json().toJson(response).getBytes(UTF_8));

    Response decoded = codec.decode(httpResponse);
    assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.ASYNC_SCRIPT_TIMEOUT);

    WebDriverException seenException = (WebDriverException) decoded.getValue();
    assertThat(seenException.getClass()).isEqualTo(exception.getClass());
    assertThat(seenException.getMessage().startsWith(exception.getMessage())).isTrue();
  }
}


text:
Given(/^a social media service "([^"]*)"$/) do |name|
  create(:social_media_service, name:)
end

When(/^I add a "([^"]*)" social media link "([^"]*)" to the (worldwide organisation|organisation)$/) do |social_service, url, social_container|
  if social_container == "worldwide organisation"
    visit admin_worldwide_organisation_path(WorldwideOrganisation.last)
  else
    visit admin_organisation_path(Organisation.last)
  end
  click_link "Social media accounts"
  click_link "Add"
  select social_service, from: "Service"
  fill_in "Url", with: url
  click_on "Save"
end

When(/^I add a "([^"]*)" social media link "([^"]*)" with the title "([^"]+)" to the (worldwide organisation|organisation)$/) do |social_service, url, title, social_container|
  if social_container == "worldwide organisation"
    visit admin_worldwide_organisation_path(WorldwideOrganisation.last)
  else
    visit admin_organisation_path(Organisation.last)
  end
  click_link "Social media accounts"
  click_link "Add"
  select social_service, from: "Service"
  fill_in "Url", with: url
  fill_in "Title", with: title
  click_on "Save"
end

When(/^I edit a "([^"]*)" social media link "([^"]*)" with the title "([^"]+)" in "([^"]*)" for the (worldwide organisation|organisation)$/) do |_social_service, url, title, language, social_container|
  if social_container == "worldwide organisation"
    visit admin_worldwide_organisation_path(WorldwideOrganisation.last)
  else
    visit admin_organisation_path(Organisation.last)
  end
  click_link "Social media accounts"
  click_link "Edit #{language}"
  fill_in "Url", with: url
  fill_in "Title", with: title
  click_on "Save"
end

Then(/^the "([^"]*)" social link should be shown on the public website for the (worldwide organisation|organisation)$/) do |social_service, social_container|
  if social_container == "worldwide organisation"
    social_container = WorldwideOrganisation.last
    visit worldwide_organisation_path(social_container)
  else
    social_container = Organisation.last
    visit organisation_path(social_container)
  end
  expect(page).to have_selector(".gem-c-share-links .gem-c-share-links__link[data-track-action=\"#{social_service.parameterize}\"]", text: social_service)
end

Then(/^the "([^"]*)" social link called "([^"]+)" should be shown on the public website for the (worldwide organisation|organisation)$/) do |social_service, title, social_container|
  if social_container == "worldwide organisation"
    social_container = WorldwideOrganisation.last
    visit worldwide_organisation_path(social_container)
  else
    social_container = Organisation.last
    visit organisation_path(social_container)
  end
  expect(page).to have_selector(".gem-c-share-links .gem-c-share-links__link[data-track-action=\"#{social_service.parameterize}\"]", text: title)
end

Then(/^the "([^"]*)" social link called "([^"]+)" should be shown on the public website with locale "([^"]*)" for the (worldwide organisation|organisation)$/) do |social_service, title, locale, social_container|
  if social_container == "worldwide organisation"
    social_container = WorldwideOrganisation.last
    visit worldwide_organisation_path(social_container, locale:)
  else
    social_container = Organisation.last
    visit organisation_path(social_container, locale:)
  end
  expect(page).to have_selector(".gem-c-share-links .gem-c-share-links__link[data-track-action=\"#{social_service.parameterize}\"]", text: title)
end


text:
PicoFeed
========

This library is **not maintained anymore**.

Features
--------

- Simple and fast
- Feed parser for Atom 1.0 and RSS 0.91, 0.92, 1.0 and 2.0
- Feed writer for Atom 1.0 and RSS 2.0
- Favicon fetcher
- Import/Export OPML subscriptions
- Content filter: HTML cleanup, remove pixel trackers and Ads
- Multiple HTTP client adapters: cURL or Stream Context
- Proxy support
- Content grabber: download from the original website the full content
- Enclosure detection
- RTL languages support
- License: MIT

Requirements
------------

- PHP >= 5.3
- libxml >= 2.7
- XML PHP extensions: DOM and SimpleXML
- cURL or Stream Context (`allow_url_fopen=On`)
- iconv extension

Documentation
-------------

- [Installation](docs/installation.markdown)
- [Running unit tests](docs/tests.markdown)
- [Feed parsing](docs/feed-parsing.markdown)
- [Feed creation](docs/feed-creation.markdown)
- [Favicon fetcher](docs/favicon.markdown)
- [OPML](docs/opml.markdown)
- [Image proxy](docs/image-proxy.markdown) (avoid SSL mixed content warnings)
- [Web scraping](docs/grabber.markdown)
- [Exceptions](docs/exceptions.markdown)
- [Debugging](docs/debugging.markdown)
- [Configuration](docs/config.markdown)


text:
namespace SchoolClasses
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    public class Student : People
    {
        private int uniqueClassNumber;

        public Student(string name, int uniqueClassNumber)
            : base(name)
        {
            this.UniqueClassNumber = uniqueClassNumber;
        }

        public int UniqueClassNumber
        {
            get
            {
                return this.uniqueClassNumber;
            }
            private set
            {
                this.uniqueClassNumber = value;
            }
        }

        public override string ToString()
        {
            StringBuilder result = new StringBuilder();

            result.AppendLine(base.ToString() + string.Format(" Class number: {0};", this.uniqueClassNumber));
            result.AppendLine("Student comment: " + this.Comment);
            return result.ToString();
        }

    }
}


text:
parsl.channels.LocalChannel
===========================

.. currentmodule:: parsl.channels

.. autoclass:: LocalChannel

   .. automethod:: __init__

   .. rubric:: Methods

   .. autosummary::

      ~LocalChannel.__init__
      ~LocalChannel.abspath
      ~LocalChannel.close
      ~LocalChannel.execute_no_wait
      ~LocalChannel.execute_wait
      ~LocalChannel.isdir
      ~LocalChannel.makedirs
      ~LocalChannel.push_file

   .. rubric:: Attributes

   .. autosummary::

      ~LocalChannel.script_dir


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="1">
        <file>
            <url>src/dashnet/Client.java</url>
            <bookmark id="1">
                <name/>
                <line>42</line>
                <key/>
            </bookmark>
        </file>
    </editor-bookmarks>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group/>
    </open-files>
</project-private>


text:
<!DOCTYPE html>
<div style="position: absolute; top: 150px; left: 100px;
            width: 100px; height: 100px; background: blue">
</div>


text:
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>

	<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
	<title>boost/qvm/vec_access.hpp</title>
	<link href='reno.css' type='text/css' rel='stylesheet'/>

QVM: Quaternions, Vectors, Matrices

boost/qvm/vec_access.hpp

This header provides generic access to the elements of a given vector object.

Synopsis:

#include <boost/qvm/vec_access.hpp>

namespace boost
{
    namespace qvm
    {
        //Only enabled if:
        //  is_vec<V>::value

        template <int I,class V> -unspecified-return-type- A( V & v );
        template <class V> -unspecified-return-type- A0( V & v );
        template <class V> -unspecified-return-type- A1( V & v );
        ...
        template <class V> -unspecified-return-type- A9( V & v );

        template <class V> -unspecified-return-type- X( V & v );
        template <class V> -unspecified-return-type- Y( V & v );
        template <class V> -unspecified-return-type- Z( V & v );
        template <class V> -unspecified-return-type- W( V & v );
    }
}

See also: Accessing Vector Elements

Copyright (c) 2008-2016 by Emil Dotchevski and Reverge Studios, Inc.

Distributed under the Boost Software License, Version 1.0.


text:
<!DOCTYPE HTML>

    <title>Hello World! - AW Labs Blog</title>
<meta charset="utf-8" />
<meta name="description" content="Hello World! Vestibulum imperdiet adipiscing arcu, quis aliquam dolor condimentum dapibus. Aliquam fermentum leo aliquet quam volutpat et molestie mauris mattis. Suspendisse semper consequat velit in suscipit." />
<meta name="viewport" content="width=device-width, initial-scale=1" />

<link rel="stylesheet" href="/assets/css/main.css" />

<link rel="alternate" type="application/atom+xml" href="/atom.xml" title="Sitewide ATOM Feed" />
<link rel="alternate" type="application/rss+xml" href="/rss.xml" title="Sitewide RSS Feed" />
<link rel="author" type="text/plain" href="/humans.txt" />

<meta property="og:type" content="article" />
<meta property="og:title" content="Hello World!" />
<meta property="og:description" content="Hello World! Vestibulum imperdiet adipiscing arcu, quis aliquam dolor condimentum dapibus. Aliquam fermentum leo aliquet quam volutpat et molestie mauris mattis. Suspendisse semper consequat velit in suscipit." />
<meta property="og:site_name" content="AW Labs Blog" />
<meta property="og:url" content="/meta/2012/01/18/hello-world.html" />

<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@#" />
<meta name="twitter:title" content="Hello World!" />
<meta name="twitter:description" content="Hello World! Vestibulum imperdiet adipiscing arcu, quis aliquam dolor condimentum dapibus. Aliquam fermentum leo aliquet quam volutpat et molestie mauris mattis. Suspendisse semper consequat velit ..." />

I am Akhil, a mobile and web developer. This is my personal blog where I write about technology and software development. I run my own indie development lab, AW Labs and am a cofounder of Synapps LLC.

Hello World!

             18 January 2012 on  Meta.

   1 minute

Hello World!

This is just a sample post.

Vestibulum imperdiet adipiscing arcu, quis aliquam dolor condimentum dapibus. Aliquam fermentum leo aliquet quam volutpat et molestie mauris mattis. Suspendisse semper consequat velit in suscipit. Praesent blandit, mi id facilisis adipiscing, tortor tellus mollis quam, sed dignissim sapien diam ac lectus. Nunc eget ornare quam. Vivamus sit amet tortor dolor, non egestas ligula. Mauris nisi risus, semper nec blandit id, suscipit eget dolor. Sed placerat odio at erat porttitor varius. Phasellus ornare vestibulum dolor ac rhoncus. Mauris laoreet varius est eu rhoncus. Curabitur facilisis mauris eu purus pharetra vitae tincidunt nulla gravida. Duis sagittis, felis a luctus mattis, metus sem tempus velit, sit amet blandit tellus nisi id augue.

Proin feugiat libero ac lorem mollis fermentum. Cras et lacus sodales nisl facilisis ornare. Sed dolor eros, pulvinar ac varius non, bibendum eget odio. Nulla facilisi. Pellentesque et nisi a tellus ullamcorper faucibus. Nullam sagittis tempor mi non mattis. Proin ultricies, enim sit amet bibendum tristique, ligula ante feugiat nunc, sit amet imperdiet tortor nisl et felis. Pellentesque et nisl dui, non dictum libero. Vivamus tempor ante ac leo suscipit a sodales ligula iaculis. Curabitur massa mi, semper sed bibendum eget, auctor in nulla. Quisque at mi in ligula viverra suscipit sed vitae leo.

Next

Code Snippets

Quick overview on how to post code snippets using Liquid tags and how to escape or not escape markdown and HTML in your blog entries.

Twitter

Linkedin

Github

Email

Feed

© AW Labs

Design: HTML5 UP


text:
using System;
using NServiceBus;

#region message-definitions

[Serializable]
[SerializeWithBinary]
public class MessageWithBinary : IMessage
{
    public string SomeProperty { get; set; }
}

[SerializeWithJson]
public class MessageWithJson : IMessage
{
    public string SomeProperty { get; set; }
}

#endregion


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 io.trino.plugin.oracle;

import com.google.inject.Binder;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import com.google.inject.Singleton;
import io.trino.plugin.jdbc.BaseJdbcConfig;
import io.trino.plugin.jdbc.ConnectionFactory;
import io.trino.plugin.jdbc.DriverConnectionFactory;
import io.trino.plugin.jdbc.ForBaseJdbc;
import io.trino.plugin.jdbc.JdbcClient;
import io.trino.plugin.jdbc.MaxDomainCompactionThreshold;
import io.trino.plugin.jdbc.RetryingConnectionFactory;
import io.trino.plugin.jdbc.credential.CredentialProvider;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleDriver;

import java.sql.SQLException;
import java.util.Properties;

import static com.google.inject.multibindings.OptionalBinder.newOptionalBinder;
import static io.airlift.configuration.ConfigBinder.configBinder;
import static io.trino.plugin.jdbc.JdbcModule.bindSessionPropertiesProvider;
import static io.trino.plugin.oracle.OracleClient.ORACLE_MAX_LIST_EXPRESSIONS;

public class OracleClientModule
        implements Module
{
    @Override
    public void configure(Binder binder)
    {
        binder.bind(JdbcClient.class).annotatedWith(ForBaseJdbc.class).to(OracleClient.class).in(Scopes.SINGLETON);
        bindSessionPropertiesProvider(binder, OracleSessionProperties.class);
        configBinder(binder).bindConfig(OracleConfig.class);
        newOptionalBinder(binder, Key.get(int.class, MaxDomainCompactionThreshold.class)).setBinding().toInstance(ORACLE_MAX_LIST_EXPRESSIONS);
    }

    @Provides
    @Singleton
    @ForBaseJdbc
    public static ConnectionFactory connectionFactory(BaseJdbcConfig config, CredentialProvider credentialProvider, OracleConfig oracleConfig)
            throws SQLException
    {
        Properties connectionProperties = new Properties();
        connectionProperties.setProperty(OracleConnection.CONNECTION_PROPERTY_INCLUDE_SYNONYMS, String.valueOf(oracleConfig.isSynonymsEnabled()));
        connectionProperties.setProperty(OracleConnection.CONNECTION_PROPERTY_REPORT_REMARKS, String.valueOf(oracleConfig.isRemarksReportingEnabled()));

        if (oracleConfig.isConnectionPoolEnabled()) {
            return new OraclePoolConnectionFactory(
                    config.getConnectionUrl(),
                    connectionProperties,
                    credentialProvider,
                    oracleConfig.getConnectionPoolMinSize(),
                    oracleConfig.getConnectionPoolMaxSize(),
                    oracleConfig.getInactiveConnectionTimeout());
        }

        return new RetryingConnectionFactory(new DriverConnectionFactory(
                new OracleDriver(),
                config.getConnectionUrl(),
                connectionProperties,
                credentialProvider));
    }
}


text:
package it.mrbigs;

import java.math.BigInteger;

/**
 * Created by Simone on 29/03/2015.
 */
public class Problem39 implements Problem {

    private static final int LIMIT = 1000;

    @Override
    public BigInteger solve() {
        int maxSolutions = 0;
        int bestPerimeter = 0;
        for (int perimeter = 0; perimeter <= LIMIT; perimeter++) {
            int nSolutions = 0;
            for (int cat1 = 1; cat1 < perimeter - 2; cat1++) {
                for (int cat2 = 1; cat2 < perimeter - 2; cat2++) {
                    int hyp = perimeter - cat1 - cat2;
                    if ((cat1 * cat1) + (cat2 * cat2) - (hyp * hyp) == 0) {
                        nSolutions++;
                    }
                }
            }
            if (nSolutions > maxSolutions) {
                maxSolutions = nSolutions;
                bestPerimeter = perimeter;
            }
        }
        return new BigInteger(String.valueOf(bestPerimeter));
    }
}