text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.switchtrue.jira.changelog;

import java.util.HashMap;
import java.util.List;
import java.io.Writer;
import java.io.IOException;
import java.io.StringWriter;
import com.github.mustachejava.*;
import java.io.File;

/**
 * Incorporates the base logic for Mustache templates for changelogs saved as
 * either a file or into a FOX module.
 *
 * @author apigram
 * @version 1.03.00
 */
public class ChangelogTemplate {

  static HashMap<String, Object> scopes = new HashMap<String, Object>();
  static String LF;
  static String fileRoot;

  /**
   * Generate and output a changelog based off a template file.
   *
   * @param isFile If the changelog is for a file, set this parameter to true.
   * Otherwise, set this parameter to false.
   * @param issues A collection of JIRA issues with an identifier and changelog
   * description.
   * @param version The build version.
   * @param output The output stream.
   * @param templateFile The template file to use when generating the changelog.
   * @param ending A value indicating the kind of newlines to be used in the
   * changelog file.
   * @param templateFile The filename of the template file to use.
   */
  public static void createChangelog(List<VersionInfo> versions, Writer output, String templateFile, LineEnding ending) {
    StringWriter out = new StringWriter();
    String buffer = null; // templated file content. This buffer is used to convert the line endings.
    MustacheFactory mf = new DefaultMustacheFactory(new File(fileRoot));
    Mustache template = mf.compile(templateFile);

    // assemble the JSON hash map
    scopes.put("versions", versions);

    // Compile the required template and generate some output. This output will
    // either be piped to a file or copied into a FOX module.

    template.execute(out, scopes);

    // grab the merged string
    buffer = out.toString();
    out.flush();

    // convert line endings accordingly, then output to the output stream
    switch (ending) {
      case WINDOWS:
        // use Windows method of newlines
        buffer = buffer.replace("\n", "\r\n");
        break;
      case NIX:
        // use UNIX method of newlines
        buffer = buffer.replace("\r\n", "\n");
        break;
      default:
        // use system method of newlines
        LF = System.getProperty("line.separator");
        buffer = buffer.replaceAll("\r?\n", LF);
        break;
    }
    try {
      output.write(buffer);
      output.flush();
    } catch (IOException e) {
      // leave blank as file will not exist
    }
  }
}


text:
title: 'Avril Consulting, Project POC'
date: '14:55 08/10/2016'
taxonomy:
    category:
        - blog
    tag:
        - avril
        - project
---

 So what do we (or I in this case) actually do here ?
Well, my first assignment was a Proof of concept for a client.

###The problem

Let me explain the use case, the client sells a lot of products by *drop shipping* from different sources, drop shipping means they don't stock any products they only resale the products provided by their partners.

As you can imagine this means multiple streams of products to import from their partners and then to export to their different web shops, marketplaces, etc.

Traditionally product catalogues were organised using Excel spreadsheets imported into the database, this can quickly become unmanageable when handling large volumes of products and even more so when using multiple sources for the import.

Another inherent problem with this method is completeness or lack thereof, indeed it is estimated the half of the product information online is incomplete or wrong.

###The solution

![](solution.jpeg?resize=150)![](b_akeneo.png?resize=150)

they asked me to put together a demo that addresses this problem, a **P**roduct **I**nformation **M**anager was the answer.
More specifically **Akeneo**, an open source **PIM** based on **Symfony**.
The first order of business was to import the excel files, therefore a connector that takes the input and *cleans* it to a format the PIM can work with needed to be created.
Then we needed a way to map the categories of the imported products to the categories created by the end user so that it is easy to organise the products the way he wants to, some more backend development was needed aswell as an interface to set the different options for the import. The last step was the export, a special connector needed to be developed as well as another interface to manage which products to export to which shop.

The clients web shops use **Prestashop** (an e-commerce framework) so a module needed to be created to import the files created by **Akeneo** as well as some configuration options.

With this the POC was done, we also explored some *cron* configurations to run the import and export on a schedule instead of starting them manually.

The stressful moment came when it was time to demo the POC to the client because as we all know that's when random bugs start to appear, fortunately enough everything went smoothly and the client was happy with the proposal.

That was the first assignment I worked on and if you want some more technical details you can download the technical documentation I wrote up here (in french) :
* [Prestashop module](AkeneoImport%20Prestashop%20Module.pdf)
* [Akeneo bundles](Akeneo%20POC%20Bundles.pdf)
* [Akeneo functionality](Akeneo%20POC%20fonctionnalit%C3%A9s.pdf)

redpajama_set_name: RedPajamaGithub


text:
using namespace std;

int main(){
	AFS myFs(20<<20);

	//myFs.format();
	perror("test complete.\n");

	//prompt user to input
	string args;
	cout<<">";
	while (getline(cin,args)){
		#ifdef DEGB
			cout<<"Command received: "<<args<<endl;
		#endif
		if (args=="exit") exit(0);
		myFs.process_command(args);
		cout<<">";
	}
}


text:
module MachineTests
  class HtmlRunner < Test::Unit::UI::Console::TestRunner
    def finished(elapsed_time)

    end
  end
end


