text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
-->
<project name="FlexUnit4Core" basedir="." default="package">
   <import file="${basedir}/../utils.xml" />
   <property environment="env" />

   <!-- Configuration -->
   <property name="build.artifactId" value="flexunit" />
   <property name="build.finalName.flex" value="${build.artifactId}-${build.version}-${build.number}-flex_${build.sdk}" />
   <property name="build.finalName.as3" value="${build.artifactId}-${build.version}-${build.number}-as3_${build.sdk}" />
   <property name="build.packaging" value="swc" />
   <property name="instrument.finalName" value="instrument" />
   <property name="instrument.metadata" value="flexunit-instrument.cvm" />
   <property name="build.deploy.name" value="FlexUnit Core Library" />
   <property name="build.deploy.description" value="FlexUnit core library" />

   <!-- Existing -->
   <property name="src.loc" location="${basedir}/src" />
   <property name="lib.loc" location="${basedir}/libs" />

   <!-- Generated -->
   <property name="dist.loc" location="${basedir}/target" />
   <property name="sonatype.loc" location="${dist.loc}/sonatype" />
   <property name="bin.loc" location="${basedir}/target/bin" />
   <property name="report.loc" location="${basedir}/target/report" />
   <property name="doc.loc" location="${basedir}/target/docs" />

   <!-- Setup Flex Ant Resources -->
   <property name="FLEX_HOME" location="${env.FLEX_HOME}" />
   <property name="FLEX_COVER_HOME" location="${env.FLEX_COVER_HOME}" />
	<taskdef resource="flexTasks.tasks" >
		<classpath>
			<pathelement location="${FLEX_HOME}/ant/lib/flexTasks.jar"/>
			<pathelement location="${FLEX_HOME}/lib/flexTasks.jar"/>
		</classpath>
	</taskdef>

   <!-- Reusable macro for compile SWC variations -->
   <macrodef name="compile-swc">
      <attribute name="sdk" />
      <attribute name="classes" />
      <attribute name="artifact" />
      <attribute name="useflex" />
      <element name="args" optional="true" />
      <sequential>
         <echo />
         <echo message="SDK: @{sdk}" />
         <echo message="Artifact: @{artifact}" />
         <echo message="UseFlex: @{useFlex}" />
         <echo />
         <java jar="@{sdk}/lib/compc.jar" fork="true" failonerror="true">
            <jvmarg value="-Xmx256m" />
            <arg line="+flexlib '@{sdk}/frameworks'" />
            <arg line="-link-report '${bin.loc}/link-report-@{useflex}.xml'" />
            <arg line="-include-classes @{classes}" />
            <arg line="-source-path+='${src.loc}'" />
            <arg line="-output '${bin.loc}/@{artifact}'" />
            <arg line="-library-path+='${lib.loc}'" />
            <arg line="-external-library-path+='@{sdk}/frameworks/libs/'" />
            <arg line="-keep-as3-metadata+=RunWith,BeforeClass,AfterClass,Before,After,Suite,Test,TestCase,Ignore,Filter,Sort,Theory,DataPoint,DataPoints,ArrayElementType,Rule,Parameters" />
            <arg line="-define=CONFIG::useFlexClasses,@{useFlex}" />
            <arg line="-verbose-stacktraces=true" />
            <arg line="-headless-server=true" />
            <args />
         </java>
      </sequential>
   </macrodef>

   <target name="clean">
      <delete dir="${dist.loc}" />
  	  <ant antfile="${basedir}/downloads.xml" target="clean" dir="${basedir}" />
   </target>

   <target name="init">
      <!-- Create paths -->
      <mkdir dir="${dist.loc}" />
      <mkdir dir="${sonatype.loc}" />
      <mkdir dir="${bin.loc}" />
      <mkdir dir="${report.loc}" />
      <mkdir dir="${doc.loc}" />

      <!-- Create properties file from .flexLibProperties -->
      <xslt in="${basedir}/.flexLibProperties" out="${bin.loc}/flexLib.properties" style="${basedir}/flexLibProperties.xsl" />
   </target>

    <target name="thirdparty-downloads">
		<ant antfile="${basedir}/downloads.xml" dir="${basedir}" />
    </target>

   <target name="compile" depends="init, thirdparty-downloads, compile-flex,compile-as3,as3-linker-check" />

   <target name="compile-flex">
      <!-- Pull in class file list for compc -->
      <property file="${bin.loc}/flexLib.properties" />

      <!-- Compile Flex SWC -->
      <compile-swc sdk="${FLEX_HOME}" artifact="${build.finalName.flex}.${build.packaging}" classes="${src.class-list}" useflex="true" />
   </target>

   <target name="compile-as3">
      <!-- Pull in class file list for compc -->
      <property file="${bin.loc}/flexLib.properties" />

      <!-- Compile AS3 SWC -->
      <compile-swc sdk="${FLEX_HOME}" artifact="${build.finalName.as3}.${build.packaging}" classes="${src.class-list}" useflex="false" />
   </target>

   <target name="instrument-compile" depends="compile" if="build.instrument" description="All instrumentation on Flex SWC">
      <!-- Pull in class file list for compc -->
      <property file="${bin.loc}/flexLib.properties" />

      <!-- Compile SWC using FlexCover SDK for flex -->
      <compile-swc sdk="${FLEX_COVER_HOME}" artifact="${instrument.finalName}.${build.packaging}" classes="${src.class-list}" useflex="true">
         <args>
            <arg line="-coverage" />
            <arg line="-coverage-metadata='${bin.loc}/${instrument.metadata}'" />
         </args>
      </compile-swc>
   </target>

   <target name="as3-linker-check" depends="compile-as3">
      <!-- Create properties file from link report for last built SWC, which should be Flex -->
      <xslt in="${bin.loc}/link-report-false.xml" out="${bin.loc}/flex-dependencies.txt" style="${basedir}/link-report.xsl" />

      <!-- Was the flex-dependencies report empty for AS3 only builds? -->
      <fail message="Build contains depedencies on the Flex framework, but is being built for AS3.">
         <condition>
            <length file="${bin.loc}/flex-dependencies.txt" when="greater" length="0" />
         </condition>
      </fail>
   </target>

   <target name="report" depends="pmdReport" if="build.report" description="All reporting done on Flex SWC">
      <!-- Pull in class file list to use with asdoc -->
      <property file="${bin.loc}/flexLib.properties" />

      <!-- Generate asdocs -->
      <java jar="${FLEX_HOME}/lib/asdoc.jar" fork="true" failonerror="true">
         <jvmarg value="-Xmx256M" />
         <arg line="+flexlib '${FLEX_HOME}/frameworks'" />
         <arg line="-doc-classes ${src.class-list}" />
         <arg line="-source-path+='${src.loc}'" />
         <arg line="-output '${doc.loc}'" />
         <arg line="-library-path+='${lib.loc}'" />
         <arg line="-define=CONFIG::useFlexClasses,true" />
      </java>
   </target>

   <target name="asdocs" description="AS docs">
      <!-- Pull in class file list to use with asdoc -->
      <property file="${bin.loc}/flexLib.properties" />

      <!-- Generate asdocs -->
      <java jar="${FLEX_HOME}/lib/asdoc.jar" fork="true" failonerror="true">
         <jvmarg value="-Xmx256M" />
         <arg line="+flexlib '${FLEX_HOME}/frameworks'" />
         <arg line="-doc-classes ${src.class-list}" />
         <arg line="-source-path+='${src.loc}'" />
         <arg line="-output '${doc.loc}'" />
         <arg line="-library-path+='${lib.loc}'" />
         <arg line="-define=CONFIG::useFlexClasses,true" />
      </java>
   </target>

   <target name="pmdReport" if="build.pmd">
      <taskdef name="pmd" classname="com.adobe.ac.pmd.ant.FlexPmdAntTask" />
      <taskdef name="cpd" classname="com.adobe.ac.cpd.ant.FlexCpdAntTask" />
      <taskdef name="metrics" classname="com.adobe.ac.pmd.metrics.ant.FlexMetricsAntTask" />

      <!-- Generate FlexPMD reports -->
      <pmd sourceDirectory="${src.loc}" outputDirectory="${report.loc}" ruleset="${basedir}/pmd-ruleset.xml" />

      <cpd minimumTokenCount="50" outputFile="${report.loc}/cpd.xml">
         <fileset dir="${src.loc}">
            <include name="**/*.as" />
            <include name="**/*.mxml" />
         </fileset>
      </cpd>

      <metrics sourcedirectory="${src.loc}" outputfile="${report.loc}/javancss.xml" />
   </target>

   <target name="package" depends="package-default,package-instrument,asdocs" />

   <target name="package-default" depends="compile">
      <copy file="${bin.loc}/${build.finalName.as3}.${build.packaging}" todir="${dist.loc}" />
      <copy file="${bin.loc}/${build.finalName.flex}.${build.packaging}" todir="${dist.loc}" />
   </target>

   <target name="package-instrument" depends="instrument-compile" if="build.instrument">
      <copy file="${bin.loc}/${instrument.metadata}" todir="${dist.loc}" />
      <copy file="${bin.loc}/${instrument.finalName}.${build.packaging}" todir="${dist.loc}" />
   </target>

   <target name="deploy" depends="package" description="Requires Ant-Contrib and GPG to work.">
      <!-- deploy flex swc to sonatype -->
      <sonatype-deploy
           binaryFile="${bin.loc}/${build.finalName.flex}.${build.packaging}"
           todir="${sonatype.loc}/flex"
           pomTemplate="${basedir}/../pom.template"
           artifact="${build.artifactId}-flex"
           type="${build.packaging}"
           name="${build.deploy.name}"
           version="${build.version}"
           description="${build.deploy.description}">
      </sonatype-deploy>

       <!-- deploy as3 swc to sonatype -->
       <sonatype-deploy
           binaryFile="${bin.loc}/${build.finalName.as3}.${build.packaging}"
           todir="${sonatype.loc}/as3"
           pomTemplate="${basedir}/../pom.template"
           artifact="${build.artifactId}-as3"
           type="${build.packaging}"
           name="${build.deploy.name}"
           version="${build.version}"
           description="${build.deploy.description}">
       </sonatype-deploy>
   </target>
</project>


text:
'use strict';
const gulp = require('gulp');
const inject = require('gulp-inject-string');
const ts = require('gulp-typescript');
const merge = require('merge2');
const tsProject = ts.createProject('tsconfig.json');

gulp.task('compile', () => {
    const tsResult = tsProject.src().pipe(tsProject());
    return merge([
        tsResult.js.pipe(inject.replace('var fgui;', ''))
            .pipe(inject.replace(/ \|\| \(fgui = \{\}\)/, ''))
            .pipe(inject.prepend(';window.fairygui = window.fgui = {};'))
            .pipe(gulp.dest('./bin')),
        tsResult.dts.pipe(inject.append('import fairygui = fgui;'))
            .pipe(gulp.dest('./bin'))
    ]);
});

gulp.task('start', () => {
    gulp.watch(['src/**/*.ts'], gulp.series('compile'));
});

gulp.task('copy', () => {
    return merge([
        gulp.src('bin/*.js')
            .pipe(gulp.dest('../demo/bin/libs/fairygui/')),
        gulp.src('bin/*.ts')
            .pipe(gulp.dest('../demo/libs/'))
    ]);
});

gulp.task('build', gulp.series('compile', 'copy'));

redpajama_set_name: RedPajamaGithub


text:
namespace ash {

class ErrorScreensHistogramHelper;
class GaiaScreenHandler;

// A class that handles the WebUI hooks in sign-in screen in OobeUI.
class SigninScreenHandler
    : public BaseWebUIHandler,
      public content::NotificationObserver,
      public NetworkStateInformer::NetworkStateInformerObserver {
 public:
  SigninScreenHandler(
      const scoped_refptr<NetworkStateInformer>& network_state_informer,
      ErrorScreen* error_screen,
      GaiaScreenHandler* gaia_screen_handler);

  SigninScreenHandler(const SigninScreenHandler&) = delete;
  SigninScreenHandler& operator=(const SigninScreenHandler&) = delete;

  ~SigninScreenHandler() override;

  // Shows the sign in screen.
  void Show();

  // NetworkStateInformer::NetworkStateInformerObserver implementation:
  void UpdateState(NetworkError::ErrorReason reason) override;

  // To avoid spurious error messages on flaky networks, the offline message is
  // only shown if the network is offline for a threshold number of seconds.
  // This method provides an ability to reduce the threshold to zero, allowing
  // the offline message to show instantaneously in tests. The threshold can
  // also be set to a high value to disable the offline message on slow
  // configurations like MSAN, where it otherwise triggers on every run.
  void SetOfflineTimeoutForTesting(base::TimeDelta offline_timeout);

 private:
  friend class GaiaScreenHandler;

  void UpdateStateInternal(NetworkError::ErrorReason reason, bool force_update);
  void HideOfflineMessage(NetworkStateInformer::State state,
                          NetworkError::ErrorReason reason);
  void ReloadGaia(bool force_reload);

  // BaseScreenHandler implementation:
  void DeclareLocalizedValues(
      ::login::LocalizedValuesBuilder* builder) override;

  // content::NotificationObserver implementation:
  void Observe(int type,
               const content::NotificationSource& source,
               const content::NotificationDetails& details) override;

  // Returns true if current visible screen is the Gaia sign-in page.
  bool IsGaiaVisible();

  // Returns true if current visible screen is the error screen over
  // Gaia sign-in page.
  bool IsGaiaHiddenByError();

  net::Error FrameError() const;

  // After proxy auth information has been supplied, this function re-enables
  // responding to network state notifications.
  void ReenableNetworkStateUpdatesAfterProxyAuth();

  // Error screen hide callback which records error screen metrics and shows
  // GAIA.
  void OnErrorScreenHide();

  // This is a helper function to merge SigninScreenHandler with GaiaScreen and
  // GaiaScreenHandler classes. It will be removed together with the whole
  // SigninScreenHandler class.
  NetworkStateInformer::State GetNetworkStateInformerStateForMigration();

  // Network state informer used to keep signin screen up.
  scoped_refptr<NetworkStateInformer> network_state_informer_;

  ErrorScreen* error_screen_ = nullptr;

  NetworkStateInformer::State last_network_state_ =
      NetworkStateInformer::UNKNOWN;

  base::CancelableOnceCallback<void()> update_state_callback_;
  base::CancelableOnceCallback<void()> connecting_callback_;

  content::NotificationRegistrar registrar_;

  // Whether we're currently ignoring network state updates because a proxy auth
  // UI pending (or we're waiting for a grace period after the proxy auth UI is
  // finished for the network to switch into the ONLINE state).
  bool network_state_ignored_until_proxy_auth_ = false;

  // Used for pending GAIA reloads.
  NetworkError::ErrorReason gaia_reload_reason_ =
      NetworkError::ERROR_REASON_NONE;

  // If network has accidentally changed to the one that requires proxy
  // authentication, we will automatically reload gaia page that will bring
  // "Proxy authentication" dialog to the user. To prevent flakiness, we will do
  // it at most 3 times.
  int proxy_auth_dialog_reload_times_;

  // True if we need to reload gaia page to bring back "Proxy authentication"
  // dialog.
  bool proxy_auth_dialog_need_reload_ = false;

  // Non-owning ptr.
  // TODO(antrim@): remove this dependency.
  GaiaScreenHandler* gaia_screen_handler_ = nullptr;

  bool is_offline_timeout_for_test_set_ = false;
  base::TimeDelta offline_timeout_for_test_;

  std::unique_ptr<ErrorScreensHistogramHelper> histogram_helper_;

  base::WeakPtrFactory<SigninScreenHandler> weak_factory_{this};
};

}  // namespace ash

#endif  // CHROME_BROWSER_UI_WEBUI_ASH_LOGIN_SIGNIN_SCREEN_HANDLER_H_


text:
package de.craftolution.craftoplugin.module.extra.help;

import de.craftolution.craftoplugin.service.command.CommandResult;
import de.craftolution.craftoplugin.service.command.annotation.Aliases;
import de.craftolution.craftoplugin.service.command.annotation.CommandHandler;
import de.craftolution.craftoplugin.service.command.annotation.Permission;
import de.craftolution.craftoplugin.service.command.args.Args;
import de.craftolution.craftoplugin.service.messenger.text.ChatStyle;
import de.craftolution.craftoplugin.service.messenger.text.Text;
import de.craftolution.craftoplugin.service.messenger.text.TextTemplates;
import de.craftolution.craftoplugin.service.module.Component;
import de.craftolution.craftoplugin.service.module.utils.Utils;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;

public class HelpComponent extends Component implements Utils {

	@CommandHandler("help")
	@Permission("craftoplugin.extra.help")
	@Aliases("hilfe")
	public CommandResult onCommand(CommandSender cs, Args args) {
		sendNeutral(cs, "Für mehr Informationen schaue auf unserer Webseite vorbei:");

		Text text = Text.builder()
			.append(TextTemplates.RIGHT_POINTER + " ")
			.color(ChatColor.GRAY)
			.append("craftolution.de/faq")
			.color(ChatColor.GOLD)
			.style(ChatStyle.ITALIC)
			.onClickOpenUrl("https://craftolution.de/faq")
			.onInsertion("https://craftolution.de/faq")
			.onHover(ChatColor.GRAY + "Klicke hier um das FAQ zu öffnen...")
			.build();

		send(cs, text);

		return CommandResult.success();
	}

}


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe 'FrozenGems' do
  it 'pending' do
    pending
  end
end


text:
package com.fei_ke.chiphellclient.api.support;

import com.android.volley.toolbox.HurlStack;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.OkUrlFactory;

/**
 * Created by 杨金阳 on 2015/11/26.
 */
public class OkHttpStack extends HurlStack {
    private final OkUrlFactory okUrlFactory;

    public OkHttpStack() {
        this(new OkUrlFactory(new OkHttpClient()));
    }

    public OkHttpStack(OkUrlFactory okUrlFactory) {
        if (okUrlFactory == null) {
            throw new NullPointerException("Client must not be null.");
        }
        this.okUrlFactory = okUrlFactory;
    }

    @Override
    protected HttpURLConnection createConnection(URL url) throws IOException {
        return okUrlFactory.open(url);
    }
}


text:
require 'spec_helper'

describe 'The Hooker App' do
  include Rack::Test::Methods

  def app
    Hooker::Application
  end

  it "says alive" do
    get '/'
    expect(last_response).to be_ok
    expect(last_response.body).to eq('alive')
  end

  it "tweet build result of Travis CI" do
    allow_any_instance_of(Twitter::REST::Client).to receive(:update).and_return true
    payload = <<-BODY
{
  "build_url": "https://travis-ci.org/arukoh/Hooker/builds/1",
  "status_message": "Passed",
  "repository": { "name": "Hooker", "owner_name": "arukoh" }
}
    BODY
    URI.encode("payload=#{payload}")
    rack_env = {
      'HTTP_TRAVIS_REPO_SLUG' => 'arukoh/Hooker',
      'HTTP_AUTHORIZATION' => Digest::SHA2.hexdigest("arukoh/Hooker#{ENV['TRAVIS_USER_TOKEN']}")
    }
    post '/travis', travis_body, rack_env
    expect(last_response.status).to eq(204)
  end
end