text:
# FlycoTabLayout
[![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-FlycoTabLayout-green.svg?style=true)](https://android-arsenal.com/details/1/2756)
#### [中文版](https://github.com/H07000223/FlycoTabLayout/blob/master/README_CN.md)
An Android TabLayout Lib has 3 kinds of TabLayout at present.

* SlidingTabLayout: deeply modified from [PagerSlidingTabStrip](https://github.com/jpardogo/PagerSlidingTabStrip).
    * new added attribute
    * new added kinds of indicators
    * new added unread msg tip
    * new added method for convenience

    ```java
        /** no need to set titles in adapter */
        public void setViewPager(ViewPager vp, String[] titles)

        /** no need to initialize even adapter */
        public void setViewPager(ViewPager vp, String[] titles, FragmentActivity fa, ArrayList<Fragment> fragments)
    ```

* CommonTabLayout:unlike SlidingTabLayout's dependence on ViewPager,it is a tabLayout without dependence on ViewPager and
can be used freely with other widgets together.
    * support kinds of indicators and indicator animation
    * support unread msg tip
    * support icon and icon gravity.
    * new added method for convenience

    ```java
        /** support switch fragments itself */
        public void setTabData(ArrayList<CustomTabEntity> tabEntitys, FragmentManager fm, int containerViewId, ArrayList<Fragment> fragments)
    ```

* SegmentTabLayout

## Demo
![](https://github.com/H07000223/FlycoTabLayout/blob/master/preview_1.gif)

![](https://github.com/H07000223/FlycoTabLayout/blob/master/preview_2.gif)

![](https://github.com/H07000223/FlycoTabLayout/blob/master/preview_3.gif)

>## Change Log

 > v2.0.0(2016-03-01)
   - remove the dependence of FlycoRoundView
   - new added method getIconView and getTitleView

 > v2.0.2(2016-04-23)
   - remove the dependence of NineOldAnimation(only support 3.0+)

## Gradle

```groovy
dependencies{
    compile 'com.android.support:support-v4:23.1.1'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.flyco.roundview:FlycoRoundView_Lib:1.1.2@aar'
    compile 'com.flyco.tablayout:FlycoTabLayout_Lib:1.5.0@aar'
}

After v2.0.0
dependencies{
    compile 'com.android.support:support-v4:23.1.1'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.flyco.tablayout:FlycoTabLayout_Lib:2.0.0@aar'
}

After v2.0.2(support 3.0+)
dependencies{
    compile 'com.android.support:support-v4:23.1.1'
    compile 'com.flyco.tablayout:FlycoTabLayout_Lib:2.1.2@aar'
}
```

## Attributes

|name|format|description|
|:---:|:---:|:---:|
| tl_indicator_color | color |set indicator color
| tl_indicator_height | dimension |set indicator height
| tl_indicator_width | dimension |set indicator width
| tl_indicator_margin_left | dimension |set indicator margin,invalid when indicator width is greater than 0.
| tl_indicator_margin_top | dimension |set indicator margin,invalid when indicator width is greater than 0.
| tl_indicator_margin_right | dimension |set indicator margin,invalid when indicator width is greater than 0.
| tl_indicator_margin_bottom | dimension |set indicator margin,invalid when indicator width is greater than 0.
| tl_indicator_corner_radius | dimension |set indicator corner radius
| tl_indicator_gravity | enum |set indicator gravity TOP or BOTTOM.
| tl_indicator_style | enum |set indicator style NORMAL or TRIANGLE or BLOCK
| tl_underline_color | color |set underline color
| tl_underline_height | dimension |set underline height
| tl_underline_gravity | enum |set underline gravity TOP or BOTTOM
| tl_divider_color | color |set divider color
| tl_divider_width | dimension |set divider width
| tl_divider_padding |dimension| set divider paddingTop and paddingBottom
| tl_tab_padding |dimension| set tab paddingLeft and paddingRight
| tl_tab_space_equal |boolean| set tab space equal
| tl_tab_width |dimension| set tab width
| tl_textsize |dimension| set text size
| tl_textSelectColor |color| set text select color
| tl_textUnselectColor |color|  set text unselect color
| tl_textBold |boolean| set text is bold
| tl_iconWidth |dimension| set icon width(only for CommonTabLayout)
| tl_iconHeight |dimension|set icon height(only for CommonTabLayout)
| tl_iconVisible |boolean| set icon is visible(only for CommonTabLayout)
| tl_iconGravity |enum| set icon gravity LEFT or TOP or RIGHT or BOTTOM(only for CommonTabLayout)
| tl_iconMargin |dimension| set icon margin with text(only for CommonTabLayout)
| tl_indicator_anim_enable |boolean| set indicator support animation(only for CommonTabLayout)
| tl_indicator_anim_duration |integer| set indicator animation duration(only for CommonTabLayout)
| tl_indicator_bounce_enable |boolean| set indicator aniamtion with bounce effect(only for CommonTabLayout)
| tl_indicator_width_equal_title |boolean| set indicator width same as text(only for SlidingTabLayout)

## Dependence
*   [NineOldAndroids](https://github.com/JakeWharton/NineOldAndroids)
*   [FlycoRoundView](https://github.com/H07000223/FlycoRoundView)

## Thanks
*   [PagerSlidingTabStrip](https://github.com/jpardogo/PagerSlidingTabStrip)


text:
<?php

namespace Service;

use Zend\EventManager\EventInterface;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\Mvc\MvcEvent;

class Module implements AutoloaderProviderInterface, BootstrapListenerInterface, ConfigProviderInterface
{

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function onBootstrap(EventInterface $e)
    {
        $events = $e->getApplication()->getEventManager();
        $events->attach(MvcEvent::EVENT_ROUTE, array($this, 'onDispatch'));
    }

    public function onDispatch(MvcEvent $e)
    {
        $serviceManager = $e->getApplication()->getServiceManager();
        $optionManager = $serviceManager->get('Base\Manager\OptionManager');

        if ($optionManager->get('service.maintenance', 'false') == 'true') {
            $userSessionManager = $serviceManager->get('User\Manager\UserSessionManager');

            /* If any non admin user is currently online, kick him off. */

            $user = $userSessionManager->getSessionUser();

            if ($user) {
                if ($user->need('status') == 'admin') {
                    return;
                }

                $userSessionManager->logout();
            }

            /* Redirect all routes except login to the system status page. */

            $routeMatch = $e->getRouteMatch();

            if (! ($routeMatch->getParam('controller') == 'User\Controller\Session' && $routeMatch->getParam('action') == 'login')) {
                $routeMatch->setParam('controller', 'Service\Controller\Service');
                $routeMatch->setParam('action', 'status');
            }
        }
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

}


text:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace TABS_UserControls.usercontrols
{
      public partial class asiaThisYearFairs : System.Web.UI.UserControl
      {
            //private TABS_UserControls.resources.code.BAL.FairClass displayFairs = new TABS_UserControls.resources.code.BAL.FairClass();
            //protected void Page_Load(object sender, EventArgs e)
            //{
            //      repFairs.DataSource = displayFairs.GetActiveFairByYear(DateTime.Now.Year.ToString());
            //      //DataTable dt = displayFairs.GetAllFairsData();
            //      //for (int i = 0; i < dt.Rows.Count; i++)
            //      //{
            //      //      dt.Rows[i]["date"].ToString();
            //      //}
            //      repFairs.DataBind();
            //}

            //public string returnDate(string date)
            //{
            //      DateTime bbb = Convert.ToDateTime(date);
            //      return bbb.Day.ToString();
            //}

            //public string GetCultureDay(string date)
            //{
            //      return System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DayNames[(int)(Convert.ToDateTime(date)).DayOfWeek];
            //      //return "bozo";
            //}
            //public string GetCultureMonth(string date)
            //{
            //      return System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[(int)(Convert.ToDateTime(date)).DayOfWeek];
            //}
      }
}


text:
(function() {
  var api_actions, boot_compute_service, boot_console_service, bootloader, compute_receive_messages, connect_to_broker, disconnect_from_broker, punk, read_options, start_rest_app, util;

  util = require("util");

  punk = {};

  punk.log = function(msg) {
    var ts;
    ts = new Date();
    return console.log("[punk] " + ts + " : " + msg);
  };

  punk.pass = function(sock, obj) {
    return sock.write(JSON.stringify(obj), 'utf8');
  };

  punk.receive = function(sock) {
    var raw_msg;
    raw_msg = sock.read();
    if (raw_msg) {
      return JSON.parse(raw_msg);
    } else {
      return false;
    }
  };

  compute_receive_messages = function(sub) {
    var obj, _results;
    punk.log("Receiving some messages");
    _results = [];
    while (obj = punk.receive(sub)) {
      _results.push(punk.log(obj));
    }
    return _results;
  };

  boot_compute_service = function(ctx) {
    var sub;
    punk.log("Booting Compute Service");
    sub = ctx.socket('SUBSCRIBE');
    return sub.connect('compute', function() {
      punk.log("Subscribed to compute topic");
      return sub.on('readable', function() {
        punk.log("Subscription topic is readable");
        return compute_receive_messages(sub);
      });
    });
  };

  api_actions = {};

  api_actions.load_client = function(req, res, pub) {
    punk.log("Responding to /");
    return res.send('Hello World!');
  };

  api_actions.ping = function(req, res, pub) {
    punk.log("Responding to /ping");
    punk.pass(pub, {
      pid: process.pid,
      text: 'ping'
    });
    return res.send('Pinged e\'rbody!');
  };

  boot_console_service = function(ctx) {
    var pub;
    punk.log("Booting Console Service");
    pub = ctx.socket('PUBLISH');
    return pub.connect('compute', function() {
      return start_rest_app(pub);
    });
  };

  start_rest_app = function(pub) {
    var app, express, server;
    punk.log("Starting Rest app");
    express = require("express");
    app = express();
    app.get('/', function(req, res) {
      return api_actions.load_client(req, res, pub);
    });
    app.get('/ping', function(req, res) {
      return api_actions.ping(req, res, pub);
    });
    return server = app.listen(3000, function() {
      var host, msg, port;
      host = server.address().address;
      port = server.address().port;
      msg = util.format('Console service listening at http://%s:%s', host, port);
      return punk.log(msg);
    });
  };

  disconnect_from_broker = function(ctx) {
    punk.log("disconnecting from broker");
    return ctx.close();
  };

  connect_to_broker = function(callback, address) {
    var broker_uri, context;
    if (address == null) {
      address = "localhost";
    }
    broker_uri = "amqp://" + address;
    punk.log("connecting to message broker at " + broker_uri);
    context = require('rabbit.js').createContext(broker_uri);
    context.on('ready', function() {
      return callback(context);
    });
    context.on('error', function(msg) {
      return punk.log(util.format("Broker Context Error (%s)", msg));
    });
    return process.on('SIGINT', function() {
      return disconnect_from_broker(context);
    });
  };

  read_options = function() {
    var argv;
    punk.log("reading command line options");
    argv = require("argv");
    argv.info(' Punk. Invoke with console or compute ');
    argv.version("0.0.0");
    argv.option({
      name: "amqp-broker",
      short: "b",
      type: "string"
    });
    argv.option({
      name: "http-port",
      short: "p",
      type: "int"
    });
    return argv.run();
  };

  bootloader = function() {
    var args, mode;
    punk.log("booting");
    args = read_options();
    mode = args["targets"][0];
    if (mode === "compute") {
      return connect_to_broker(boot_compute_service);
    } else if (mode === "console") {
      return connect_to_broker(boot_console_service);
    } else {
      return punk.log("You gotta tell me compute or console");
    }
  };

  bootloader();

}).call(this);


text:
//  *************************************************************
// <copyright file="IntegerExtension.cs" company="None">
//     Copyright (c) 2014 andy. All rights reserved.
// </copyright>
// <license>MIT Licence</license>
// <author>andy</author>
// <email>andy.augustin@t-online.de</email>
// *************************************************************

namespace GenericMath.Base.Contracts
{
    using System;
    using System.Diagnostics;
    using System.Linq.Expressions;
    using System.Reflection;

    /// <summary>
    /// Extension Methods for the Integer class.
    /// </summary>
    public static class IntegerExtension
    {
        #region METHODS

        /// <summary>
        /// Calculates the gcd (greatest common divisor) with the euclidian algorithm.
        /// </summary>
        /// <returns>The gcd of a and b.</returns>
        /// <param name="a">The alpha component.</param>
        /// <param name="b">The blue component.</param>
        /// <returns>The gcd of a and b</returns>
        public static int EuclidianAlgorithm (this int a, int b)
        {
            int gcd;
            a = Math.Abs(a);
            b = Math.Abs(b);

            while (b != 0) {
                gcd = a % b;
                a = b;
                b = gcd;
            }

            gcd = a;
            return gcd;
        }

        /// <summary>
        /// Extends the euclidian algorithm.
        /// It also calculates x,y.
        /// gcd(a,b) = a * x + b * y.
        /// </summary>
        /// <returns>The euclidian algorithm.</returns>
        /// <param name="a">The alpha component.</param>
        /// <param name="b">The blue component.</param>
        /// <param name="x">The x coordinate.</param>
        /// <param name="y">The y coordinate.</param>
        /// <returns>The gcd of a and b</returns>
        public static int ExtendedEuclidianAlgorithm (
            this int a,
            int b,
            out int x,
            out int y)
        {
            int q;
            int r;
            int xx;
            int yy;
            int gcd = 0;
            int sign = 1;
            var xs = new int[2];
            var ys = new int[2];

            xs[0] = 1;
            xs[1] = 0;
            ys[0] = 0;
            ys[1] = 1;

            // till b != 0 a = b, b = a%b
            // calculate coefficients
            while (b != 0) {
                r = a % b;
                q = a / b;
                a = b;
                b = r;
                xx = xs[1];
                yy = ys[1];
                xs[1] = (q * xs[1]) + xs[0];
                ys[1] = (q * ys[1]) + ys[0];
                xs[0] = xx;
                ys[0] = yy;
                sign = -sign;
            }

            // calculate coefficients
            x = sign * xs[0];
            y = -sign * ys[0];

            gcd = a;

            return gcd;
        }

        /// <summary>
        /// Calculates the chinese rest term algorithm.
        /// Calculates a solution for the equation
        /// result = x[0] mod moduli[0]
        /// result = x[1] mod moduli[1]
        /// .....
        /// result = x[n] mod moduli[n]
        /// It needs to be true that gcd(moduli) = 1
        /// </summary>
        /// <returns>The rest term.</returns>
        /// <param name="moduli">The moduli.</param>
        /// <param name="x">The parameters.</param>
        /// <returns>The solution for the equation posted above.</returns>
        public static int ChineseRestTerm (this int[] moduli, int[] x)
        {
            if (moduli.Length != x.Length) {
                throw new IndexOutOfRangeException("The index for the moduli and the x do not agree");
            }

            var multipliers = new int[moduli.Length];
            var result = 0;
            var modulus = ChineseRestTermHelper(moduli, ref multipliers);
            for (var i = 0; i < moduli.Length; i++) {
                result = (result + (multipliers[i] * x[i])) % modulus;
            }

            return result;
        }

        #endregion

        #region HELPER METHODS

        private static int ChineseRestTermHelper (
            int[] moduli,
            ref int[] multipliers)
        {
            var modulus = 1;

            // calculate the modulus (the product of all moduli)
            for (var i = 0; i < moduli.Length; i++) {
                modulus *= moduli[i];
            }

            var m = 0;
            var inverse = 0;
            var gcd = 0;
            var y = 0;

            for (var i = 0; i < moduli.Length; i++) {
                m = modulus / moduli[i];

                gcd = m.ExtendedEuclidianAlgorithm(
                    moduli[i],
                    out inverse,
                    out y);
                if (gcd != 1) {
                    throw new InvalidOperationException("gcd(moduli) != 1"); // TODO find other solution (extend to integer rings)
                }

                multipliers[i] = inverse * (m % modulus);
            }

            return modulus;
        }

        #endregion

        #region DEBUG METHODS

        [Conditional("DEBUG")]
        private static void Checkvariable<T> (Expression<Func<T>> expr) where T : struct
        {
            // Grab name of calling method
            var methodName = new StackTrace().GetFrame(1).GetMethod().Name;

            Console.WriteLine(string.Format("Method: {0}", methodName));
            var body = (MemberExpression)expr.Body;
            Console.WriteLine("Name is: {0}", body.Member.Name);
            Console.WriteLine(
                "Value is: {0}",
                ((FieldInfo)body.Member).GetValue(((ConstantExpression)body.Expression).Value));
        }

        #endregion
    }
}


text:
import numpy as np

from bokeh.models import ColumnDataSource, Plot, LinearAxis, Grid
from bokeh.models.glyphs import Wedge
from bokeh.io import curdoc, show

N = 9
x = np.linspace(-2, 2, N)
y = x**2
r = x/15.0+0.3

source = ColumnDataSource(dict(x=x, y=y, r=r))

plot = Plot(
    title=None, plot_width=300, plot_height=300,
    min_border=0, toolbar_location=None)

glyph = Wedge(x="x", y="y", radius="r", start_angle=0.6, end_angle=4.1, fill_color="#b3de69")
plot.add_glyph(source, glyph)

xaxis = LinearAxis()
plot.add_layout(xaxis, 'below')

yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')

plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

curdoc().add_root(plot)

show(plot)


text:
package slbedu.library.services;

import javax.ejb.EJB;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.ejb.StatefulTimeout;

//each minute remove the unpaid reservations
@Stateful
@StatefulTimeout(1)
public class ReservationSheduler {
	private static final int MINUTES_TO_KEEP_RESERVATION = 10;

	@EJB
	private ReservationService reservationService;

	@Remove
	public void checkout() {
		reservationService.sheduleTemproates(MINUTES_TO_KEEP_RESERVATION);
	}
}


text:
package by.vorokhobko.servletwithuser.servlets;

import by.vorokhobko.servletwithuser.User;
import by.vorokhobko.servletwithuser.UserStore;
import org.junit.Test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Test.
 *
 * @author Evgeny Vorokhobko (vorokhobko2011@yandex.ru).
 * @version 1.
 * @since 18.03.2018.
 */
public class ShowAllElementTest {
    /**
     * The class field.
     */
    private UserStore userStore = UserStore.INSTANCE;
    /**
     * Test Add.
     */
    @Test
    public void whenAddUserInBD() throws IOException {
        CreateServlet create = new CreateServlet();
        this.userStore.createConnection();
        HttpServletResponse response = mock(HttpServletResponse.class);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getParameter("name")).thenReturn("test");
        when(request.getParameter("login")).thenReturn("test");
        when(request.getParameter("email")).thenReturn("test");
        when(request.getParameter("createDate")).thenReturn(String.valueOf(new Timestamp(System.currentTimeMillis())));
        when(request.getParameter("password")).thenReturn("test");
        when(request.getParameter("role")).thenReturn("USER");

        create.doPost(request, response);
        User user = this.userStore.searchLoginAndPassword("test", "test");
        assertThat(user.getLogin(), is("test"));
    }
    /**
     * Test Add.
     */
    @Test
    public void whenUpdateUserInBD() throws IOException {
        UpdateServlet update = new UpdateServlet();
        this.userStore.createConnection();
        List<User> list = this.userStore.findAll();
        HttpServletResponse response = mock(HttpServletResponse.class);
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getParameter("name")).thenReturn("testUpdate");
        when(request.getParameter("login")).thenReturn("testUpdate");
        when(request.getParameter("email")).thenReturn("testUpdate");
        when(request.getParameter("createDate")).thenReturn(String.valueOf(new Timestamp(System.currentTimeMillis())));
        when(request.getParameter("password")).thenReturn("testUpdate");
        when(request.getParameter("role")).thenReturn("USER");
        String id = null;
        for (User user : list) {
            if (this.userStore.compareLoginAndPassword("test", "test")) {
                id = String.valueOf(user.getId());
            }
        }
        when(request.getParameter("id")).thenReturn(id);

        update.doPost(request, response);
        User user = this.userStore.searchLoginAndPassword("testUpdate", "testUpdate");
        assertThat(user.getLogin(), is("testUpdate"));
    }
    /**
     * Test Add.
     */
    @Test
    public void whenDeleteUserInBD() throws IOException {
        DeleteServlet delete = new DeleteServlet();
        this.userStore.createConnection();
        List<User> list = this.userStore.findAll();
        HttpServletResponse response = mock(HttpServletResponse.class);
        HttpServletRequest request = mock(HttpServletRequest.class);
        String id = null;
        for (User user : list) {
            if (this.userStore.compareLoginAndPassword("testUpdate", "testUpdate")) {
                id = String.valueOf(user.getId());
            }
        }
        when(request.getParameter("id")).thenReturn(id);

        delete.doPost(request, response);
        User user = this.userStore.searchLoginAndPassword("testUpdate", "testUpdate");
        assertNull(user);
    }
}


text:
define([
  'marionette',
  'entities/filters',
  'entities/items',
  'modules/templates',
  'modules/vent',
  'views/items_lists',
  'views/filters'
], function (Marionette, Filters, Items, templates, vent, ItemsListsView, FiltersView) {

  return Marionette.LayoutView.extend({
    template: templates.dashboard,

    regions: {
      'Main': '.dashboard-main',
      'Side': '.dashboard-side'
    },

    initialize: function() {
      this.items  = this.options.items;
      this.people = this.options.people;
      this.tags   = this.options.tags;
    },

    onRender: function() {
      var self = this;

      this.filters = new Filters();

      this.lunrIndex = this.items.createLunrIndex();

      this.filteredItems = new Items(this.items.toJSON());

      this.itemsListsView = new ItemsListsView({
        collection: this.filteredItems
      });

      this.filtersView = new FiltersView({
        model: this.filters,
        people: this.people,
        tags: this.tags
      });

      vent.on('filters:change', function(filters) {
        self.onFiltersChange(filters);
      });

      vent.on('app:resize', function() {
        self.setWidthOnItemsListsForScrolling();
      });
    },

    onShow: function() {
      this.Main.show(this.itemsListsView);
      this.Side.show(this.filtersView);

      this.setWidthOnItemsListsForScrolling();
    },

    setWidthOnItemsListsForScrolling: function() {
      var windowWidth = $(window).width();
      var leftOffset = this.$el.find('.dashboard-main').offset().left;
      this.$el.find('.dashboard-main').width(windowWidth - leftOffset);
    },

    onSearchChange: function() {

    },

    onFiltersChange: function(filters) {
      var people            = filters.get('people');
      var isPeopleFilterSet = (people.length > 0);

      var tags           = filters.get('tags');
      var tagsLength     = tags.length;
      var isTagsFilterSet = (tagsLength > 0);

      if (isPeopleFilterSet || isTagsFilterSet) {
        var filteredItemsArray = _.filter(this.items.toJSON(), function(item) {
          // Filters on Assignee
          if (isPeopleFilterSet) {
            if (item.assigned_to === null) {
              return false;
            }
            if ((people.indexOf(item.assigned_to.first_name + ' ' + item.assigned_to.last_name)) === -1){
              return false;
            }
          }

          // Filter on Tag. Use AND operation for multiple tags.
          if (isTagsFilterSet) {
            for (var i = 0; i < tagsLength; i++) {
              if (item.tags.indexOf(tags[i]) === -1) {
                return false;
              }
            }
          }
         return true;
        });
      } else {
        var filteredItemsArray = this.items.toJSON();
      }

      // Filters on Search
      var search = filters.get('search');
      if (search !== '' && search.length >= 3) {
        var results = this.lunrIndex.search(search);
        results = _.pluck(results,'ref');
        results = _.map(results, function(num) {
          return parseInt(num, 10);
        });
        filteredItemsArray = _.filter(filteredItemsArray, function(item) {
          return (results.indexOf(item.number) !== -1);
        })
      }

      this.filteredItems.reset(filteredItemsArray)
    }

  });

});


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using XenAdmin.Controls;

namespace XenAdmin.Wizards.DRWizards
{
    public partial class DRFailoverWizardReportPage : XenTabPage
    {
        public DRFailoverWizardReportPage()
        {
            InitializeComponent();
        }

        public override string Text
        {
            get
            {
                return Messages.DR_WIZARD_REPORTPAGE_TEXT;
            }
        }

        public override string PageTitle
        {
            get
            {
                switch (WizardType)
                {
                    case DRWizardType.Failback:
                        return String.Format(Messages.DR_WIZARD_REPORTPAGE_TITLE_FAILBACK, Connection.Name);
                    case DRWizardType.Dryrun:
                        return String.Format(Messages.DR_WIZARD_REPORTPAGE_TITLE_DRYRUN, Connection.Name);
                    default:
                        return String.Format(Messages.DR_WIZARD_REPORTPAGE_TITLE_FAILOVER, Connection.Name);
                }
            }
        }

        public override string HelpID
        {
            get
            {
                switch (WizardType)
                {
                    case DRWizardType.Failback:
                        return "Failback_Report";
                    case DRWizardType.Dryrun:
                        return "Dryrun_Report";
                    default:
                        return "Failover_Report";
                }
            }
        }

        public override bool EnableCancel()
        {
            return false;
        }

        public override bool EnablePrevious()
        {
            return true;
        }

        public override void PageLoaded(PageLoadedDirection direction)
        {
            base.PageLoaded(direction);

            if (SummaryRetreiver == null)
                return;

            textBoxSummary.Text = SummaryRetreiver.Invoke();
        }

        public Func<string> SummaryRetreiver { private get; set; }
        public DRWizardType WizardType { private get; set; }
    }
}


text:
#nullable enable
using Content.Server.Utility;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Components;
using Robust.Shared.GameObjects.Components.Transform;
using Robust.Shared.Log;
using Robust.Shared.ViewVariables;

namespace Content.Server.GameObjects.Components.PA
{
    public abstract class ParticleAcceleratorPartComponent : Component
    {
        [ViewVariables] private PhysicsComponent? _collidableComponent;
        [ViewVariables] public ParticleAcceleratorControlBoxComponent? Master;
        [ViewVariables] protected SnapGridComponent? SnapGrid;

        public override void Initialize()
        {
            base.Initialize();
            // FIXME: this has to be an entity system, full stop.
            if (!Owner.TryGetComponent(out _collidableComponent))
            {
                Logger.Error("ParticleAcceleratorPartComponent created with no CollidableComponent");
            }
            else
            {
                _collidableComponent.AnchoredChanged += OnAnchorChanged;
            }

            if (!Owner.TryGetComponent(out SnapGrid))
            {
                Logger.Error("ParticleAcceleratorControlBox was created without SnapGridComponent");
            }
        }

        public void OnAnchorChanged()
        {
            RescanIfPossible();
        }

        public override void OnRemove()
        {
            base.OnRemove();

            RescanIfPossible();
        }

        private void RescanIfPossible()
        {
            Master?.RescanParts();
        }

        public virtual void Rotated()
        {
            RescanIfPossible();
        }
    }
}


text:
#region Copyright
// Copyright 2014 Myrcon Pty. Ltd.
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using System.Globalization;

namespace Potato.Net.Shared.Utils {
    /// <summary>
    /// A variety of string extenstions to help with various tasks
    /// </summary>
    public static class StringExtensions {

        /// <summary>
        /// Generates a random string
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string RandomString(int length) {
            byte[] randBuffer = new byte[length];
            RandomNumberGenerator.Create().GetBytes(randBuffer);
            return System.Convert.ToBase64String(randBuffer).Remove(length);
        }

        /// <summary>
        /// Splits a string into words, preserving words inside quotes
        /// </summary>
        public static List<String> Wordify(this String data) {
            List<String> list = new List<String>();

            String word = String.Empty;
            int stack = 0;
            bool escaped = false;

            foreach (char input in data) {

                if (input == ' ') {
                    if (stack == 0) {
                        list.Add(word);
                        word = String.Empty;
                    }
                    else {
                        word += ' ';
                    }
                }
                else if (input == 'n' && escaped == true) {
                    word += '\n';
                    escaped = false;
                }
                else if (input == 'r' && escaped == true) {
                    word += '\r';
                    escaped = false;
                }
                else if (input == 't' && escaped == true) {
                    word += '\t';
                    escaped = false;
                }
                else if (input == '"') {
                    if (escaped == false) {
                        if (stack == 0) {
                            stack++;
                        }
                        else {
                            stack--;
                        }
                    }
                    else {
                        word += '"';
                    }
                }
                else if (input == '\\') {
                    if (escaped == true) {
                        word += '\\';
                        escaped = false;
                    }
                    else {
                        escaped = true;
                    }
                }
                else {
                    word += input;
                    escaped = false;
                }
            }

            list.Add(word);

            return list;
        }

        /// <summary><![CDATA[
        /// Takes a string and splits it on words based on characters
        /// string testString = "this is a string with some words in it";
        /// testString.WordWrap(10) == List<string>() { "this is a", "string", "with some", "words in", "it" }
        ///
        /// Useful if you want to output a long string to the game and want all of the data outputed without
        /// losing any data.
        /// ]]></summary>
        /// <param name="text"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        public static List<String> WordWrap(this string text, int column) {
            List<String> result = new List<String>(text.Split(' '));

            for (int i = 0; i < result.Count - 1; i++) {
                if (result[i].Length + result[i + 1].Length + 1 <= column) {
                    result[i] = String.Format("{0} {1}", result[i], result[i + 1]);
                    result.RemoveAt(i + 1);
                    i--;
                }
            }

            return result;
        }

        /// <summary>
        /// Removes diacritics, such as the umlaut (ë => e).  Though not linguistically
        /// correct it does allow UTF8 to be represented in ASCII, at least to a degree
        /// that will alert translators that further translation is required.
        /// </summary>
        /// <param name="s">String containing diacritics</param>
        /// <returns>Normalized s</returns>
        public static string RemoveDiacritics(this string s) {
            string normalizedString = s.Normalize(NormalizationForm.FormD);
            StringBuilder stringBuilder = new StringBuilder();

            foreach (char t in normalizedString.Where(t => CharUnicodeInfo.GetUnicodeCategory(t) != UnicodeCategory.NonSpacingMark)) {
                stringBuilder.Append(t);
            }

            return stringBuilder.ToString();
        }

        private static readonly Dictionary<string, string> LeetRules = new Dictionary<string, string>() {
            { "4", "A" },
            { @"/\", "A" },
            { "@", "A" },
            { "^", "A" },
            { "13", "B" },
            { "/3", "B" },
            { "|3", "B" },
            { "8", "B" },
            { "><", "X" },
            { "<", "C" },
            { "(", "C" },
            { "|)", "D" },
            { "|>", "D" },
            { "3", "E" },
            { "6", "G" },
            { "/-/", "H" },
            { "[-]", "H" },
            { "]-[", "H" },
            { "!", "I" },
            { "|_", "L" },
            { "_/", "J" },
            { "_|", "J" },
            { "1", "L" },
            { "0", "O" },
            { "5", "S" },
            { "7", "T" },
            { @"\/\/", "W" },
            { @"\/", "V" },
            { "2", "Z" }
        };

        /// <summary>
        /// Removes leet speak from a name
        ///
        /// P]-[0gu3 => Phogue
        /// </summary>
        /// <param name="s">String containing leet speak</param>
        /// <returns>Normalized s</returns>
        public static string RemoveLeetSpeek(this string s) {
            return StringExtensions.LeetRules.Aggregate(s, (current, x) => current.Replace(x.Key, x.Value));
        }

        /// <summary>
        /// Strips both leet and diacritic from a string so it is represented
        /// in basic ASCII.
        /// </summary>
        /// <param name="s">String containing leet speak and diacritics</param>
        /// <returns>Normalized s</returns>
        public static string Strip(this string s) {
            string stripped = s;

            if (s != null) {
                stripped = stripped.RemoveLeetSpeek().RemoveDiacritics();
                stripped = new string(stripped.Where(ch => char.IsLetterOrDigit(ch) || char.IsWhiteSpace(ch)).ToArray());
            }

            return stripped;
        }

        /// <summary>
        /// Sanitizes a directory name (replaces all non-word chars with hyphens)
        /// </summary>
        public static String SanitizeDirectory(this String s) {
            s = Regex.Replace(s, "[^\\w]+", "-").Trim('-');

            return s;
        }

        /// <summary>
        /// Strips the query string from a url and sanitizes the remaining text
        /// </summary>
        public static String Slug(this String s) {
            String combined = s;
            Uri uri;

            if (Uri.TryCreate(s, UriKind.Absolute, out uri) == true) {
                combined = uri.Host + uri.PathAndQuery;
            }

            return combined.SanitizeDirectory();
        }

        /// <summary>
        /// Replaces the first occurance of a string within another string
        /// </summary>
        /// <param name="text">The source text to find replacements</param>
        /// <param name="search">The string to search for</param>
        /// <param name="replace">The text to replace with</param>
        /// <returns></returns>
        public static String ReplaceFirst(this String text, String search, String replace) {
            int pos = text.IndexOf(search, System.StringComparison.Ordinal);
            if (pos < 0) {
                return text;
            }
            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
        }
    }
}


text:
package com.sixrr.inspectjs.control;

import javax.annotation.Nonnull;

import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.lang.javascript.psi.*;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.sixrr.inspectjs.*;
import com.sixrr.inspectjs.utils.ControlFlowUtils;

public class  UnnecessaryReturnJSInspection extends JavaScriptInspection {
    private final UnnecessaryReturnFix fix = new UnnecessaryReturnFix();

    @Override
	@Nonnull
    public String getID() {
        return "UnnecessaryReturnStatementJS";
    }

    @Override
	@Nonnull
    public String getDisplayName() {
        return InspectionJSBundle.message("unnecessary.return.statement.display.name");
    }

    @Override
	@Nonnull
    public String getGroupDisplayName() {
        return JSGroupNames.CONTROL_FLOW_GROUP_NAME;
    }

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

    @Override
	public String buildErrorString(Object... args) {
        return InspectionJSBundle.message("unnecessary.return.error.string");
    }

    @Override
	public BaseInspectionVisitor buildVisitor() {
        return new UnnecessaryReturnVisitor();
    }

    @Override
	public InspectionJSFix buildFix(PsiElement location) {
        return fix;
    }

    private static class UnnecessaryReturnFix extends InspectionJSFix {
        @Override
		@Nonnull
        public String getName() {
            return InspectionJSBundle.message("remove.unnecessary.return.fix");
        }

        @Override
		public void doFix(Project project, ProblemDescriptor descriptor)
                throws IncorrectOperationException {
            final PsiElement returnKeywordElement = descriptor.getPsiElement();
            final PsiElement returnStatement = returnKeywordElement.getParent();
            assert returnStatement != null;
            deleteElement(returnStatement);
        }
    }

    private static class UnnecessaryReturnVisitor extends BaseInspectionVisitor {

        @Override public void visitJSReturnStatement(@Nonnull JSReturnStatement statement) {
            super.visitJSReturnStatement(statement);

            final JSExpression returnValue = statement.getExpression();
            if(returnValue!=null)
            {
                return;
            }
            final JSFunction function =
                    PsiTreeUtil.getParentOfType(statement, JSFunction.class);
            if (function == null) {
                return;
            }
            final PsiElement body = function.getLastChild();
            if (body == null) {
                return;
            }
            if(!(body instanceof JSBlockStatement))
            {
                return;
            }
            if (ControlFlowUtils.statementCompletesWithStatement((JSStatement) body, statement)) {
                registerStatementError(statement);
            }
        }
    }
}


text:
! { dg-do run }

! PR fortran/37193
! Check fix for problem with re-using the same symbol both renamed and
! plain.

MODULE m
  IMPLICIT NONE
  INTEGER :: i
END MODULE m

PROGRAM main
  USE m, ONLY: i, j => i
  IMPLICIT NONE

  i = 4
  j = 5

  IF (i /= j) THEN
    CALL abort ()
  END IF
END PROGRAM main

! { dg-final { cleanup-modules "m" } }


text:
// Copyright 2017 The Kubernetes Dashboard Authors.
//
// 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.

import {stateName as roleState} from 'role/list/state';

/**
 * @final
 */
export class RoleNavController {
  /**
   * @param {!angular.$resource} $resource
   * @ngInject
   */
  constructor($resource) {
    /** @export */
    this.isVisible = false;

    /** @private {!angular.$resource} */
    this.resource_ = $resource;

    /**
     * Initialized from binding.
     *
     * @export {!Object<string, string>}
     */
    this.states;
  }

  /**
   * Check status of rbacs in the cluster to show/hide Role menu entry.
   *
   * @export
   */
  $onInit() {
    this.resource_('api/v1/rbac/status').get().$promise.then((result) => {
      if (result && result.enabled) {
        Object.assign(this.states, {'role': roleState});
        this.isVisible = true;
      }
    });
  }
}

/**
 * @type {!angular.Component}
 */
export const roleNavComponent = {
  controller: RoleNavController,
  templateUrl: 'chrome/nav/rolenav.html',
  bindings: {
    'states': '=',
  },
};


text:
Jedinice mere

           Šifra
           Naziv

          {{article.sifraJediniceMere}}
          {{article.nazivJediniceMere}}

      <button class="btn btn-default" ng-click="add()">Dodaj</button>
       <button class="btn btn-default" ng-click="delete()">Obriši</button>
        <button class="btn btn-default" ng-click="update()">Izmeni</button>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Enumeratio plantarum 236. 1809

#### Original name
null

### Remarks
null


text:
/**
 * @author Evgeniya G. Maenkova
 */
package javax.swing.text;

import java.io.Serializable;
import javax.swing.JFormattedTextField;

public class DefaultFormatterFactory extends
    JFormattedTextField.AbstractFormatterFactory implements Serializable {

    private JFormattedTextField.AbstractFormatter nullFormatter;
    private JFormattedTextField.AbstractFormatter editFormatter;
    private JFormattedTextField.AbstractFormatter displayFormatter;
    private JFormattedTextField.AbstractFormatter defaultFormatter;

    public DefaultFormatterFactory() {
    }

    public DefaultFormatterFactory
         (final JFormattedTextField.AbstractFormatter defaultFormatter,
          final JFormattedTextField.AbstractFormatter displayFormatter,
          final JFormattedTextField.AbstractFormatter editFormatter) {
        this(defaultFormatter, displayFormatter, editFormatter, null);
    }

    public DefaultFormatterFactory
        (final JFormattedTextField.AbstractFormatter defaultFormatter,
         final JFormattedTextField.AbstractFormatter displayFormatter) {
        this(defaultFormatter, displayFormatter, null, null);
    }

    public DefaultFormatterFactory
        (final JFormattedTextField.AbstractFormatter defaultFormatter,
         final JFormattedTextField.AbstractFormatter displayFormatter,
         final JFormattedTextField.AbstractFormatter editFormatter,
         final JFormattedTextField.AbstractFormatter nullFormatter) {
        this.defaultFormatter = defaultFormatter;
        this.displayFormatter = displayFormatter;
        this.editFormatter = editFormatter;
        this.nullFormatter = nullFormatter;
    }

    public DefaultFormatterFactory
        (final JFormattedTextField.AbstractFormatter defaultFormatter) {
        this(defaultFormatter, null, null, null);
    }

    public JFormattedTextField.AbstractFormatter getDefaultFormatter() {
        return defaultFormatter;
    }

    public JFormattedTextField.AbstractFormatter getDisplayFormatter() {
        return displayFormatter;
    }

    public JFormattedTextField.AbstractFormatter getEditFormatter() {
        return editFormatter;
    }

    public JFormattedTextField.AbstractFormatter
        getFormatter(final JFormattedTextField ftf) {
        if (ftf.getValue() == null && nullFormatter != null) {
            return nullFormatter;
        }
        boolean hasFocus = ftf.hasFocus();
        JFormattedTextField.AbstractFormatter formatter =
            hasFocus ? editFormatter : displayFormatter;

        return (formatter != null) ? formatter : defaultFormatter;
    }

    public JFormattedTextField.AbstractFormatter getNullFormatter() {
        return nullFormatter;
    }

    public void setDefaultFormatter
        (final JFormattedTextField.AbstractFormatter formatter) {
        defaultFormatter = formatter;
    }

    public void setDisplayFormatter
        (final JFormattedTextField.AbstractFormatter formatter) {
        displayFormatter = formatter;
    }

    public void setEditFormatter
        (final JFormattedTextField.AbstractFormatter formatter) {
        editFormatter = formatter;
    }

    public void setNullFormatter
        (final JFormattedTextField.AbstractFormatter formatter) {
        nullFormatter = formatter;
    }
}


text:
package com.lightbend.lagom.internal.javadsl.persistence.cassandra

import java.util
import java.util.concurrent.{ CompletableFuture, CompletionStage }
import java.util.function.{ BiFunction, Function, Supplier }

import javax.inject.{ Inject, Singleton }
import akka.Done
import akka.actor.ActorSystem
import akka.event.Logging
import com.datastax.driver.core.BoundStatement
import com.lightbend.lagom.internal.javadsl.persistence.ReadSideImpl
import com.lightbend.lagom.internal.persistence.cassandra.CassandraOffsetStore
import com.lightbend.lagom.javadsl.persistence.ReadSideProcessor.ReadSideHandler
import com.lightbend.lagom.javadsl.persistence._
import com.lightbend.lagom.javadsl.persistence.cassandra.CassandraReadSide.ReadSideHandlerBuilder
import com.lightbend.lagom.javadsl.persistence.cassandra.{ CassandraReadSide, CassandraReadSideProcessor, CassandraSession }
import org.pcollections.{ PSequence, TreePVector }
import play.api.inject.Injector

/**
 * Internal API
 */
@Singleton
private[lagom] final class CassandraReadSideImpl @Inject() (
  system: ActorSystem, session: CassandraSession, offsetStore: CassandraOffsetStore, readSide: ReadSideImpl, injector: Injector
) extends CassandraReadSide {

  private val dispatcher = system.settings.config.getString("lagom.persistence.read-side.use-dispatcher")
  implicit val ec = system.dispatchers.lookup(dispatcher)

  override def register[Event <: AggregateEvent[Event]](
    processorClass: Class[_ <: CassandraReadSideProcessor[Event]]
  ): Unit = {

    readSide.registerFactory(
      () => {

        val processor = injector.instanceOf(processorClass)

        new ReadSideProcessor[Event] {
          override def buildHandler(): ReadSideHandler[Event] = {
            new LegacyCassandraReadSideHandler[Event](session, processor, dispatcher)
          }

          override def aggregateTags(): PSequence[AggregateEventTag[Event]] = {
            TreePVector.singleton(processor.aggregateTag)
          }

          override def readSideName(): String = Logging.simpleName(processorClass)
        }
      }, processorClass
    )
  }

  override def builder[Event <: AggregateEvent[Event]](eventProcessorId: String): ReadSideHandlerBuilder[Event] = {
    new ReadSideHandlerBuilder[Event] {
      import CassandraAutoReadSideHandler.Handler
      private var prepareCallback: AggregateEventTag[Event] => CompletionStage[Done] =
        tag => CompletableFuture.completedFuture(Done.getInstance())
      private var globalPrepareCallback: () => CompletionStage[Done] =
        () => CompletableFuture.completedFuture(Done.getInstance())
      private var handlers = Map.empty[Class[_ <: Event], Handler[Event]]

      override def setGlobalPrepare(callback: Supplier[CompletionStage[Done]]): ReadSideHandlerBuilder[Event] = {
        globalPrepareCallback = () => callback.get
        this
      }

      override def setPrepare(callback: Function[AggregateEventTag[Event], CompletionStage[Done]]): ReadSideHandlerBuilder[Event] = {
        prepareCallback = callback.apply
        this
      }

      override def setEventHandler[E <: Event](
        eventClass: Class[E],
        handler:    Function[E, CompletionStage[util.List[BoundStatement]]]
      ): ReadSideHandlerBuilder[Event] = {

        handlers += (eventClass -> ((event: E, offset: Offset) => handler(event)))
        this
      }

      override def setEventHandler[E <: Event](
        eventClass: Class[E],
        handler:    BiFunction[E, Offset, CompletionStage[util.List[BoundStatement]]]
      ): ReadSideHandlerBuilder[Event] = {

        handlers += (eventClass -> handler.apply _)
        this
      }

      override def build(): ReadSideHandler[Event] = {
        new CassandraAutoReadSideHandler[Event](session, offsetStore, handlers, globalPrepareCallback, prepareCallback, eventProcessorId, dispatcher)
      }
    }
  }
}


text:
module Stupidedi
  module Versions
    module FortyTen
      module SegmentDefs
        s = Schema
        e = ElementDefs
        r = ElementReqs

        SCH = s::SegmentDef.build(:SCH, "Line Item Schedule",
          "To specify the dat for scheduling aspecifc line-item",
          e::E380 .simple_use(r::Mandatory,  s::RepeatCount.bounded(1)),
          e::E355 .simple_use(r::Mandatory,  s::RepeatCount.bounded(1)),
          e::E98  .simple_use(r::Optional,   s::RepeatCount.bounded(1)),
          e::E93  .simple_use(r::Relational, s::RepeatCount.bounded(1)),
          e::E374 .simple_use(r::Optional,   s::RepeatCount.bounded(1)),
          e::E373 .simple_use(r::Optional,   s::RepeatCount.bounded(1)),
          e::E374 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
          e::E373 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
          SyntaxNotes::C.build(3, 4))
      end
    end
  end
end


text:
"use strict";
const utils = {

    isString : (str) => { return typeof str === 'string'},
    isNumber : (no) => { return typeof no === 'Number'},
    size     : (obj) => { return Object.keys(obj).length;}

}

module.exports = utils;


text:
<?php

namespace AppBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use AppBundle\Entity\CarClass;

class LoadCarClassData extends AbstractFixture implements OrderedFixtureInterface{
    public function load(ObjectManager $manager)
    {

        $class = new CarClass();
        $class->setType('Mini');
        $manager->persist($class);

        $class = new CarClass();
        $class->setType('Economy');
        $manager->persist($class);

        $class = new CarClass();
        $class->setType('Premium');
        $manager->persist($class);

        $class = new CarClass();
        $class->setType('Van');
        $manager->persist($class);

        $manager->flush();
    }

    public function getOrder()
    {
        return 3;
    }
}


text:
package org.apache.tinkerpop.gremlin.tinkergraph.process.traversal.strategy.decoration;

import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.ScalarMapStep;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.OptionsStrategy;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collection;

import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat;

/**
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public class OptionsStrategyTest {

    @Test
    public void shouldAddOptionsToTraversal() {
        final Graph graph = TinkerGraph.open();
        final GraphTraversalSource optionedG = graph.traversal().withStrategies(OptionsStrategy.build().with("a", "test").with("b").create());
        assertOptions(optionedG);
    }

    @Test
    public void shouldAddOptionsToTraversalUsingWith() {
        final Graph graph = TinkerGraph.open();
        final GraphTraversalSource optionedG = graph.traversal().with("a", "test").with("b");
        assertOptions(optionedG);
    }

    private static void assertOptions(final GraphTraversalSource optionedG) {
        GraphTraversal t = optionedG.inject(1);
        t = t.asAdmin().addStep(new ScalarMapStep<Object, Object>(t.asAdmin()) {
            @Override
            protected Object map(final Traverser.Admin<Object> traverser) {
                final OptionsStrategy strategy = traversal.asAdmin().getStrategies().getStrategy(OptionsStrategy.class).get();
                return Arrays.asList(strategy.getOptions().get("a"), strategy.getOptions().get("b"));
            }
        });
        assertThat((Collection<Object>) t.next(), contains("test", true));
    }
}


text:
package org.itas.core.bytecode;

import javassist.CtClass;
import javassist.CtField;

/**
 * 枚举关键字为int数据[field]类型字节码动态生成
 * @author liuzhen(liuxing521a@gmail.com)
 * @crateTime 2015年2月26日下午4:51:14
 */
class FDEnumIntProvider extends AbstractFieldProvider
    implements FieldProvider, TypeProvider {

	private static final String STATEMENT_SET = new StringBuffer()
		.append(next(1, 2)).append("{")
		.append(next(1, 3)).append("int value_ = 0;")
		.append(next(1, 3)).append("if (get%s() != null) {")
		.append(next(1, 4)).append("value_ = get%s().key();")
		.append(next(1, 3)).append("}")
		.append(next(1, 3)).append("state.setInt(%s, value_);")
		.append(next(1, 2)).append("}")
		.toString();

	private static final String RESULTSET_GET = new StringBuffer()
		.append(next(1, 2))
		.append("set%s(parse(%s.class, result.getInt(\"%s\")));")
		.toString();

	public static final FDEnumIntProvider PROVIDER = new FDEnumIntProvider();

	private FDEnumIntProvider() {
	}

	@Override
	public boolean isType(Class<?> clazz) {
		return javaType.enumInt_.isAssignableFrom(clazz);
	}

	@Override
	public boolean isType(CtClass clazz)  throws Exception {
		return clazz.subtypeOf(javassistType.enumInt_);
	}

	@Override
	public String sqlType(CtField field) {
		return String.format("`%s` INT(11) NOT NULL DEFAULT '0'", field.getName());
	}

	@Override
	public String setStatement(int index, CtField field) {
		return String.format(STATEMENT_SET,
			upCase(field.getName()), upCase(field.getName()), index);
	}

	@Override
	public String getResultSet(CtField field) throws Exception {
		return String.format(RESULTSET_GET, upCase(field.getName()),
			field.getType().getName().replace('$', '.'), field.getName());
	}

}


text:
package org.apache.druid.segment.filter;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import org.apache.druid.collections.bitmap.ImmutableBitmap;
import org.apache.druid.collections.spatial.search.Bound;
import org.apache.druid.query.BitmapResultFactory;
import org.apache.druid.query.filter.BitmapIndexSelector;
import org.apache.druid.query.filter.DruidDoublePredicate;
import org.apache.druid.query.filter.DruidFloatPredicate;
import org.apache.druid.query.filter.DruidLongPredicate;
import org.apache.druid.query.filter.DruidPredicateFactory;
import org.apache.druid.query.filter.Filter;
import org.apache.druid.query.filter.FilterTuning;
import org.apache.druid.query.filter.ValueMatcher;
import org.apache.druid.segment.ColumnSelector;
import org.apache.druid.segment.ColumnSelectorFactory;
import org.apache.druid.segment.incremental.SpatialDimensionRowTransformer;

import java.util.Objects;
import java.util.Set;

/**
 */
public class SpatialFilter implements Filter
{
  private final String dimension;
  private final Bound bound;
  private final FilterTuning filterTuning;

  public SpatialFilter(
      String dimension,
      Bound bound,
      FilterTuning filterTuning
  )
  {
    this.dimension = Preconditions.checkNotNull(dimension, "dimension");
    this.bound = Preconditions.checkNotNull(bound, "bound");
    this.filterTuning = filterTuning;
  }

  @Override
  public <T> T getBitmapResult(BitmapIndexSelector selector, BitmapResultFactory<T> bitmapResultFactory)
  {
    Iterable<ImmutableBitmap> search = selector.getSpatialIndex(dimension).search(bound);
    return bitmapResultFactory.unionDimensionValueBitmaps(search);
  }

  @Override
  public ValueMatcher makeMatcher(ColumnSelectorFactory factory)
  {
    return Filters.makeValueMatcher(
        factory,
        dimension,
        new BoundDruidPredicateFactory(bound)

    );
  }

  @Override
  public boolean supportsBitmapIndex(BitmapIndexSelector selector)
  {
    return selector.getBitmapIndex(dimension) != null;
  }

  @Override
  public boolean shouldUseBitmapIndex(BitmapIndexSelector selector)
  {
    return Filters.shouldUseBitmapIndex(this, selector, filterTuning);
  }

  @Override
  public boolean supportsSelectivityEstimation(ColumnSelector columnSelector, BitmapIndexSelector indexSelector)
  {
    return false;
  }

  @Override
  public Set<String> getRequiredColumns()
  {
    return ImmutableSet.of(dimension);
  }

  @Override
  public double estimateSelectivity(BitmapIndexSelector indexSelector)
  {
    // selectivity estimation for multi-value columns is not implemented yet.
    throw new UnsupportedOperationException();
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    SpatialFilter that = (SpatialFilter) o;
    return Objects.equals(dimension, that.dimension) &&
           Objects.equals(bound, that.bound) &&
           Objects.equals(filterTuning, that.filterTuning);
  }

  @Override
  public int hashCode()
  {
    return Objects.hash(dimension, bound, filterTuning);
  }

  @VisibleForTesting
  static class BoundDruidPredicateFactory implements DruidPredicateFactory
  {
    private final Bound bound;

    BoundDruidPredicateFactory(Bound bound)
    {
      this.bound = bound;
    }

    @Override
    public Predicate<String> makeStringPredicate()
    {
      return input -> {
        if (input == null) {
          return false;
        }
        final float[] coordinate = SpatialDimensionRowTransformer.decode(input);
        return bound.contains(coordinate);
      };
    }

    @Override
    public DruidLongPredicate makeLongPredicate()
    {
      // SpatialFilter does not currently support longs
      return DruidLongPredicate.ALWAYS_FALSE;
    }

    @Override
    public DruidFloatPredicate makeFloatPredicate()
    {
      // SpatialFilter does not currently support floats
      return DruidFloatPredicate.ALWAYS_FALSE;
    }

    @Override
    public DruidDoublePredicate makeDoublePredicate()
    {
      // SpatialFilter does not currently support doubles
      return DruidDoublePredicate.ALWAYS_FALSE;
    }

    @Override
    public boolean equals(Object o)
    {
      if (this == o) {
        return true;
      }
      if (o == null || getClass() != o.getClass()) {
        return false;
      }
      BoundDruidPredicateFactory that = (BoundDruidPredicateFactory) o;
      return Objects.equals(bound, that.bound);
    }

    @Override
    public int hashCode()
    {
      return Objects.hash(bound);
    }
  }
}


text:
namespace reil {
namespace test {

// NOTE: This file is generated by aarch64_decoder_test_generator.py - please
// add new tests there and regenerate this file instead of modifying this file
// directly.

TEST(AArch64Decoder, Adr) {
  uint32_t opcode = 0x10000000;
  aarch64::decoder::Instruction insn =
      aarch64::decoder::DecodeInstruction(0x1000, opcode);

  std::cerr << insn << std::endl;

  ASSERT_EQ(insn.opcode, aarch64::decoder::kAdr);
}

TEST(AArch64Decoder, AddImmediate) {
  uint32_t opcode = 0x91008ffd;
  aarch64::decoder::Instruction insn =
      aarch64::decoder::DecodeInstruction(0x1000, opcode);

  std::cerr << insn << std::endl;

  ASSERT_EQ(insn.opcode, aarch64::decoder::kAddImmediate);
}

TEST(AArch64Decoder, LdaxrBug1) {
  uint32_t opcode = 0xc85ffe88;
  aarch64::decoder::Instruction insn =
      aarch64::decoder::DecodeInstruction(0x1000, opcode);

  std::cerr << insn << std::endl;

  ASSERT_EQ(insn.opcode, aarch64::decoder::kLdaxr);
}

TEST(AArch64Decoder, SimdLdrLiteral) {
  uint32_t opcode = 0x9c000000;
  aarch64::decoder::Instruction insn =
      aarch64::decoder::DecodeInstruction(0x1000, opcode);

  std::cerr << insn << std::endl;

  ASSERT_EQ(insn.opcode, aarch64::decoder::kSimdLdrLiteral);
}

TEST(AArch64Decoder, SimdLdp) {
  uint32_t opcode = 0xad400400;
  aarch64::decoder::Instruction insn =
      aarch64::decoder::DecodeInstruction(0x1000, opcode);

  std::cerr << insn << std::endl;

  ASSERT_EQ(insn.opcode, aarch64::decoder::kSimdLdp);
}

TEST(AArch64Decoder, SimdLdnp) {
  uint32_t opcode = 0xac400400;
  aarch64::decoder::Instruction insn =
      aarch64::decoder::DecodeInstruction(0x1000, opcode);

  std::cerr << insn << std::endl;

  ASSERT_EQ(insn.opcode, aarch64::decoder::kSimdLdnp);
}

TEST(AArch64Decoder, SimdStp) {
  uint32_t opcode = 0xad000400;
  aarch64::decoder::Instruction insn =
      aarch64::decoder::DecodeInstruction(0x1000, opcode);

  std::cerr << insn << std::endl;

  ASSERT_EQ(insn.opcode, aarch64::decoder::kSimdStp);
}

TEST(AArch64Decoder, SimdStnp) {
  uint32_t opcode = 0xac000400;
  aarch64::decoder::Instruction insn =
      aarch64::decoder::DecodeInstruction(0x1000, opcode);

  std::cerr << insn << std::endl;

  ASSERT_EQ(insn.opcode, aarch64::decoder::kSimdStnp);
}

TEST(AArch64Decoder, SimdLdrUnscaledImmediatePostindex) {
  uint32_t opcode = 0x3c401400;
  aarch64::decoder::Instruction insn =
      aarch64::decoder::DecodeInstruction(0x1000, opcode);

  std::cerr << insn << std::endl;

  ASSERT_EQ(insn.opcode, aarch64::decoder::kSimdLdr);
  ASSERT_EQ(insn.operands.size(), 2);
  ASSERT_EQ(absl::get<aarch64::decoder::Register>(insn.operands[0]).size, 8);
  ASSERT_EQ(absl::get<aarch64::decoder::Register>(insn.operands[0]).name,
            aarch64::decoder::Register::kV0);
}

TEST(AArch64Decoder, SimdStrUnscaledImmediatePostindex) {
  uint32_t opcode = 0x3c80141f;
  aarch64::decoder::Instruction insn =
      aarch64::decoder::DecodeInstruction(0x1000, opcode);

  std::cerr << insn << std::endl;

  ASSERT_EQ(insn.opcode, aarch64::decoder::kSimdStr);
  ASSERT_EQ(insn.operands.size(), 2);
  ASSERT_EQ(absl::get<aarch64::decoder::Register>(insn.operands[0]).size, 128);
  ASSERT_EQ(absl::get<aarch64::decoder::Register>(insn.operands[0]).name,
            aarch64::decoder::Register::kV31);
}

}  // namespace test
}  // namespace reil

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
/*************************
*   Precompiled Header   *
**************************/
#include "precomp_graphics.h"

/**********************
*   System Includes   *
***********************/

/*************************
*   3rd Party Includes   *
**************************/

/***************************
*   Game Engine Includes   *
****************************/
#include "Texture.h"
#include "GraphicDevice.h"

//Always include last
#include "Memory\MemLeaks.h"

/********************
*   Function Defs   *
*********************/
Texture::Texture(GraphicDevice& graphicDevice, TextureType textureType, const std::string& textureName)
    : GameResource(textureName, GameResourceType::Unknown)
    , m_GraphicDevice(graphicDevice)
    , m_TextureType(textureType)
{
    switch (m_TextureType)
    {
        case TextureType::Texture2D:
            m_ResourceType = GameResourceType::Texture2D;
            break;

        case TextureType::TextureCube:
            m_ResourceType = GameResourceType::TextureCube;
            break;

        default:
            AEAssert(false);
            break;
    }
}

Texture::~Texture()
{
    ReleaseCOM(m_ShaderResourceView);
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidtest.material.MaterialActivity">

    <!-- <TextView
        android:id="@+id/my_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:elevation="5dp"
        android:text="@string/hello_world" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />   -->

    <android.support.v7.widget.CardView

        android:id="@+id/card_view"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center"

        >

        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <ImageView
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:background="@drawable/bg" />
    </android.support.v7.widget.CardView>

    <SeekBar
        android:id="@+id/seek_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>


text:
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<style is="custom-style">

/*
 Polymer includes a shim for CSS Custom Properties that we can use for application theming.
 Below, you'll find the default palette for the Polymer Starter Kit layout. Feel free to play
 with changing the colors used or generate your own palette of colours at MaterialPalette.com.

 See https://www.polymer-project.org/1.0/docs/devguide/styling.html#xscope-styling-details
 for further information on custom CSS properties.
 */

/* Application theme */

:root {
  --dark-primary-color: #303F9F;
  --default-primary-color:#3F51B5;
  --light-primary-color: #C5CAE9;
  --text-primary-color: #ffffff; /*text/icons*/
  --accent-color: #FF4081;
  --primary-background-color: #c5cae9;
  --primary-text-color: #212121;
  --secondary-text-color: #727272;
  --disabled-text-color: #bdbdbd;
  --divider-color: #B6B6B6;

  /* Components */

  /* paper-drawer-panel */
  --drawer-menu-color: #ffffff;
  --drawer-border-color: 1px solid #ccc;
  --drawer-toolbar-border-color: 1px solid rgba(0, 0, 0, 0.22);

    /* paper-menu */
  --paper-menu-background-color: #fff;
  --menu-link-color: #111111;
}

/* General styles */

paper-material {
  border-radius: 2px;
  height: 100%;
  padding: 16px 0px 16px 0px;
  width: calc(98.66% - 16px);
  margin: 16px auto;
  background: white;
}

#mainToolbar {
  box-shadow: 0 4px 5px 0 rgba(0,0,0,.14),
  0 2px 9px 1px rgba(0,0,0,.12),
  0 4px 2px -2px rgba(0,0,0,.2);
}

paper-menu iron-icon {
  margin-right: 33px;
  opacity: 0.54;
}

.paper-menu > .iron-selected {
  color: var(--default-primary-color);
}

#mainToolbar .bottom {
  padding-bottom: 120px;
  padding-left: 30px;
}

paper-menu a {
  text-decoration: none;
  color: var(--menu-link-color);
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -ms-flex-direction: row;
  -webkit-flex-direction: row;
  flex-direction: row;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
  font-family: 'Roboto', 'Noto', sans-serif;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
  font-size: 14px;
  font-weight: 400;
  line-height: 24px;
  min-height: 48px;
  padding: 0px 16px;
}

#drawerToolbar {
  border-bottom: var(--drawer-toolbar-border-color);
  height: 120px;
}

#paperToggle {
  width: 45px;
  height: 45px;
  border: none;
  color: var(--drawer-menu-color);
  background-color: transparent;
  margin-right: 16px;
  padding: 8px;
}

/* Breakpoints */

/* Small */

@media (max-width: 600px) {

  paper-toolbar.has-shadow {
    height: 56px;
  }

  .paper-font-display2 {
    font-size: 30px;
  }

  .paper-font-display1 {
    font-size: 12px;
  }

  paper-material {
    --menu-container-display: none;
    width: calc(97.33% - 32px);
    padding-left: 16px;
    padding-right: 16px;
  }

  #drawer .paper-toolbar {
    margin-left: 16px;
  }

  #overlay {
    min-width: 360px;
  }

  .bg {
    background: white;
  }

  #mainToolbar .bottom {
    padding-left: 50px;
    padding-bottom: 24px;
  }

  #mainToolbar.has-shadow .bottom {
    padding-bottom: 0px;
  }

  .appname {
    font-size: 24px;
    padding-bottom: 0px;
  }
}