text:
$(document).ready(function() {

    var cityName = "Nashville";

    $.get("http://api.openweathermap.org/data/2.5/forecast?q=" + cityName + "&units=imperial&APPID=a29fff7fa1bce3c0229d7f6f97530e87", function(data, status){
            console.log(data);  //just for visualization

            var name; var dateTime; var temp; var temp_max; var temp_min; var description; var windDeg; var windSpeed;

            for (var i = 0; i < data['list'].length; i++) {
                name = data['city']['name'];
                dateTime = data['list'][i]['dt_txt'];
                temp = data['list'][i]['main']['temp'];
                temp_max = data['list'][i]['main']['temp_max'];
                temp_min = data['list'][i]['main']['temp_min'];
                description = data['list'][i]['weather']['0']['description'];
                windDeg = data['list'][i]['wind']['deg'];
                windSpeed = data['list'][i]['wind']['speed'];

                console.log(description);

                if (i == 0) {
                    $("#currentTemp").text("");
                    $("#currentTemp").append("
Location: " + name + "
");
                    $("#currentTemp").append("
Date: " + dateTime + "
");
                    $("#currentTemp").append("
Current Temp: " + temp + "°F
");
                    $("#currentTemp").append("
High Temp: " + temp_max + "°F
");
                    $("#currentTemp").append("
Low Temp: " + temp_min + "°F
");
                    $("#currentTemp").append("
Wind Degree: " + windDeg + "°
");
                    $("#currentTemp").append("
Wind Speed: " + windSpeed + " mph
");

                } else if (i == 1) {
                    if (description.includes("sky")) {
                        $("#icon1").attr('src', 'icons/sunny.png');
                    } else if (description.includes("clouds")) {
                        $("#icon1").attr('src', 'icons/cloudy_no_sun.png');
                    } else if (description.includes("rain")) {
                        $("#icon1").attr('src', 'icons/rainy.png');
                    } else if (description.includes("sun")) {
                        $("#icon1").attr('src', 'icons/sunny.png');
                    } else if (description.includes("snow")) {
                        $("#icon1").attr('src', 'icons/snow.png');
                    } else if (description.includes("storm")) {
                        $("#icon1").attr('src', 'icons/storm.png');
                    } else if (description.includes("clear")) {
                        $("#icon1").attr('src', 'icons/sunny.png');
                    } else {
                        $("#icon1").attr('src', 'icons/cloudy.png');
                    }

                    $("#highTemp1").text(temp_max + "°F");
                    $("#description").text(description);
                } else if (i == 8) {
                    if (description.includes("sky")) {
                        $("#icon2").attr('src', 'icons/sunny.png');
                    } else if (description.includes("clouds")) {
                        $("#icon2").attr('src', 'icons/cloudy_no_sun.png');
                    } else if (description.includes("rain")) {
                        $("#icon2").attr('src', 'icons/rainy.png');
                    } else if (description.includes("sun")) {
                        $("#icon2").attr('src', 'icons/sunny.png');
                    } else if (description.includes("snow")) {
                        $("#icon2").attr('src', 'icons/snow.png');
                    } else if (description.includes("storm")) {
                        $("#icon2").attr('src', 'icons/storm.png');
                    } else if (description.includes("clear")) {
                        $("#icon2").attr('src', 'icons/sunny.png');
                    } else {
                        $("#icon2").attr('src', 'icons/cloudy.png');
                    }

                    $("#highTemp2").text(temp_max + "°F");
                    $("#description2").text(description);
                } else if (i == 16) {
                    if (description.includes("sky")) {
                        $("#icon3").attr('src', 'icons/sunny.png');
                    } else if (description.includes("clouds")) {
                        $("#icon3").attr('src', 'icons/cloudy_no_sun.png');
                    } else if (description.includes("rain")) {
                        $("#icon3").attr('src', 'icons/rainy.png');
                    } else if (description.includes("sun")) {
                        $("#icon3").attr('src', 'icons/sunny.png');
                    } else if (description.includes("snow")) {
                        $("#icon3").attr('src', 'icons/snow.png');
                    } else if (description.includes("storm")) {
                        $("#icon3").attr('src', 'icons/storm.png');
                    } else if (description.includes("clear")) {
                        $("#icon3").attr('src', 'icons/sunny.png');
                    } else {
                        $("#icon3").attr('src', 'icons/cloudy.png');
                    }

                    $("#highTemp3").text(temp_max + "°F");
                    $("#description3").text(description);
                } else if (i == 24) {
                    if (description.includes("sky")) {
                        $("#icon4").attr('src', 'icons/sunny.png');
                    } else if (description.includes("clouds")) {
                        $("#icon4").attr('src', 'icons/cloudy_no_sun.png');
                    } else if (description.includes("rain")) {
                        $("#icon4").attr('src', 'icons/rainy.png');
                    } else if (description.includes("sun")) {
                        $("#icon4").attr('src', 'icons/sunny.png');
                    } else if (description.includes("snow")) {
                        $("#icon4").attr('src', 'icons/snow.png');
                    } else if (description.includes("storm")) {
                        $("#icon4").attr('src', 'icons/storm.png');
                    } else if (description.includes("clear")) {
                        $("#icon4").attr('src', 'icons/sunny.png');
                    } else {
                        $("#icon4").attr('src', 'icons/cloudy.png');
                    }

                    $("#highTemp4").text(temp_max + "°F");
                    $("#description4").text(description);
                } else if (i == 32) {
                    if (description.includes("sky")) {
                        $("#icon5").attr('src', 'icons/sunny.png');
                    } else if (description.includes("clouds")) {
                        $("#icon5").attr('src', 'icons/cloudy_no_sun.png');
                    } else if (description.includes("rain")) {
                        $("#icon5").attr('src', 'icons/rainy.png');
                    } else if (description.includes("sun")) {
                        $("#icon5").attr('src', 'icons/sunny.png');
                    } else if (description.includes("snow")) {
                        $("#icon5").attr('src', 'icons/snow.png');
                    } else if (description.includes("storm")) {
                        $("#icon5").attr('src', 'icons/storm.png');
                    } else if (description.includes("clear")) {
                        $("#icon5").attr('src', 'icons/sunny.png');
                    } else {
                        $("#icon5").attr('src', 'icons/cloudy.png');
                    }

                    $("#highTemp5").text(temp_max + "°F");
                    $("#description5").text(description);
                }
            }

    });

});


text:
Ενοποιημμένες Ομάδες

<?php

  sleep(0.25);

  require('../parameteDB.php');

  try {
    //creating PDObject
    $pdoObject= new PDO("mysql:host=$dbhost;dbname=$dbname;", $dbuser, $dbpass);
    $pdoObject->exec('set names utf8');
    //creating parameterized query
    $sql = "SELECT * FROM schoolstudentgroup_professor_links WHERE professorID_byProfessors = :professorID_byProfessors ORDER BY schoolStudGroupProfesAbbrev ASC";
    //query preparing for avoiding SQL Injection
    $statement= $pdoObject->prepare($sql);
    //passing of the value in placeholders
    $statement->execute( array(':professorID_byProfessors'=>$_POST['professorID']));

    //query results loop for display
    while ( $record= $statement->fetch() ) {
      //για κάθε record αποτελέσματος κάνε το ακόλουθο

      $schooStudeGroupProfID= $record['schoolStudentGroupProfessorID'];
      $sql2 = " SELECT COUNT(schoolStudentGroupProfessorID) AS rowCounter
                   FROM eventplannedcourse_scarceresource_participantgroup_combis
                    WHERE schoolStudentGroupProfessorID = $schooStudeGroupProfID ";
       $statement2= $pdoObject->query($sql2);
       $record2=  $statement2->fetch();
      if ( $record2['rowCounter'] > 0 )
      { echo '
 - '.'' .$record['schoolStudGroupProfesAbbrev'].''.'x'.$record2['rowCounter'].'
'; }
      else
      { echo '
 - '.$record['schoolStudGroupProfesAbbrev'].'
'; };
      $statement2->closeCursor();

      echo '
 - '.$record['schoolStudGroupProfesAbbrev'].'
';

    }

    $statement->closeCursor();  //closing results dataset

    $pdoObject = null;        // database connect. ending
    echo '
* Οι τσεκαρισμένες είναι ανατεθημμένες ομάδες τουλάχιστο μια φορα.
';
  } catch (PDOException $e) {

      die("Database Error: " . $e->getMessage());
    }
?>


text:
package com.rest.um.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rest.common.persistence.service.AbstractService;
import com.rest.um.persistence.dao.IPrivilegeJpaDao;
import com.rest.um.persistence.model.Privilege;
import com.rest.um.service.IPrivilegeService;

@Service
@Transactional
public class PrivilegeServiceImpl extends AbstractService<Privilege> implements IPrivilegeService {

    @Autowired
    private IPrivilegeJpaDao dao;

    public PrivilegeServiceImpl() {
        super();
    }

    // API

    // find

    @Override
    public Privilege findByName(final String name) {
        return getDao().findByName(name);
    }

    // Spring

    @Override
    protected final IPrivilegeJpaDao getDao() {
        return dao;
    }

    @Override
    protected JpaSpecificationExecutor<Privilege> getSpecificationExecutor() {
        return dao;
    }

}


text:
struct ShowFilterInfo
{
    TCHAR   m_szName[1024];             // friendly name
    TCHAR   m_szVersion[32];            // version
    TCHAR   m_ClsidFilter[300];         // guid
    TCHAR   m_szFileName[MAX_PATH];     // file name
    TCHAR   m_szFileVersion[32];        // file version
    TCHAR   m_szCatName[1024];          // category name
    TCHAR   m_ClsidCat[300];            // category guid
    DWORD   m_dwInputs;                 // number input pins
    DWORD   m_dwOutputs;                // number output pins
    DWORD   m_dwMerit;                  // merit - in hex

    DWORD m_nElementCount;
};

struct ShowInfo
{
    vector<ShowFilterInfo*> m_vShowFilters;
};

#endif // SHOWINFO_H


text:
package eu.cdevreeze.springjdbc
package namedparam

import java.sql.{ Connection, Statement, PreparedStatement }
import scala.collection.immutable
import scala.reflect.ClassManifest
import org.springframework.jdbc.core.{ JdbcOperations => _, JdbcTemplate => _, _ }
import org.springframework.jdbc.core.namedparam._

/**
 * Scala `NamedParamJdbcOperations`, wrapping a Spring `NamedParameterJdbcOperations`. Unlike the wrapped Spring counterpart, immutable Scala collections
 * are used instead of Java collections (and Options instead of null).
 *
 * Other than that, the API closely resembles the wrapped API. As a consequence, this wrapper API also heavily uses overloaded
 * methods. This implies that the Spring callback interfaces are used as parameters instead of Scala functions. Fortunately,
 * using factory methods in `JdbcTemplateUtils`, Scala functions can easily be converted to Spring JDBC callback interfaces.
 *
 * For the methods named `execute` in the wrapped Spring counterpart, if needed, use that wrapped Spring counterpart.
 *
 * @author Chris de Vreeze
 */
trait NamedParamJdbcOperations {

  def wrappedObject: org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations

  // TODO Batch updates

  // Using typed args

  def query[A](sql: String, typedArgs: TypedArgMap, rse: ResultSetExtractor[A]): A

  def query[A](sql: String, typedArgs: TypedArgMap, rch: RowCallbackHandler): Unit

  def query[A](sql: String, typedArgs: TypedArgMap, rowMapper: RowMapper[A]): immutable.IndexedSeq[A]

  // Using args without SQL types

  def query[A](sql: String, args: Map[String, AnyRef], rse: ResultSetExtractor[A]): A

  def query[A](sql: String, args: Map[String, AnyRef], rch: RowCallbackHandler): Unit

  def query[A](sql: String, args: Map[String, AnyRef], rowMapper: RowMapper[A]): immutable.IndexedSeq[A]

  // Query for Int

  def queryForInt(sql: String, typedArgs: TypedArgMap): Int

  def queryForInt(sql: String, args: Map[String, AnyRef]): Int

  // Query for Long

  def queryForLong(sql: String, typedArgs: TypedArgMap): Long

  def queryForLong(sql: String, args: Map[String, AnyRef]): Long

  // Query for Map (record)

  def queryForMap(sql: String, typedArgs: TypedArgMap): Map[String, AnyRef]

  def queryForMap(sql: String, args: Map[String, AnyRef]): Map[String, AnyRef]

  // Query for Seq (sequence of records)

  def queryForSeq[A](sql: String, typedArgs: TypedArgMap, cls: Class[A]): immutable.IndexedSeq[A]

  def queryForSeq[A](sql: String, typedArgs: TypedArgMap): immutable.IndexedSeq[Map[String, AnyRef]]

  def queryForSeq[A](sql: String, args: Map[String, AnyRef], cls: Class[A]): immutable.IndexedSeq[A]

  def queryForSeq[A](sql: String, args: Map[String, AnyRef]): immutable.IndexedSeq[Map[String, AnyRef]]

  // Query for Object

  def queryForObject[A](sql: String, typedArgs: TypedArgMap, cls: Class[A]): A

  def queryForObject[A](sql: String, args: Map[String, AnyRef], cls: Class[A]): A

  def queryForObject[A](sql: String, typedArgs: TypedArgMap, rowMapper: RowMapper[A]): A

  def queryForObject[A](sql: String, args: Map[String, AnyRef], rowMapper: RowMapper[A]): A

  // Updates

  def update(sql: String, args: Map[String, AnyRef]): Int

  def update(sql: String, typedArgs: TypedArgMap): Int
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

const ADDON = "test_bug521905";
const ID = "bug521905@tests.mozilla.org";

// Disables security checking our updates which haven't been signed
Services.prefs.setBoolPref("extensions.checkUpdateSecurity", false);

function run_test() {
  // This test is only relevant on builds where the version is included in the
  // checkCompatibility preference name
  if (isNightlyChannel()) {
    return;
  }

  do_test_pending();
  createAppInfo("xpcshell@tests.mozilla.org", "XPCShell", "2.0pre", "2");

  startupManager();
  AddonManager.checkCompatibility = false;

  installAllFiles([do_get_addon(ADDON)], function() {
    restartManager();

    AddonManager.getAddonByID(ID, function(addon) {
      do_check_neq(addon, null);
      do_check_true(addon.isActive);

      run_test_1();
    });
  });
}

function run_test_1() {
  Services.prefs.setBoolPref("extensions.checkCompatibility.2.0pre", true);

  restartManager();
  AddonManager.getAddonByID(ID, function(addon) {
    do_check_neq(addon, null);
    do_check_false(addon.isActive);

    run_test_2();
  });
}

function run_test_2() {
  Services.prefs.setBoolPref("extensions.checkCompatibility.2.0p", false);

  restartManager();
  AddonManager.getAddonByID(ID, function(addon) {
    do_check_neq(addon, null);
    do_check_false(addon.isActive);

    do_test_finished();
  });
}


text:
justjournal
===========

JustJournal.com's Source

Just Journal is a blogging web application that supports multiple users and has clients in
C#, Java, Apple's Dashboard (javascript), and unix command line (C)

JustJournal is developed on JDK 1.8 (java 8) on Linux
using MySQL 8.0 and Spring Boot 2.2.x.  It has been successfully
deployed on MidnightBSD 2.1 with the OpenJDK 1.8 JDK using MySQL 8.0.

Fore more information, see the INSTALL file

[![DepShield Badge](https://depshield.sonatype.org/badges/laffer1/justjournal/depshield.svg)](https://depshield.github.io)[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Flaffer1%2Fjustjournal.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Flaffer1%2Fjustjournal?ref=badge_shield)

## License
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Flaffer1%2Fjustjournal.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Flaffer1%2Fjustjournal?ref=badge_large)


text:
package com.netflix.hystrix.metric.consumer;

import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.metric.CommandStreamTest;
import com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Subscriber;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.*;

public class RollingThreadPoolMaxConcurrencyStreamTest extends CommandStreamTest {
    RollingThreadPoolMaxConcurrencyStream stream;
    HystrixRequestContext context;
    ExecutorService threadPool;

    private static Subscriber<Integer> getSubscriber(final CountDownLatch latch) {
        return new Subscriber<Integer>() {
            @Override
            public void onCompleted() {
                latch.countDown();
            }

            @Override
            public void onError(Throwable e) {
                fail(e.getMessage());
            }

            @Override
            public void onNext(Integer maxConcurrency) {
                System.out.println("OnNext @ " + System.currentTimeMillis() + " : Max of " + maxConcurrency);
            }
        };
    }

    @Before
    public void setUp() {
        context = HystrixRequestContext.initializeContext();
        threadPool = Executors.newFixedThreadPool(20);
    }

    @After
    public void tearDown() {
        context.shutdown();
        stream.unsubscribe();
        RollingCommandMaxConcurrencyStream.reset();
        threadPool.shutdown();
    }

    @Test
    public void testEmptyStreamProducesZeros() {
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-A");
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-A");
        HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-A");
        stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
        stream.startCachingStreamValuesIfUnstarted();

        final CountDownLatch latch = new CountDownLatch(1);
        stream.observe().take(10).subscribe(getSubscriber(latch));

        //no writes

        try {
            assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
        } catch (InterruptedException ex) {
            fail("Interrupted ex");
        }
        assertEquals(0, stream.getLatestRollingMax());
    }

    @Test
    public void testStartsAndEndsInSameBucketProduceValue() throws InterruptedException {
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-B");
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-B");
        HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-B");
        stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
        stream.startCachingStreamValuesIfUnstarted();

        final CountDownLatch latch = new CountDownLatch(1);
        stream.observe().take(10).subscribe(getSubscriber(latch));

        Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 50);
        Command cmd2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 40);

        cmd1.observe();
        Thread.sleep(1);
        cmd2.observe();

        assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
        assertEquals(2, stream.getLatestRollingMax());
    }

    @Test
    public void testStartsAndEndsInSameBucketSemaphoreIsolated() throws InterruptedException {
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-C");
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-C");
        HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-C");
        stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
        stream.startCachingStreamValuesIfUnstarted();

        final CountDownLatch latch = new CountDownLatch(1);
        stream.observe().take(10).subscribe(getSubscriber(latch));

        Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
        Command cmd2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 14, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);

        cmd1.observe();
        Thread.sleep(1);
        cmd2.observe();

        assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
        //since commands run in semaphore isolation, they are not tracked by threadpool metrics
        assertEquals(0, stream.getLatestRollingMax());
    }

    /***
     * 3 Commands,
     * Command 1 gets started in Bucket A and not completed until Bucket B
     * Commands 2 and 3 both start and end in Bucket B, and there should be a max-concurrency of 3
     */
    @Test
    public void testOneCommandCarriesOverToNextBucket() throws InterruptedException {
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-D");
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-D");
        HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-D");
        stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
        stream.startCachingStreamValuesIfUnstarted();

        final CountDownLatch latch = new CountDownLatch(1);
        stream.observe().take(10).subscribe(getSubscriber(latch));

        Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 560);
        Command cmd2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 50);
        Command cmd3 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 75);

        cmd1.observe();
        Thread.sleep(150); //bucket roll
        cmd2.observe();
        Thread.sleep(1);
        cmd3.observe();

        assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
        assertEquals(3, stream.getLatestRollingMax());
    }

    /**
     * BUCKETS
     *     A    |    B    |    C    |    D    |    E    |
     * 1:  [-------------------------------]
     * 2:          [-------------------------------]
     * 3:                      [--]
     * 4:                              [--]
     *
     * Max concurrency should be 3
     */
    @Test
    public void testMultipleCommandsCarryOverMultipleBuckets() throws InterruptedException {
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-E");
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-E");
        HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-E");
        stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
        stream.startCachingStreamValuesIfUnstarted();

        final CountDownLatch latch = new CountDownLatch(1);
        stream.observe().take(10).subscribe(getSubscriber(latch));

        Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 300);
        Command cmd2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 300);
        Command cmd3 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10);
        Command cmd4 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10);

        cmd1.observe();
        Thread.sleep(100); //bucket roll
        cmd2.observe();
        Thread.sleep(100);
        cmd3.observe();
        Thread.sleep(100);
        cmd4.observe();

        assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
        assertEquals(3, stream.getLatestRollingMax());
    }

    /**
     * BUCKETS
     *     A    |    B    |    C    |    D    |    E    |
     * 1:  [-------------------------------]              ThreadPool x
     * 2:          [-------------------------------]                 y
     * 3:                      [--]                                  x
     * 4:                              [--]                          x
     *
     * Same input data as above test, just that command 2 runs in a separate threadpool, so concurrency should not get tracked
     * Max concurrency should be 2 for x
     */
    @Test
    public void testMultipleCommandsCarryOverMultipleBucketsForMultipleThreadPools() throws InterruptedException {
        HystrixCommandGroupKey groupKeyX = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-X");
        HystrixCommandGroupKey groupKeyY = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-Y");
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-X");
        HystrixCommandKey keyX = HystrixCommandKey.Factory.asKey("RollingConcurrency-X");
        HystrixCommandKey keyY = HystrixCommandKey.Factory.asKey("RollingConcurrency-Y");
        stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
        stream.startCachingStreamValuesIfUnstarted();

        final CountDownLatch latch = new CountDownLatch(1);
        stream.observe().take(10).subscribe(getSubscriber(latch));

        Command cmd1 = Command.from(groupKeyX, keyX, HystrixEventType.SUCCESS, 300);
        Command cmd2 = Command.from(groupKeyY, keyY, HystrixEventType.SUCCESS, 300);
        Command cmd3 = Command.from(groupKeyX, keyY, HystrixEventType.SUCCESS, 10);
        Command cmd4 = Command.from(groupKeyX, keyY, HystrixEventType.SUCCESS, 10);

        cmd1.observe();
        Thread.sleep(100); //bucket roll
        cmd2.observe();
        Thread.sleep(100);
        cmd3.observe();
        Thread.sleep(100);
        cmd4.observe();

        assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
        assertEquals(2, stream.getLatestRollingMax());
    }

    /**
     * BUCKETS
     *     A    |    B    |    C    |    D    |    E    |
     * 1:  [-------------------------------]
     * 2:          [-------------------------------]
     * 3:                      [--]
     * 4:                              [--]
     *
     * Max concurrency should be 3, but by waiting for 30 bucket rolls, final max concurrency should be 0
     */
    @Test
    public void testMultipleCommandsCarryOverMultipleBucketsAndThenAgeOut() throws InterruptedException {
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-F");
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-F");
        HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-F");
        stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
        stream.startCachingStreamValuesIfUnstarted();

        final CountDownLatch latch = new CountDownLatch(1);
        stream.observe().take(30).subscribe(getSubscriber(latch));

        Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 300);
        Command cmd2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 300);
        Command cmd3 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10);
        Command cmd4 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10);

        cmd1.observe();
        Thread.sleep(100); //bucket roll
        cmd2.observe();
        Thread.sleep(100);
        cmd3.observe();
        Thread.sleep(100);
        cmd4.observe();

        assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
        assertEquals(0, stream.getLatestRollingMax());
    }

    @Test
    public void testConcurrencyStreamProperlyFiltersOutResponseFromCache() throws InterruptedException {
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-G");
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-G");
        HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-G");
        stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
        stream.startCachingStreamValuesIfUnstarted();

        final CountDownLatch latch = new CountDownLatch(1);
        stream.observe().take(10).subscribe(getSubscriber(latch));

        Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 40);
        Command cmd2 = Command.from(groupKey, key, HystrixEventType.RESPONSE_FROM_CACHE);
        Command cmd3 = Command.from(groupKey, key, HystrixEventType.RESPONSE_FROM_CACHE);
        Command cmd4 = Command.from(groupKey, key, HystrixEventType.RESPONSE_FROM_CACHE);

        cmd1.observe();
        Thread.sleep(5);
        cmd2.observe();
        cmd3.observe();
        cmd4.observe();

        assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
        System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
        assertTrue(cmd2.isResponseFromCache());
        assertTrue(cmd3.isResponseFromCache());
        assertTrue(cmd4.isResponseFromCache());
        assertEquals(1, stream.getLatestRollingMax());
    }

    @Test
    public void testConcurrencyStreamProperlyFiltersOutShortCircuits() throws InterruptedException {
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-H");
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-H");
        HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-H");
        stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
        stream.startCachingStreamValuesIfUnstarted();

        final CountDownLatch latch = new CountDownLatch(1);
        stream.observe().take(10).subscribe(getSubscriber(latch));

        //after 3 failures, next command should short-circuit.
        //to prove short-circuited commands don't contribute to concurrency, execute 3 FAILURES in the first bucket sequentially
        //then when circuit is open, execute 20 concurrent commands.  they should all get short-circuited, and max concurrency should be 1
        Command failure1 = Command.from(groupKey, key, HystrixEventType.FAILURE);
        Command failure2 = Command.from(groupKey, key, HystrixEventType.FAILURE);
        Command failure3 = Command.from(groupKey, key, HystrixEventType.FAILURE);

        List<Command> shortCircuited = new ArrayList<Command>();

        for (int i = 0; i < 20; i++) {
            shortCircuited.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 100));
        }

        failure1.execute();
        failure2.execute();
        failure3.execute();

        Thread.sleep(150);

        for (Command cmd: shortCircuited) {
            cmd.observe();
        }

        assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
        System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
        for (Command cmd: shortCircuited) {
            assertTrue(cmd.isResponseShortCircuited());
        }
        assertEquals(1, stream.getLatestRollingMax());
    }

    @Test
    public void testConcurrencyStreamProperlyFiltersOutSemaphoreRejections() throws InterruptedException {
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-I");
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-I");
        HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-I");
        stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
        stream.startCachingStreamValuesIfUnstarted();

        final CountDownLatch latch = new CountDownLatch(1);
        stream.observe().take(10).subscribe(getSubscriber(latch));

        //10 commands executed concurrently on different caller threads should saturate semaphore
        //once these are in-flight, execute 10 more concurrently on new caller threads.
        //since these are semaphore-rejected, the max concurrency should be 10

        List<Command> saturators = new ArrayList<Command>();
        for (int i = 0; i < 10; i++) {
            saturators.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 400, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE));
        }

        final List<Command> rejected = new ArrayList<Command>();
        for (int i = 0; i < 10; i++) {
            rejected.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 100, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE));
        }

        for (final Command saturatingCmd: saturators) {
            threadPool.submit(new HystrixContextRunnable(new Runnable() {
                @Override
                public void run() {
                    saturatingCmd.observe();
                }
            }));
        }

        Thread.sleep(30);

        for (final Command rejectedCmd: rejected) {
            threadPool.submit(new HystrixContextRunnable(new Runnable() {
                @Override
                public void run() {
                    rejectedCmd.observe();
                }
            }));
        }

        assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
        System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());

        for (Command rejectedCmd: rejected) {
            assertTrue(rejectedCmd.isResponseSemaphoreRejected() || rejectedCmd.isResponseShortCircuited());
        }
        //should be 0 since all are executed in a semaphore
        assertEquals(0, stream.getLatestRollingMax());
    }

    @Test
    public void testConcurrencyStreamProperlyFiltersOutThreadPoolRejections() throws InterruptedException {
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-J");
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-J");
        HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-J");
        stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
        stream.startCachingStreamValuesIfUnstarted();

        final CountDownLatch latch = new CountDownLatch(1);
        stream.observe().take(10).subscribe(getSubscriber(latch));

        //10 commands executed concurrently should saturate the Hystrix threadpool
        //once these are in-flight, execute 10 more concurrently
        //since these are threadpool-rejected, the max concurrency should be 10

        List<Command> saturators = new ArrayList<Command>();
        for (int i = 0; i < 10; i++) {
            saturators.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 400));
        }

        final List<Command> rejected = new ArrayList<Command>();
        for (int i = 0; i < 10; i++) {
            rejected.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 100));
        }

        for (final Command saturatingCmd: saturators) {
            saturatingCmd.observe();
        }

        Thread.sleep(30);

        for (final Command rejectedCmd: rejected) {
            rejectedCmd.observe();
        }

        assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
        System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
        for (Command rejectedCmd: rejected) {
            assertTrue(rejectedCmd.isResponseThreadPoolRejected());
        }

        //this should not count rejected commands
        assertEquals(10, stream.getLatestRollingMax());
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <parent>
    <groupId>io.enmasse</groupId>
    <artifactId>enmasse</artifactId>
    <version>0.34-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <artifactId>api-model</artifactId>
  <dependencies>
    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>kubernetes-model</artifactId>
    </dependency>
    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>kubernetes-client</artifactId>
    </dependency>
    <dependency>
      <groupId>io.sundr</groupId>
      <artifactId>builder-annotations</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.hibernate.validator</groupId>
      <artifactId>hibernate-validator</artifactId>
    </dependency>
    <dependency>
      <groupId>org.hibernate.validator</groupId>
      <artifactId>hibernate-validator-annotation-processor</artifactId>
    </dependency>
    <dependency>
      <groupId>org.jboss.spec.javax.el</groupId>
      <artifactId>jboss-el-api_3.0_spec</artifactId>
    </dependency>
    <dependency>
      <groupId>org.glassfish</groupId>
      <artifactId>javax.el</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>

    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-params</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.platform</groupId>
      <artifactId>junit-platform-launcher</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
@interface UIImage ()
@end

@implementation UIImage (Resize)

// Returns a rescaled copy of the image, taking into account its orientation
// The image will be scaled disproportionately if necessary to fit the bounds specified by the parameter
- (UIImage *)resizedImage:(CGSize)newSize interpolationQuality:(CGInterpolationQuality)quality {
    BOOL drawTransposed;

    switch (self.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            drawTransposed = YES;
            break;

        default:
            drawTransposed = NO;
    }

    return [self resizedImage:newSize
               drawTransposed:drawTransposed
         interpolationQuality:quality];
}

// Resizes the image according to the given content mode, taking into account the image's orientation
- (UIImage *)resizedImageWithContentMode:(UIViewContentMode)contentMode
                                  bounds:(CGSize)bounds
                    interpolationQuality:(CGInterpolationQuality)quality {
    CGFloat horizontalRatio = bounds.width / self.size.width;
    CGFloat verticalRatio = bounds.height / self.size.height;
    CGFloat ratio;

    switch (contentMode) {
        case UIViewContentModeScaleAspectFill:
            ratio = MAX(horizontalRatio, verticalRatio);
            break;

        case UIViewContentModeScaleAspectFit:
            ratio = MIN(horizontalRatio, verticalRatio);
            break;

        default:
            [NSException raise:NSInvalidArgumentException format:@"Unsupported content mode"];
    }

    CGSize newSize = CGSizeMake(self.size.width * ratio, self.size.height * ratio);

    return [self resizedImage:newSize interpolationQuality:quality];
}