@media (min-width: 601px) {

  paper-material {
    width: calc(98% - 46px);
    padding-left: 30px;
    padding-right: 30px;
  }

    #mainToolbar.has-shadow .bottom {
        margin-left: 50px;
        padding-bottom: 0;
        padding-left: 0;
        font-size: 24px;
    }

}

/* Material Design Adaptive Breakpoints */
/*
  Below you'll find CSS media queries based on the breakpoint guidance
  published by the Material Design team. You can choose to use, customise
  or remove these breakpoints based on your needs.

  http://www.google.com/design/spec/layout/adaptive-ui.html#adaptive-ui-breakpoints
 */

/* mobile-small */
@media all and (min-width: 0px) and (max-width: 360px) and (orientation: portrait) { }
/* mobile-large */
@media all and (min-width: 361px) and (orientation: portrait) { }
/* mobile-small-landscape */
@media all and (min-width: 0px) and (max-width: 480px) and (orientation: landscape) { }
/* mobile-large-landscape */
@media all and (min-width: 481px) and (orientation: landscape) { }
/* tablet-small-landscape */
@media all and (min-width: 600px) and (max-width: 960px) and (orientation: landscape) { }
/* tablet-large-landscape */
@media all and (min-width: 961px) and (orientation: landscape) { }
/* tablet-small */
@media all and (min-width: 600px) and (orientation: portrait) { }
/* tablet-large */
@media all and (min-width: 601px) and (max-width: 840px) and (orientation : portrait) { }
/* desktop-x-small-landscape */
@media all and (min-width: 0px) and (max-width: 480px) and (orientation: landscape) { }
/* desktop-x-small */
@media all and (min-width: 0px) and (max-width: 480px) and (max-aspect-ratio: 4/3) { }
/* desktop-small-landscape */
@media all and (min-width: 481px) and (max-width: 840px) and (orientation: landscape) { }
/* desktop-small */
@media all and (min-width: 481px) and (max-width: 840px) and (max-aspect-ratio: 4/3) { }
/* desktop-medium-landscape */
@media all and (min-width: 841px) and (max-width: 1280px) and (orientation: landscape) { }
/* desktop-medium */
@media all and (min-width: 841px) and (max-width: 1280px) and (max-aspect-ratio: 4/3) { }
/* desktop-large */
@media all and (min-width: 1281px) and (max-width: 1600px) { }
/* desktop-xlarge */
@media all and (min-width: 1601px) and (max-width: 1920px) { }
</style>