#pragma mark -
#pragma mark Private helper methods

// Returns a copy of the image that has been transformed using the given affine transform and scaled to the new size
// The new image's orientation will be UIImageOrientationUp, regardless of the current image's orientation
// If the new size is not integral, it will be rounded up
- (UIImage *)resizedImage:(CGSize)newSize
           drawTransposed:(BOOL)transpose
     interpolationQuality:(CGInterpolationQuality)quality {
    CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
    CGRect transposedRect = CGRectMake(0, 0, newRect.size.height, newRect.size.width);
    CGImageRef imageRef = self.CGImage;

    // Build a context that's the same dimensions as the new size
    CGContextRef bitmap = CGBitmapContextCreate(NULL,
                                                newRect.size.width,
                                                newRect.size.height,
                                                CGImageGetBitsPerComponent(imageRef),
                                                0,
                                                CGImageGetColorSpace(imageRef),
                                                CGImageGetBitmapInfo(imageRef));

    // Set the quality level to use when rescaling
    CGContextSetInterpolationQuality(bitmap, quality);

    // Draw into the context; this scales the image
    CGContextDrawImage(bitmap, transpose ? transposedRect : newRect, imageRef);

    // Get the resized image from the context and a UIImage
    CGImageRef newImageRef = CGBitmapContextCreateImage(bitmap);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

    // Clean up
    CGContextRelease(bitmap);
    CGImageRelease(newImageRef);

    return newImage;
}

@end


text:
@interface IQSelectedMediaPhotoCell ()

@end

@implementation IQSelectedMediaPhotoCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        self.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];

        _imageViewPreview = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
        _imageViewPreview.clipsToBounds = YES;
        _imageViewPreview.contentMode = UIViewContentModeScaleAspectFill;
        [self.contentView addSubview:_imageViewPreview];
    }
    return self;
}

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    BOOL canPerform = [super canPerformAction:action withSender:sender];

    if (canPerform == NO)
    {
        if (action == @selector(delete:))
        {
            canPerform = YES;
        }
    }

    return canPerform;
}