text:
<?php

namespace Symfony\Tests\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraints\Language;
use Symfony\Component\Validator\Constraints\LanguageValidator;

class LanguageValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $validator;

    protected function setUp()
    {
        $this->validator = new LanguageValidator();
    }

    protected function tearDown()
    {
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->assertTrue($this->validator->isValid(null, new Language()));
    }

    public function testEmptyStringIsValid()
    {
        $this->assertTrue($this->validator->isValid('', new Language()));
    }

    public function testExpectsStringCompatibleType()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');

        $this->validator->isValid(new \stdClass(), new Language());
    }

    /**
     * @dataProvider getValidLanguages
     */
    public function testValidLanguages($date)
    {
        $this->assertTrue($this->validator->isValid($date, new Language()));
    }

    public function getValidLanguages()
    {
        return array(
            array('en'),
            array('en_US'),
            array('my'),
        );
    }

    /**
     * @dataProvider getInvalidLanguages
     */
    public function testInvalidLanguages($date)
    {
        $this->assertFalse($this->validator->isValid($date, new Language()));
    }

    public function getInvalidLanguages()
    {
        return array(
            array('EN'),
            array('foobar'),
        );
    }

    public function testMessageIsSet()
    {
        $constraint = new Language(array(
            'message' => 'myMessage'
        ));

        $this->assertFalse($this->validator->isValid('foobar', $constraint));
        $this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
        $this->assertEquals($this->validator->getMessageParameters(), array(
            '{{ value }}' => 'foobar',
        ));
    }
}