-(void)delete:(id)sender
{
    UIResponder *collectionViewResponder = [self nextResponder];

    do {
        if ([collectionViewResponder isKindOfClass:[UICollectionView class]])
        {
            break;
        }
        else
        {
            collectionViewResponder = [self nextResponder];
        }
    } while (collectionViewResponder != nil);

    if ([collectionViewResponder isKindOfClass:[UICollectionView class]])
    {
        UICollectionView *collectionView = (UICollectionView*)collectionViewResponder;

        if ([collectionView.delegate respondsToSelector:@selector(collectionView:performAction:forItemAtIndexPath:withSender:)])
        {
            NSIndexPath *indexPath = [collectionView indexPathForCell:self];

            [collectionView.delegate collectionView:collectionView performAction:_cmd forItemAtIndexPath:indexPath withSender:sender];
        }
    }
}

@end


text:
package syntax

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"
)

// Allow types to mark themselves as valid for TLS to marshal/unmarshal
type Validator interface {
	ValidForTLS() error
}

var (
	validatorType = reflect.TypeOf(new(Validator)).Elem()
)

// `tls:"head=2,min=2,max=255,varint"`

type fieldOptions struct {
	omitHeader   bool // whether to omit the slice header
	varintHeader bool // whether to encode the header length as a varint
	headerSize   int  // length of length in bytes
	minSize      int  // minimum vector size in bytes
	maxSize      int  // maximum vector size in bytes

	varint   bool // whether to encode as a varint
	optional bool // whether to encode pointer as optional
	omit     bool // whether to skip a field
}

func mutuallyExclusive(vals []bool) bool {
	set := 0
	for _, val := range vals {
		if val {
			set += 1
		}
	}
	return set <= 1
}

func (opts fieldOptions) Consistent() bool {
	// No more than one of the header options must be set
	headerPaths := []bool{opts.omitHeader, opts.varintHeader, opts.headerSize > 1}
	if !mutuallyExclusive(headerPaths) {
		return false
	}

	// Max must be greater than min
	if opts.maxSize > 0 && opts.minSize > opts.maxSize {
		return false
	}

	// varint and optional are mutually exclusive with each other, and with the slice options
	headerOpts := (opts.omitHeader || opts.varintHeader || opts.headerSize > 1 || opts.maxSize > 0 || opts.minSize > 0)
	encodePaths := []bool{headerOpts, opts.varint, opts.optional}
	if !mutuallyExclusive(encodePaths) {
		return false
	}

	// Omit is mutually exclusive with everything else
	otherThanOmit := (headerOpts || opts.varint || opts.optional)
	if !mutuallyExclusive([]bool{opts.omit, otherThanOmit}) {
		return false
	}

	return true
}

func (opts fieldOptions) ValidForType(t reflect.Type) bool {
	headerType := t.Kind() == reflect.Slice || t.Kind() == reflect.Map
	headerTags := opts.omitHeader || opts.varintHeader || (opts.headerSize != 0) ||
		(opts.minSize != 0) || (opts.maxSize != 0)
	if headerTags && !headerType {
		return false
	}

	uintRequired := opts.varint
	if uintRequired {
		switch t.Kind() {
		case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		default:
			return false
		}
	}

	ptrRequired := opts.optional
	if ptrRequired && t.Kind() != reflect.Ptr {
		return false
	}

	return true
}

var (
	varintOption   = "varint"
	optionalOption = "optional"
	omitOption     = "omit"

	headOptionNone   = "none"
	headOptionVarint = "varint"
	headValueNoHead  = uint(255)
	headValueVarint  = uint(254)

	optionalFlagAbsent  uint8 = 0
	optionalFlagPresent uint8 = 1
)

func atoi(a string) int {
	i, err := strconv.Atoi(a)
	if err != nil {
		panic(fmt.Errorf("Invalid header size: %v", err))
	}
	return i
}

// parseTag parses a struct field's "tls" tag as a comma-separated list of
// name=value pairs, where the values MUST be unsigned integers, or in
// the special case of head, "none" or "varint"
func parseTag(tag string) fieldOptions {
	opts := fieldOptions{}
	for _, token := range strings.Split(tag, ",") {
		parts := strings.Split(token, "=")

		// Handle name-only entries
		if len(parts) == 1 {
			switch parts[0] {
			case varintOption:
				opts.varint = true
			case optionalOption:
				opts.optional = true
			case omitOption:
				opts.omit = true
			default:
				// XXX(rlb): Ignoring unknown fields
			}
			continue
		}

		if len(parts) != 2 || len(parts[0]) == 0 || len(parts[1]) == 0 {
			panic(fmt.Errorf("Malformed tag"))
		}

		// Handle name=value entries
		switch parts[0] {
		case "head":
			switch {
			case parts[1] == headOptionNone:
				opts.omitHeader = true
			case parts[1] == headOptionVarint:
				opts.varintHeader = true
			default:
				opts.headerSize = atoi(parts[1])
			}

		case "min":
			opts.minSize = atoi(parts[1])

		case "max":
			opts.maxSize = atoi(parts[1])

		default:
			// XXX(rlb): Ignoring unknown fields
		}
	}

	if !opts.Consistent() {
		panic(fmt.Errorf("Inconsistent options"))
	}

	return opts
}


text:
package ru.semiot.simulators.heatmeter;

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

public class TestimonialStore {

    private static final Map<Integer, Testimonial> data = new HashMap<>();
    private static final TestimonialStore instance = new TestimonialStore();
    private final List<IListener> listeners = new ArrayList<>();
    private int current_id = 0;

    public TestimonialStore() {
    }

    public static TestimonialStore getInstance() {
        return instance;
    }

    public int getNextId() {
        return current_id++;
    }

    public int getId() {
        return current_id;
    }

    public void addListener(IListener listener) {
        listeners.add(listener);
    }

    public Testimonial getData(int id) {
        if (data.containsKey(id)) {
            return data.get(id);
        } else {
            return null;
        }
    }

    public void setData(double temperature, double heat, int id) {
        Testimonial t;
        if (!data.containsKey(id)) {
            for (IListener l : listeners) {
                l.onCreated(id);
            }
            data.put(id, new Testimonial());
        }
        t = data.get(id);
        t.update(temperature, heat);
        for (IListener l : listeners) {
            l.onUpdated(id, t);
        }
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}
module Main where
import AlgebraicPrelude

default (Fraction Integer)

arg, main :: IO ()
arg = do
  putStrLn "Good morning everybody!"
  if True
  then print (5.2 :: Rational)
  else print $ take 5 [1 :: Double,2,345]
main = arg


text:
package com.test.controller;

import static org.hamcrest.CoreMatchers.is;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import com.test.service.GreetingService;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

/**
 * Unit tests for the {@link HomeController} class.
 *
 * Note: Serice mocks need to be defined in src/test/resources/app-config.xml.
 *
 * @author David
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:app-config.xml", "file:src/main/webapp/WEB-INF/spring/mvc-config.xml" })
public class HomeControllerTests {

	/** The web application context. */
	@Autowired
	private WebApplicationContext 	wac;

	/** The mock MVC. */
	private MockMvc 				mockMvc;

	/** The greeting service. */
	@Autowired
	private GreetingService 		greetingService;

	/**
	 * Sets up the test.
	 */
	@Before
	public void setup() {
		mockMvc = webAppContextSetup(wac).build();
	}

	/**
	 * Tests /home.
	 */
	@Test
	public void testMain() throws Exception {
		mockMvc
			.perform(get("/home")
				.accept(MediaType.TEXT_HTML))
  			.andDo(print())
			.andExpect(status().isOk())
			.andExpect(view().name("home/index"));
	}

	/**
	 * Tests /home.
	 */
	@Test
	public void testSayHello() throws Exception {
		when(greetingService.randomGreeting()).thenReturn("Hello");

		mockMvc
			.perform(post("/home")
				.accept(MediaType.TEXT_HTML)
				.contentType(MediaType.APPLICATION_FORM_URLENCODED)
				.param("name", "bob"))
  			.andDo(print())
			.andExpect(status().isOk())
			.andExpect(model().attributeExists("greeting"))
			.andExpect(model().attribute("name", is("bob")))
			.andExpect(view().name("home/hello"));

		verify(greetingService).randomGreeting();
	}
}


text:
namespace Selenium.WebDriver.Extensions.IntegrationTests.Fixtures
{
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using JetBrains.Annotations;
    using OpenQA.Selenium.Chrome;

    [UsedImplicitly]
    [ExcludeFromCodeCoverage]
    public class ChromeFixture : FixtureBase
    {
        public ChromeFixture()
        {
            var options = new ChromeOptions();
            options.AddArgument("--headless");
            Browser = new ChromeDriver(Path.GetDirectoryName(typeof(ChromeFixture).Assembly.Location), options);
        }
    }
}


text:
<?php

namespace Cekurte\WebScrapingBundle\Tests\Template\Outlet;

use Cekurte\WebScrapingBundle\Selector\Core\LinkSelector;
use Cekurte\WebScrapingBundle\Selector\Core\MetaSelector;
use Cekurte\WebScrapingBundle\Selector\Outlet\TechCrunchArticleSelector;
use Cekurte\WebScrapingBundle\Selector\Outlet\TechCrunchAuthorSelector;
use Cekurte\WebScrapingBundle\Template\Core\ArticleTemplateInterface;
use Cekurte\WebScrapingBundle\Template\Outlet\TechCrunchArticleTemplate;
use Symfony\Component\DomCrawler\Crawler;

class TechCrunchArticleTemplateTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ArticleTemplateInterface
     */
    private $article;

    public function setUp()
    {
        $body = <<<EOT

    <meta name="description" content="description" />
    <meta name="keywords" content="val1,val2,val3" />
    <meta name="charset" content="utf-8" />
    <meta property="og:site_name" content="og_site_name" />
    <meta property="og:title" content="og_title" />
    <meta property="og:description" content="og_description" />
    <meta property="og:image" content="og_image" />
    <meta property="og:url" content="og_url" />
    <link href="fakeurl" rel="canonical" />

ArticleTitle

            AuthorName

                Twitter

                <time class="timestamp" datetime="2015-06-27"></time>

P1

P2

EOT;

        $this->article = new TechCrunchArticleTemplate(
            new Crawler($body),
            new TechCrunchArticleSelector(
                new TechCrunchAuthorSelector(),
                new MetaSelector(),
                new LinkSelector()
            )
        );
    }

    public function testImplementsArticleTemplateInterface()
    {
        $reflection = new \ReflectionClass(
            '\\Cekurte\\WebScrapingBundle\\Template\\Outlet\\TechCrunchArticleTemplate'
        );

        $this->assertTrue($reflection->implementsInterface(
            '\\Cekurte\\WebScrapingBundle\\Template\\Core\\ArticleTemplateInterface'
        ));
    }

    public function testGetTitle()
    {
        $this->assertEquals('ArticleTitle', $this->article->getTitle());
    }

    public function testGetImage()
    {
        $this->assertEquals('og_image', $this->article->getImage());
    }

    public function testGetUrl()
    {
        $this->assertEquals('fakeurl', $this->article->getUrl());
    }

    public function testGetAbstract()
    {
        $this->assertEquals('P1', $this->article->getAbstract());
    }

    public function testGetContent()
    {
        $crawler = new Crawler($this->article->getContent());

        $this->assertEquals(2, $crawler->filter('p')->count());

        $this->assertEquals('P1', $crawler->filter('p')->first()->text());
        $this->assertEquals('P2', $crawler->filter('p')->last()->text());
    }

    public function testGetPublicationDate()
    {
        $this->assertInstanceOf('\\DateTime', $this->article->getPublicationDate());

        $this->assertEquals('2015', $this->article->getPublicationDate()->format('Y'));
        $this->assertEquals('06', $this->article->getPublicationDate()->format('m'));
        $this->assertEquals('27', $this->article->getPublicationDate()->format('d'));
    }

    public function testGetAuthor()
    {
        $this->assertInstanceOf(
            '\\Cekurte\\WebScrapingBundle\\Template\\Core\\AuthorTemplateInterface',
            $this->article->getAuthor()
        );
    }

    public function testGetMeta()
    {
        $this->assertInstanceOf(
            '\\Cekurte\\WebScrapingBundle\\Template\\Core\\MetaTemplateInterface',
            $this->article->getMeta()
        );
    }

    public function testGetLink()
    {
        $this->assertInstanceOf(
            '\\Cekurte\\WebScrapingBundle\\Template\\Core\\LinkTemplateInterface',
            $this->article->getLink()
        );
    }
}


text:
package com.ineat.quickadapter.exceptions;

/**
 * Created by mslimani on 13/10/2016.
 */

public class NotAccessItemRendererException extends RuntimeException {

    public NotAccessItemRendererException(String message) {
        super(message);
    }
}


text:
@implementation OutlineCollection

@synthesize childObject;
@synthesize objectTitle;
@synthesize projectTitle;

@synthesize projectDescription;
@synthesize flagPublic;
@synthesize startDateReal;
@synthesize endDateReal;
@synthesize completed;
@synthesize projectStatus;
@synthesize projectPercentage;
@synthesize percentageCompleteString;
@synthesize projectId;
@synthesize childProject;

@synthesize startDate;
@synthesize endDate;

- (BOOL)isLeaf {
    if ([childObject count] > 0)
        return NO;
    else
        return YES;
}

- (id)copyWithZone:(NSZone *)zone {

    OutlineCollection *copy = [[OutlineCollection alloc] init];

    copy.objectTitle = [objectTitle copyWithZone:zone];

    copy.projectTitle = [projectTitle copyWithZone:zone];
    copy.projectId = [projectId copyWithZone:zone];
    copy.projectDescription = [projectDescription copyWithZone:zone];
    copy.endDate = [endDate copyWithZone:zone];
    copy.endDateReal = [endDateReal copyWithZone:zone];
    copy.flagPublic = flagPublic;
    copy.completed = completed;
    copy.startDate = [startDate copyWithZone:zone];
    copy.startDateReal = [startDateReal copyWithZone:zone];
    copy.childProject = [childProject copyWithZone:zone];

    copy.projectPercentage = [projectPercentage copyWithZone:zone];
    copy.projectStatus = [projectStatus copyWithZone:zone];

    return copy;
}

@end


text:
package me.semx11.autotip.message;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import me.semx11.autotip.gson.exclusion.Exclude;

public class HoverMessage extends Message {

    @Exclude
    private final Map<String, HoverMessageMatcher> hoverMessageCache = new ConcurrentHashMap<>();

    private StatsType statsType;

    public HoverMessage() {
        super();
    }

    public HoverMessage(Pattern pattern, StatsType statsType) {
        super(pattern);
        this.statsType = statsType;
    }

    public HoverMessageMatcher getMatcherFor(String input) {
        if (hoverMessageCache.containsKey(input)) {
            return hoverMessageCache.get(input);
        }
        HoverMessageMatcher matcher = new HoverMessageMatcher(pattern, input, statsType);
        hoverMessageCache.put(input, matcher);
        return matcher;
    }

}


text:
package loadtestclient.client;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;

public class ProtocolHandlerLS extends ProtocolHandler {

    private static final String HEADER_END = "// END OF HEADER";
    private static final String START_STRING = "start('";

    private int nextProg = 1;
    private long keepaliveMillis;

    private String session = null;
    private String adapter;
    private String previous = null;