text:
package org.apache.alert.coordinator;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.eagle.alert.coordinator.impl.MetadataValdiator;
import org.apache.eagle.alert.coordinator.provider.InMemScheduleConext;
import org.junit.Test;

/**
 * Created on 10/2/16.
 */
public class TestMetadataValidator {

    private static final ObjectMapper om = new ObjectMapper();

    @Test
    public void validate() throws Exception {
        InMemScheduleConext context = new InMemScheduleConext();
        MetadataValdiator mv = new MetadataValdiator(context);

        // om.readValue(TestMetadataValidator.class.getResourceAsStream("/validation/datasources.json"), new Gene);
        // TODO add more test here.

    }
}


text:
FactoryGirl.define do
  factory :main_entry_cross_reference do
    main_entry nil
    cross_reference_form_id 1
  end
end


text:
import os
from pprint import pprint

from kwmqueues.utils.ainput import ainput
from kwmqueues.utils.tableoutput import TableOutput

from queue import QUEUE

class CloudQueueCLI:
    def __init__(self):
        return

    def ListQueues(self):
        queue = QUEUE()
        queues = queue.ListQueues()
        labels = ('Name', 'href', 'metadata')
        rows = []

        for queue in queues:
            rows.append((str(queue['name']), str(queue['href']), str(queue['metadata'])))

        to = TableOutput()
        print to.indent([labels] + rows, hasHeader=True, separateRows=True, prefix='| ', postfix=' |')

        return

    def GetQueueStats(self):
        name = ainput("Queue Name: ").getString()

        queue = QUEUE()
        stats = queue.GetQueueStats(name)
        labels = ('Queue', 'Free', 'Claimed')
        rows = []

        rows.append((name, str(stats['messages']['free']), str(stats['messages']['claimed'])))

        to = TableOutput()
        print to.indent([labels] + rows, hasHeader=True, separateRows=True, prefix='| ', postfix=' |')

        return

    def CreateQueue(self):
        name = ainput("Queue Name: ").getString()

        queue = QUEUE()
        response, content = queue.CreateQueue(name)
        print response
        print content

        return

    def DeleteQueue(self):
        name = ainput("Queue Name: ").getString()

        queue = QUEUE()
        response, content = queue.DeleteQueue(name)
        print response
        print content

        return

    def PostMessage(self):
        qname = ainput("Queue Name: ").getString()
        ttl = ainput("TTL: ").getInteger()
        body = ainput("Body: ").getString()

        queue = QUEUE()
        response, content = queue.PostMessage(qname, ttl, body)
        print response
        print content

        return

    def GetMessages(self):
        qname = ainput("Queue Name: ").getString()

        queue = QUEUE()
        response, content = queue.GetMessages(qname)
        print response
        print content

        return

    def DeleteMessage(self):
        qname = ainput("Queue Name: ").getString()
        message_id = ainput("Message Id: ").getString()

        queue = QUEUE()
        response, content = queue.DeleteMessage(qname, message_id)
        print response
        print content

        return

    def ClaimMessages(self):
        qname = ainput("Queue Name: ").getString()
        num_messages = ainput("Number of Messages: ").getInteger()

        queue = QUEUE()
        response, content = queue.ClaimMessages(qname, str(num_messages))
        print response
        print content

        return