    public ProtocolHandlerLS(BasicWSClient basicWSClient,String server, String adapter, long keepaliveMillis) {
        super(basicWSClient,server);
        //let's encode it once
        try {
            this.adapter = URLEncoder.encode(adapter,"UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        this.keepaliveMillis = keepaliveMillis;
    }

    public synchronized void handleMessage(String text) {

        if (this.status == OFF) {
           int pointer = 0;
           //first frame should contain header end and start command

           if ((pointer = text.indexOf(HEADER_END)) > -1) {
               pointer += HEADER_END.length();

               pointer = text.indexOf(START_STRING,pointer);
               pointer += START_STRING.length();

               //let's encode it once
               try {
                   this.session = URLEncoder.encode(text.substring(pointer,text.indexOf("'",pointer)),"UTF-8");
               } catch (UnsupportedEncodingException e) {
               }

               this.status = WAITING_SUB;
               this.openGateway();
               this.sendSubscription();
           }

       } else {

           //I need to handle:
           // d(1,1,1); <- update
           // d(1,1,'data'); <- update
           // c(4,1,"socket",0,0); <- message ack
           // c(5,1,"socket",0,0); <- message ok
           // r( <- lost updates
           // error(errorCode, msgProg, "MSGsocket", "something"); <-- message error

         //Let's keep it simple:
           // assume no call can contain ); in its internal strings

           StringBuffer command = new StringBuffer(5);
           int pointer = 0;

           while(pointer < text.length() && this.status != END) {

               char ch = text.charAt(pointer);
               if (ch == '(') {

                   if (command.toString().equals("d")) {

                       //update
                       this.readUpdate(text,pointer);

                   } else if (command.toString().equals("c")) {

                       //message ack or ok
                       this.readMessageNotify(text,pointer);

                   } else if (command.toString().equals("error") || command.toString().equals("r")) {

                       //error in message handling
                       this.readMessageError(text,pointer);

                   } //else we don't care

                   pointer = text.indexOf(");",pointer)+2;
                   command.setLength(0);

               } else {
                   if (ch >= 97 && ch <= 122) {
                       command.append(ch);
                   }
                   pointer++;
               }
           }

       }

    }

    private void readMessageError(String text, int pointer) {
        //again, we actually don't care what kind of error this is, just abort
        this.abortGateway();
    }

    private void readMessageNotify(String text, int pointer) {
        //we actually don't care
    }

    private void readUpdate(String text, int pointer) {
        //actually we don't care, we only want to create load on the server

        //skip 1,1,

        pointer += 5;

        char ch = text.charAt(pointer);

        String update = null;

        if (ch == '1') {
            //update unchanged
            update = previous;
            this.dispatcher.createEvent(EventDispatcher.MESSAGE, update);
            return;

        } else { //'
            ch = text.charAt(pointer+1);
            int end = text.indexOf("');",pointer);
            if (ch != '#') {
                update = text.substring(pointer+1,end);
            }

            pointer = end+2;
            previous = update;
        }

        //then the update
        if (update != null) {
            this.dispatcher.createEvent(EventDispatcher.MESSAGE, update);
        }

    }

    public synchronized void sendMessage(String message) {
        try {
            this.networkHandler.send("msg\r\nLS_session="+this.session+"&LS_message="+URLEncoder.encode(message,"UTF-8")+"&LS_sequence=socket&LS_outcome=&LS_ack=&LS_msg_prog="+(this.nextProg++));
        } catch (UnsupportedEncodingException e) {

        }
    }

    private void sendSubscription() {
        this.networkHandler.send("control\r\nLS_session="+this.session+"&LS_table=1&LS_op=add&LS_mode=RAW&LS_id=timestamp&LS_schema=message&LS_max_frequency=unfiltered");
    }

    public void handleSocketOpen() {
        this.networkHandler.send("create_session\r\nLS_client_version=6.0&LS_adapter_set="+this.adapter + (this.keepaliveMillis > 0 ? "&LS_keepalive_millis="+this.keepaliveMillis : "") );
    }

    public void open() {
        try {
            this.networkHandler.open(new URI("ws://" +server + "/lightstreamer"));
        } catch (Exception e) {
        }
    }

}


text:
package com.wiseowl.WiseOwl.query;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import net.didion.jwnl.JWNLException;
import opennlp.tools.coref.mention.JWNLDictionary;
import opennlp.tools.parser.Parse;

/**
 * Identify the features of the question by leveraging Wordnet and using the parse of the question
 * and the question word (how, why, what, etc.) to output a context, which is the set
 * of features that can be passed to the model.  Can use Wordnet to examine what words are
 * also predictive by looking at the synsets.
 *
 * It is a rule-based feature selector
 */
public class AnswerTypeContextGenerator {

  private static final Pattern falseHeadsPattern = Pattern.compile("^(name|type|kind|sort|form|one|breed|names|variety)$");
  private static final Pattern copulaPattern = Pattern.compile("^(is|are|'s|were|was|will)$");
  private static final Pattern queryWordPattern = Pattern.compile("^(who|what|when|where|why|how|whom|which|name)$");
  private static final Pattern useFocusNounPattern = Pattern.compile("^(who|what|which|name)$");
  private static final Pattern howModifierTagPattern = Pattern.compile("^(JJ|RB)");
  private JWNLDictionary wordnet;

  /**
   *
   * @param dictDir The dict directory under the wordnet dir
   */
  public AnswerTypeContextGenerator(File dictDir) {
    try {
      wordnet = new JWNLDictionary(dictDir.getAbsolutePath());
    }
    catch (IOException e) {
      throw new RuntimeException("Unable to initalize",e);
    }
    catch (JWNLException e) {
      throw new RuntimeException("Unable to initalize",e);
    }
  }

  private boolean isQueryWord(String word) {
    return(queryWordPattern.matcher(word).matches());
  }

  private int movePastPrep(int i, Parse[] toks) {
    if (i < toks.length && (toks[i].toString().equals("of") || toks[i].toString().equals("for"))) {
      i++;
    }
    return (i);
  }

  private  int movePastOf(int i, Parse[] toks) {
    if (i < toks.length && toks[i].toString().equals("of")) {
      i++;
    }
    return (i);
  }

  private int movePastCopula(int i, Parse[] toks) {
    if (i < toks.length && toks[i].getType().startsWith("V")) {
      if (copulaPattern.matcher(toks[i].toString()).matches()) {
        i++;
      }
    }
    return (i);
  }

  private Parse[] getNounPhrases(Parse parse) {
    List<Parse> nps = new ArrayList<Parse>(10);
    List<Parse> parts = new ArrayList<Parse>();
    parts.add(parse);
    while (parts.size() > 0) {
      List<Parse> newParts = new ArrayList<Parse>();
      for (int pi=0,pn=parts.size();pi<pn;pi++) {
        Parse cp = parts.get(pi);
        if (cp.getType().equals("NP") && cp.isFlat()) {
          nps.add(cp);
        }
        else if (!cp.isPosTag()) {
          newParts.addAll(Arrays.asList(cp.getChildren()));
        }
      }
      parts = newParts;
    }
    return nps.toArray(new Parse[nps.size()]);
  }

  private Parse getContainingNounPhrase(Parse token) {
    Parse parent = token.getParent();
    if (parent.getType().equals("NP")) {
      return parent;
    }
    return null;
  }

  private int getTokenIndexFollowingPhrase(Parse p,Parse[] toks) {
    Parse[] ptok = p.getTagNodes();
    Parse lastToken = ptok[ptok.length-1];
    for (int ti=0,tl=toks.length;ti<tl;ti++) {
      if (toks[ti] == lastToken) {
        return(ti+1);
      }
    }
    return(toks.length);
  }

  public Parse findFocusNounPhrase(String queryWord, int qwi, Parse[] toks) {
    if (queryWord.equals("who")) {
      int npStart = movePastCopula(qwi + 1, toks);
      if (npStart > qwi + 1) { // check to ensure there is a copula
        Parse np = getContainingNounPhrase(toks[npStart]);
        if (np != null) {
          return (np);
        }
      }
    }
    else if (queryWord.equals("what")) {
      int npStart = movePastCopula(qwi + 1, toks);
      Parse np = getContainingNounPhrase(toks[npStart]);
      //removed copula case
      if (np != null) {
        Parse head = np.getHead();
        if (falseHeadsPattern.matcher(head.toString()).matches()) {
          npStart += np.getChildren().length;
          int np2Start = movePastPrep(npStart, toks);
          if (np2Start > npStart) {
            Parse snp = getContainingNounPhrase(toks[np2Start]);
            if (snp != null) {
              return (snp);
            }
          }
        }
        return (np);
      }
    }
    else if (queryWord.equals("which")) {
      //check for false query words like which VBD
      int npStart = movePastCopula(qwi + 1, toks);
      if (npStart > qwi + 1) {
        return (getContainingNounPhrase(toks[npStart]));
      }
      else {
        npStart = movePastOf(qwi + 1, toks);
        return (getContainingNounPhrase(toks[npStart]));
      }
    }
    else if (queryWord.equals("how")) {
      if (qwi + 1 < toks.length) {
        return (getContainingNounPhrase(toks[qwi + 1]));
      }
    }
    else if (qwi == 0 && queryWord.equals("name")) {
      int npStart = qwi + 1;
      Parse np = getContainingNounPhrase(toks[npStart]);
      if (np != null) {
        Parse head = np.getHead();
        if (falseHeadsPattern.matcher(head.toString()).matches()) {
          npStart += np.getChildren().length;
          int np2Start = movePastPrep(npStart, toks);
          if (np2Start > npStart) {
            Parse snp = getContainingNounPhrase(toks[np2Start]);
            if (snp != null) {
              return (snp);
            }
          }
        }
        return (np);
      }
    }
    return (null);
  }

  private String[] getLemmas(Parse np) {
    // make sure we're getting a single word.
    String word = np.getHead().toString().toLowerCase();
    return wordnet.getLemmas(word,"NN");
  }

  private Set<String> getSynsetSet(Parse np) {

    Set<String> synsetSet = new HashSet<String>();
    String[] lemmas = getLemmas(np);
    for (int li = 0; li < lemmas.length; li++) {
      String[] synsets = wordnet.getParentSenseKeys(lemmas[li],"NN",0);
      for (int si=0,sn=synsets.length;si<sn;si++) {
        synsetSet.add(synsets[si]);
      }
    }
    return (synsetSet);
  }

  private void generateWordNetFeatures(Parse focusNoun, List<String> features) {

    Parse[] toks = focusNoun.getTagNodes();
    if (toks[toks.length - 1].getType().startsWith("NNP")) {
      return;
    }
    //check wordnet
    Set<String> synsets = getSynsetSet(focusNoun);

    for (String synset : synsets) {
      features.add("s=" + synset);
    }
  }

  private void generateWordFeatures(Parse focusNoun, List<String> features) {
    Parse[] toks = focusNoun.getTagNodes();
    int nsi = 0;
    for (; nsi < toks.length - 1; nsi++) {
      features.add("mw=" + toks[nsi]);
      features.add("mt=" + toks[nsi].getType());
    }
    features.add("hw=" + toks[nsi]);
    features.add("ht=" + toks[nsi].getType());
  }

  public String[] getContext(Parse query) {
    Parse focalNoun = null;
    String queryWord = null;
    List<String> features = new ArrayList<String>();
    features.add("def");
    Parse[] nps = getNounPhrases(query);
    Parse[] toks = query.getTagNodes();
    int fnEnd = 0;
    int i = 0;
    boolean fnIsLast = false;
    for (; i < toks.length; i++) {
      String tok = toks[i].toString().toLowerCase();
      if (isQueryWord(tok)) {
        queryWord = tok;
        focalNoun = findFocusNounPhrase(queryWord, i, toks);
        if (tok.equals("how") && i+1 < toks.length) {
          if (howModifierTagPattern.matcher(toks[i+1].getType()).find()) {
            queryWord=tok+"_"+toks[i+1].toString();
          }
        }
        if (focalNoun != null) {
          fnEnd = getTokenIndexFollowingPhrase(focalNoun,toks);
        }
        if (focalNoun != null && focalNoun.equals(nps[nps.length - 1])) {
          fnIsLast  = true;
        }
        break;
      }
    }
    int ri = i + 1;
    if (focalNoun != null) {
      ri = fnEnd + 1;
    }
    for (; ri < toks.length; ri++) {
      features.add("rw=" + toks[ri].toString());
    }
    if (queryWord != null) {
      features.add("qw=" + queryWord);
      String verb = null;
      //skip first verb for some query words like how much
      for (int vi = i + 1; vi < toks.length; vi++) {
        String tag = toks[vi].getType();
        if (tag != null && tag.startsWith("V")) {
          verb = toks[vi].toString();
          break;
        }
      }
      if (focalNoun == null) {
        features.add("qw_verb=" + queryWord + "_" + verb);
        features.add("verb="+ verb);
        features.add("fn=null");
      }
      else if (useFocusNounPattern.matcher(queryWord).matches()) {
        generateWordFeatures(focalNoun, features);
        generateWordNetFeatures(focalNoun, features);
      }
      if (fnIsLast) {
        features.add("fnIsLast=" + fnIsLast);
      }
    }
    return(features.toArray(new String[features.size()]));
  }

}


text:
import json

from tempest.common import rest_client
from tempest import config

CONF = config.CONF

class ServiceClientJSON(rest_client.RestClient):

    def __init__(self, auth_provider):
        super(ServiceClientJSON, self).__init__(auth_provider)
        self.service = CONF.identity.catalog_type
        self.endpoint_url = 'adminURL'
        self.api_version = "v3"

    def update_service(self, service_id, **kwargs):
        """Updates a service."""
        resp, body = self.get_service(service_id)
        name = kwargs.get('name', body['name'])
        type = kwargs.get('type', body['type'])
        desc = kwargs.get('description', body['description'])
        patch_body = {
            'description': desc,
            'type': type,
            'name': name
        }
        patch_body = json.dumps({'service': patch_body})
        resp, body = self.patch('services/%s' % service_id, patch_body)
        self.expected_success(200, resp.status)
        body = json.loads(body)
        return resp, body['service']

    def get_service(self, service_id):
        """Get Service."""
        url = 'services/%s' % service_id
        resp, body = self.get(url)
        self.expected_success(200, resp.status)
        body = json.loads(body)
        return resp, body['service']

    def create_service(self, serv_type, name=None, description=None,
                       enabled=True):
        body_dict = {
            'name': name,
            'type': serv_type,
            'enabled': enabled,
            'description': description,
        }
        body = json.dumps({'service': body_dict})
        resp, body = self.post("services", body)
        self.expected_success(201, resp.status)
        body = json.loads(body)
        return resp, body["service"]

    def delete_service(self, serv_id):
        url = "services/" + serv_id
        resp, body = self.delete(url)
        self.expected_success(204, resp.status)
        return resp, body

    def list_services(self):
        resp, body = self.get('services')
        self.expected_success(200, resp.status)
        body = json.loads(body)
        return resp, body['services']


text:
package net.minecraft.command;

public class PlayerNotFoundException extends CommandException
{
    private static final String __OBFID = "CL_00001190";

    public PlayerNotFoundException()
    {
        this("commands.generic.player.notFound", new Object[0]);
    }

    public PlayerNotFoundException(String p_i1362_1_, Object ... p_i1362_2_)
    {
        super(p_i1362_1_, p_i1362_2_);
    }
}


text:
'use strict';

var warning = require('fbjs/lib/warning');

class AppStateIOS {

  static addEventListener(type, handler) {
    warning(false, 'Cannot listen to AppStateIOS events on Android.');
  }

  static removeEventListener(type, handler) {
    warning(false, 'Cannot remove AppStateIOS listener on Android.');
  }

}

AppStateIOS.currentState = null;

module.exports = AppStateIOS;


text: from .restrict_staff_to_admin import RestrictStaffToAdminMiddleware