def show_main_menu():
    print "\nRackspace Queuing\n"
    qcli = CloudQueueCLI()

    print "\nChoose from an option below:\n\
        1. List Queues\n\
        2. Create Queue\n\
        3. Delete Queue\n\
        4. Post Message\n\
        5. Get Messages\n\
        6. Delete Message\n\
        7. Get Queue Stats\n\
        8. Claim Messages\n\
        9. Exit\n"

    option = ainput("Select a number from the menu above: ").getString()
    arguments = []

    if option == '1':
        qcli.ListQueues()
    elif option == '2':
        qcli.CreateQueue()
    elif option == '3':
        qcli.DeleteQueue()
    elif option == '4':
        qcli.PostMessage()
    elif option == '5':
        qcli.GetMessages()
    elif option == '6':
        qcli.DeleteMessage()
    elif option == '7':
        qcli.GetQueueStats()
    elif option == '8':
        qcli.ClaimMessages()
    elif option == '9':
        print "\n"
        exit()

    return

def main():

    while True:
        os.system('clear')
        show_main_menu()
        raw_input("Press any key to continue")

    return

if __name__ == '__main__':
    try:
        main()
    except EOFError:
        print "\n"
        exit()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sistematiki i Rasprostranenie Gribov (Tartu) 151 (1978)

#### Original name
Cistella orientalis Raitv.

### Remarks
null


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Pengamatan extends CI_Controller {

	public function Save()
	{
		$strinfo = $this->input->post("info");
		$mode = $this->input->post("editmode");

		$info = json_decode($strinfo);

		$this->load->model('Pengamatan_model');
		if($mode=="edit") {
			$this->Pengamatan_model->DeletePengamatan($info->idlama);
			$this->Pengamatan_model->DeletePengamatanDetail($info->idlama);
		}

		$this->Pengamatan_model->SavePengamatan($info);
		foreach($info->details as $detail) $this->Pengamatan_model->SavePengamatanDetail($detail);
	}

	public function Delete() {
		$kode_desa = $this->input->post("kodedesa");

		$this->load->model('Pengamatan_model');
		$this->Pengamatan_model->DeleteData($kode_desa);
	}

	public function GetByCity($kodekota) {
		$this->load->model('Pengamatan_model');
		$data = $this->Pengamatan_model->LoadByKota($kodekota);

		$data = json_encode($data->result());
		echo $data;
	}

}