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

class Homework extends CI_Controller
 {

	function __construct()
	{
		 parent::__construct();

		  $this->load->helper('url');
		  $this->load->library('session');
		  $this->load->model('homeworkmodel');
		  $this->load->model('class_manage');
		  $this->load->model('subjectmodel');
		  $this->load->model('smsmodel');
		  $this->load->model('mailmodel');
		  $this->load->model('notificationmodel');

        }

	public function home()
	 {
	 		 $datas=$this->session->userdata();
  	 		 $user_id=$this->session->userdata('user_id');
			 $user_type=$this->session->userdata('user_type');
			 if($user_type==2){
			 //$datas=$this->homeworkmodel->get_teacher_id($user_id);
			 $datas['cls_sec']=$this->homeworkmodel->get_teacher_class_sec($user_id,$user_type);
			 $datas['cls_tutor']=$this->homeworkmodel->get_cls_tutor($user_id,$user_type);
			 $datas['result']=$this->homeworkmodel->getall_details($user_id,$user_type);
			 $datas['ayear']=$this->homeworkmodel->get_acdaemicyear();
			 //echo'<pre>';print_r($datas['cls_tutor']);exit;
	 		 $this->load->view('adminteacher/teacher_header');
			 $this->load->view('adminteacher/homework/add',$datas);
	 		 $this->load->view('adminteacher/teacher_footer');
	 		 }
	 		 else{
	 		  redirect('/');
	 		 }
	 	}

		public function add_mark($hw_id)
		{

			    $datas=$this->session->userdata();
  	 		    $user_id=$this->session->userdata('user_id');
				$user_type=$this->session->userdata('user_type');
				$datas['result'] = $this->homeworkmodel->get_stu_details($hw_id,$user_id,$user_type);
				//echo'<pre>';print_r($datas['result']);exit;
			    if($user_type==2)
			      {
					 $this->load->view('adminteacher/teacher_header');
					 $this->load->view('adminteacher/homework/add_test',$datas);
					 $this->load->view('adminteacher/teacher_footer');
				  }
	 		   else{
	 				redirect('/');
	 		 }

		}

	  public function marks()
		{
			$datas=$this->session->userdata();
	 		$user_id=$this->session->userdata('user_id');
			$user_type=$this->session->userdata('user_type');
			$enroll=$this->input->post('enroll');
			$hwid=$this->input->post('hwid');
			$marks=$this->input->post('marks');
			//print_r($enroll);exit;
			$remarks=$this->db->escape_str($this->input->post('remarks'));
			$datas = $this->homeworkmodel->enter_marks($enroll,$hwid,$marks,$remarks,$user_id,$user_type);
			  if($datas['status']=="success")
			  {
				$this->session->set_flashdata('msg','Added Successfully');
                redirect('homework/home',$datas);
			  }else{
			   $this->session->set_flashdata('msg','Falid To Added');
                redirect('homework/home',$datas);
			  }

		}
	 public function create()
		{
	 		$datas=$this->session->userdata();
	 		$user_id=$this->session->userdata('user_id');
			$user_type=$this->session->userdata('user_type');
			//echo $user_id;exit;
			$test_type=$this->input->post('test_type');

			//echo $test_type;
			//exit;

			$year_id=$this->input->post('year_id');

			$class_id=$this->input->post('class_id');
			$title=$this->db->escape_str($this->input->post('title'));
			$subject_name=$this->input->post('subject_name');
			//echo $subject_name;exit;
			$tet_date=$this->input->post('tet_date');

			$dateTime = new DateTime($tet_date);
			$formatted_date=date_format($dateTime,'Y-m-d' );

            $submission_date=$this->input->post('sub_date');
			$dateTime = new DateTime($submission_date);
			$format_date=date_format($dateTime,'Y-m-d' );

			$details=$this->db->escape_str($this->input->post('details'));
		    $datas=$this->homeworkmodel->create_test($year_id,$class_id,$user_id,$user_type,$test_type,$title,$subject_name,$formatted_date,$format_date,$details);
			//echo'<pre>';print_r($datas["res"]);
			if($datas['status']=="success")
			{
				$this->session->set_flashdata('msg','Added Successfully');
                redirect('homework/home',$datas);
			   //redirect('add_test');
			}else if($datas['status']=="Already Exist"){
				$this->session->set_flashdata('msg','Test Date Already Exist');
                redirect('homework/home',$datas);
			}else{
				$this->session->set_flashdata('msg','Falid To Added');
                redirect('homework/home',$datas);
			}

	 	}
		//----2---------
		public function checker()
		{
			$datas=$this->session->userdata();
	 		$user_id=$this->session->userdata('user_id');
			$user_type=$this->session->userdata('user_type');
			$classid=$this->input->post('id');
		    $data=$this->homeworkmodel->get_subject($classid,$user_id,$user_type);
			//print_r($data['res']);exit;
			echo json_encode($data);
		}

		public function edit_mark($hw_id)
		{
			    $datas=$this->session->userdata();
  	 		    $user_id=$this->session->userdata('user_id');
				$user_type=$this->session->userdata('user_type');
				$datas['result']=$this->homeworkmodel->edit_details($hw_id,$user_id,$user_type);
				//echo'<pre>';print_r($datas['result']);exit;
				$datas['resubject'] = $this->subjectmodel->getsubject();
			    if($user_type==2)
			      {
					 $this->load->view('adminteacher/teacher_header');
					 $this->load->view('adminteacher/homework/edit_marks',$datas);
					 $this->load->view('adminteacher/teacher_footer');
				  }
	 		   else{
	 				redirect('/');
	 		 }
		}

       public function update()
	   {
		    $datas=$this->session->userdata();
	 		$user_id=$this->session->userdata('user_id');
			$user_type=$this->session->userdata('user_type');

		    $enroll=$this->input->post('enroll');
			$hwid=$this->input->post('hwid');
			$marks=$this->input->post('marks');
			//print_r($enroll);exit;
			$remarks=$this->db->escape_str($this->input->post('remarks'));
			$datas = $this->homeworkmodel->update_marks($enroll,$hwid,$marks,$remarks,$user_id,$user_type);
			  if($datas['status']=="success")
			  {
				$this->session->set_flashdata('msg','Update Successfully');
                redirect('homework/home',$datas);
			  }else{
			   $this->session->set_flashdata('msg','Falid To Update');
                redirect('homework/home',$datas);
			  }

	   }

	   public function edit_test($hw_id)
	   {
		        $datas=$this->session->userdata();
  	 		    $user_id=$this->session->userdata('user_id');
				$user_type=$this->session->userdata('user_type');
				$datas['result']=$this->homeworkmodel->edit_test_details($hw_id,$user_id,$user_type);

				//echo'<pre>';print_r($datas['result']);exit;

			    if($user_type==2)
			      {
					 $this->load->view('adminteacher/teacher_header');
					 $this->load->view('adminteacher/homework/edit_test',$datas);
					 $this->load->view('adminteacher/teacher_footer');
				  }
	 		   else{
	 				redirect('/');
	 		 }
	   }

	   public function update_test()
	   {
		        $datas=$this->session->userdata();
  	 		    $user_id=$this->session->userdata('user_id');
				$user_type=$this->session->userdata('user_type');

		    $test_details=$this->db->escape_str($this->input->post('test_details'));
		    $id=$this->input->post('id');
		    $hw_type=$this->input->post('hw_type');
			$title=$this->db->escape_str($this->input->post('title'));

			$test_date=$this->input->post('test_date');
			$dateTime = new DateTime($test_date);
			$formatted_date=date_format($dateTime,'Y-m-d' );

			$submission_date=$this->input->post('sub_date');
			$dateTime = new DateTime($submission_date);
			$format_date=date_format($dateTime,'Y-m-d' );

			$status=$this->input->post('status');

			$datas= $this->homeworkmodel->update_test_details($id,$hw_type,$title,$formatted_date,$format_date,$test_details,$status,$user_id,$user_type);
			  if($datas['status']=="success")
			  {
				$this->session->set_flashdata('msg','Update Successfully');
                redirect('homework/home',$datas);
			  }else{
			   $this->session->set_flashdata('msg','Falid To Update');
                redirect('homework/home',$datas);
			  }
	   }

	   //SMS
	   public function get_all_homework($cls_tutor_id)
	   {
		   $datas=$this->session->userdata();
  	 	   $user_id=$this->session->userdata('user_id');
		   $user_type=$this->session->userdata('user_type');

		   $datas['tutor_homework']=$this->homeworkmodel->get_all_ctutor_homework($user_id,$cls_tutor_id);
           //echo'<pre>';print_r($datas['tutor_homework']);exit;
		   if($user_type==2)
		   {
			 $this->load->view('adminteacher/teacher_header');
			 $this->load->view('adminteacher/homework/send_sms',$datas);
			 $this->load->view('adminteacher/teacher_footer');
		   }else{
	 		  redirect('/');
	 		 }
	   }

	   public function send_sms_all_homework()
	   {
		   $datas=$this->session->userdata();
  	 	   $user_id=$this->session->userdata('user_id');
		   $user_type=$this->session->userdata('user_type');
		   if($user_type==2)
		  {

		   $createdate=$this->input->post('tdate');
		   $clssid=$this->input->post('clsid');
		   $sendtype=$this->input->post('sendoption');
		   $acount=count($sendtype);

		   $datas['send_status']=$this->homeworkmodel->send_homework_status($user_id,$createdate,$clssid);

		 if($acount==3)
		 {
		   $datas=$this->smsmodel->send_sms_homework($user_id,$user_type,$createdate,$clssid);
		   $datas=$this->mailmodel->send_mail_homework($user_id,$user_type,$createdate,$clssid);
		   $datas=$this->notificationmodel->send_notify_homework($user_id,$user_type,$createdate,$clssid);
		 }

		 if($acount==2)
	    {
		  $ct1=$sendtype[0];
	      $ct2=$sendtype[1];

		   if($ct1=='SMS' && $ct2=='Mail')
		  {
			$datas=$this->smsmodel->send_sms_homework($user_id,$user_type,$createdate,$clssid);
		    $datas=$this->mailmodel->send_mail_homework($user_id,$user_type,$createdate,$clssid);
		  }
		  if($ct1=='SMS' && $ct2=='Notification')
		  {
			$datas=$this->smsmodel->send_sms_homework($user_id,$user_type,$createdate,$clssid);
		    $datas=$this->notificationmodel->send_notify_homework($user_id,$user_type,$createdate,$clssid);
		  }
		  if($ct1=='Mail' && $ct2=='Notification')
		  {
			 $datas=$this->mailmodel->send_mail_homework($user_id,$user_type,$createdate,$clssid);
			 $datas=$this->notificationmodel->send_notify_homework($user_id,$user_type,$createdate,$clssid);
		  }
	  }

	  if($acount==1)
	  {
		  $ct=$sendtype[0];
		  if($ct=='SMS')
		  {
			 $datas=$this->smsmodel->send_sms_homework($user_id,$user_type,$createdate,$clssid);
		  }
		  if($ct=='Notification')
		  {
			 $datas=$this->notificationmodel->send_notify_homework($user_id,$user_type,$createdate,$clssid);
		  }
		  if($ct=='Mail')
		  {
			 $datas=$this->mailmodel->send_mail_homework($user_id,$user_type,$createdate,$clssid);
		  }
	  }
	  if($datas['status']=="success")
	  {
	    echo "success";
	  }else{
         echo "Something went wrong!";
      }
		  }else{
             redirect('/');
			 }
	   }

	   public function view_send_all_homework($tdate,$cid)
	   {

		   $datas=$this->session->userdata();
		   $user_id=$this->session->userdata('user_id');
		   $user_type=$this->session->userdata('user_type');
		   $datas['view_all']=$this->homeworkmodel->view_send_homework_all($user_id,$tdate,$cid);
		   if($user_type==2)
		   {
			 $this->load->view('adminteacher/teacher_header');
			 $this->load->view('adminteacher/homework/view_send_all_hw',$datas);
			 $this->load->view('adminteacher/teacher_footer');
		   }else{
	 		  redirect('/');
	 		 }
	   }

 }


text:
package com.centurylink.mdw.model.task;

import java.util.HashMap;
import java.util.Map;

public class TaskStatuses
{
  private static Map<Integer,String> taskStatuses = new HashMap<Integer,String>();

  static {
    for (int i = 0; i < TaskStatus.allStatusCodes.length; i++)
    {
      taskStatuses.put(TaskStatus.allStatusCodes[i], TaskStatus.allStatusNames[i]);
    }
  }

  public static Map<Integer,String> getTaskStatuses() { return taskStatuses; }

  public static String getName(Integer code) {
      String name = taskStatuses.get(code);
      if (TaskStatus.STATUSNAME_CANCELLED.equals(name))
          return TaskStatus.STATUSNAME_CANCELED;
      else
          return name;
  }
  public static Integer getCode(String name) {
      if (TaskStatus.STATUSNAME_CANCELED.equals(name))
          return TaskStatus.STATUS_CANCELLED;
      else
        return TaskStatus.getStatusCodeForName(name);
  }
}

redpajama_set_name: RedPajamaGithub


text:
SOAP Server 4: addfunctions
--SKIPIF--
<?php require_once('skipif.inc'); ?>
--FILE--
<?php
function Add($x,$y) {
  return $x+$y;
}
function Sub($x,$y) {
  return $x-$y;
}

$server = new soapserver(null,array('uri'=>"http://testuri.org"));
$server->addfunction(array("Sub","Add"));

$HTTP_RAW_POST_DATA = <<<EOF
<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope
  SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:si="http://soapinterop.org/xsd">
  <SOAP-ENV:Body>
    <ns1:Add xmlns:ns1="http://testuri.org">
      <x xsi:type="xsd:int">22</x>
      <y xsi:type="xsd:int">33</y>
    </ns1:Add>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
EOF;

$server->handle($HTTP_RAW_POST_DATA);
echo "ok\n";
?>
--EXPECT--
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://testuri.org" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><ns1:AddResponse><return xsi:type="xsd:int">55</return></ns1:AddResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>
ok


text:
<?php

namespace M6Web\Bundle\DaemonBundle\Tests\Units\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use M6Web\Bundle\DaemonBundle\Command\DaemonCommand as Base;
use M6Web\Bundle\DaemonBundle\Command\StopLoopException as StopLoopExceptionBase;

class DaemonCommandConcreteThrowException extends Base
{

    public static $exceptionMessage = null;

    protected function configure()
    {
        $this->setName('test:daemontest')
            ->setDescription('command for unit test');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        self::$exceptionMessage = (string) uniqid();

        throw new \Exception(self::$exceptionMessage);
    }
}


text:
package ru.job4j.switcher;
/**
 * Класс для создагия строки двумя потоками.
 * Сначала первый поток пишет в строку 111, затем второй пишет 222 и т.д.
 */
public class StringOfNumbers {
    /**
     * строка для записи цифр.
     */
    private StringBuffer str = new StringBuffer();
    /**
     * имя первого потока.
     */
    private final String firstThread = "Thread-0";
    /**
     * имя второго потока.
     */
    private final String secondThread = "Thread-1";
    /**
     * количество цифр, кторое пишет поток за одну блокировку.
     */
    private final int actionsMax = 3;
    /**
     * количество цифр, написанных потоком за текущую блокировку.
     */
    private int actions = 0;

    /**
     * поток, захвативший блокировку.
     */
    private volatile String lockingThread = "Thread-0";

    /**
     * метод позволяет одному из потоков добавить цифру в строку.
     * после добавления actionMax цифр происходит переключения на второй поток.
      * @param number - добавляемая цифра
     * @throws InterruptedException
     */
    public void addNumber(int  number) throws InterruptedException {
        synchronized (this) {

            while (!Thread.currentThread().getName().equals(lockingThread)) {
                wait();
            }
            this.str.append(number);
            actions++;
            if (actions >= actionsMax) {
                actions = 0;
                if (Thread.currentThread().getName().equals("Thread-0")) {
                    lockingThread = "Thread-1";
                } else {
                    lockingThread = "Thread-0";
                }
                notifyAll();
            }
        }
    }

    /**
     * метод возвращает содержимое строки.
     * @return строка
     */
    public String getStr() {

        return this.str.toString();
    }
}


text:
package com.newsblur.view;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.newsblur.R;
import com.newsblur.activity.NewsBlurApplication;
import com.newsblur.activity.Profile;
import com.newsblur.domain.UserDetails;
import com.newsblur.network.domain.ActivitiesResponse;
import com.newsblur.util.ImageLoader;

public class ActivitiesAdapter extends ArrayAdapter<ActivitiesResponse> {

	private LayoutInflater inflater;
	private ImageLoader imageLoader;
	private final String startedFollowing, ago, repliedTo, sharedStory, withComment, likedComment;
	private ForegroundColorSpan highlight, darkgray;
	private String TAG = "ActivitiesAdapter";
	private Context context;
	private UserDetails currentUserDetails;

	public ActivitiesAdapter(final Context context, final ActivitiesResponse[] activities, UserDetails user) {
		super(context, R.id.row_activity_text);
		inflater = LayoutInflater.from(context);
		imageLoader = ((NewsBlurApplication) context.getApplicationContext()).getImageLoader();
		this.context = context;

		for (ActivitiesResponse response : activities) {
			add(response);
		}

		currentUserDetails = user;

		Resources resources = context.getResources();
		startedFollowing = resources.getString(R.string.profile_started_following);
		repliedTo = resources.getString(R.string.profile_replied_to);
		likedComment = resources.getString(R.string.profile_liked_comment);
		sharedStory = resources.getString(R.string.profile_shared_story);
		withComment = resources.getString(R.string.profile_with_comment);
		ago = resources.getString(R.string.profile_ago);

		highlight = new ForegroundColorSpan(resources.getColor(R.color.linkblue));
		darkgray = new ForegroundColorSpan(resources.getColor(R.color.darkgray));
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = null;
		if (convertView == null) {
			view = inflater.inflate(R.layout.row_activity, null);
		} else {
			view = convertView;
		}
		final ActivitiesResponse activity = getItem(position);
		SpannableStringBuilder stringBuilder = new SpannableStringBuilder();

		ClickableSpan usernameClick = new ClickableSpan() {
			@Override
			public void onClick(View widget) {
				Intent i = new Intent(context, Profile.class);
				i.putExtra(Profile.USER_ID, activity.id);
				context.startActivity(i);
			}
		};

		TextView activityText = (TextView) view.findViewById(R.id.row_activity_text);
		TextView activityTime = (TextView) view.findViewById(R.id.row_activity_time);
		ImageView imageView = (ImageView) view.findViewById(R.id.row_activity_icon);

		activityTime.setText(activity.timeSince.toUpperCase() + " " + ago);
		if (activity.user != null) {
			imageLoader.displayImage(activity.user.photoUrl, imageView);
		} else if (TextUtils.equals(activity.category, "sharedstory")) {
			imageLoader.displayImage(currentUserDetails.photoUrl, imageView, 10f);
		} else {
			imageView.setImageResource(R.drawable.logo);
		}

		if (TextUtils.equals(activity.category, "follow")) {
			stringBuilder.append(startedFollowing);
			stringBuilder.append(" ");
			stringBuilder.append(activity.user.username);
			stringBuilder.setSpan(darkgray, 0, startedFollowing.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			stringBuilder.setSpan(usernameClick, startedFollowing.length() + 1, startedFollowing.length() + 1 + activity.user.username.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			stringBuilder.setSpan(highlight, startedFollowing.length() + 1, startedFollowing.length() + 1 + activity.user.username.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			stringBuilder.setSpan(highlight, startedFollowing.length() + 1, startedFollowing.length() + 1 + activity.user.username.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		} else if (TextUtils.equals(activity.category, "comment_like")) {
			stringBuilder.append(likedComment);
			stringBuilder.append(" \"");
			stringBuilder.append(activity.content);
			stringBuilder.append("\" ");
			stringBuilder.append("by ");
			stringBuilder.append(activity.user.username);
			stringBuilder.setSpan(darkgray, 0, likedComment.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			stringBuilder.setSpan(highlight, likedComment.length() + 1, likedComment.length() + 3 + activity.content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			stringBuilder.setSpan(darkgray, stringBuilder.length() - activity.user.username.length() - 4, stringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			stringBuilder.setSpan(usernameClick, likedComment.length() + 3 + activity.content.length() + 4, stringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		} else if (TextUtils.equals(activity.category, "comment_reply")) {
				stringBuilder.append(repliedTo);
				stringBuilder.append(" ");
				stringBuilder.append(activity.user.username);
				stringBuilder.append(": \"");
				stringBuilder.append(activity.content);
				stringBuilder.append("\"");
				stringBuilder.setSpan(darkgray, 0, repliedTo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				stringBuilder.setSpan(usernameClick, repliedTo.length() + 1, repliedTo.length() + 1 + activity.user.username.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				stringBuilder.setSpan(highlight, repliedTo.length() + 1, repliedTo.length() + 1 + activity.user.username.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				stringBuilder.setSpan(highlight, repliedTo.length() + 1, repliedTo.length() + 1 + activity.user.username.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				stringBuilder.setSpan(darkgray, stringBuilder.length() - activity.content.length() - 2, stringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		} else if (TextUtils.equals(activity.category, "sharedstory")) {
			stringBuilder.append(sharedStory);
			stringBuilder.append(" ");
			stringBuilder.append(activity.title);
			stringBuilder.append(" ");
			if (!TextUtils.isEmpty(activity.content)) {
				stringBuilder.append(withComment);
				stringBuilder.append(": \"");
				stringBuilder.append(activity.content);
				stringBuilder.append("\"");
			}
			stringBuilder.setSpan(darkgray, 0, sharedStory.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			stringBuilder.setSpan(highlight, sharedStory.length() + 1, sharedStory.length() + 1 + activity.title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			if (!TextUtils.isEmpty(activity.content)) {
				stringBuilder.setSpan(darkgray, sharedStory.length() + 4 + activity.title.length() + withComment.length(), stringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
		}

		activityText.setText(stringBuilder);
		activityText.setMovementMethod(LinkMovementMethod.getInstance());

		return view;
	}

}


text:
title: Content Security Policy - the surprising site speed win
date: 2017-01-26 20:26:00 Z
published: false
---

I'm working on a new version of [requestmap](https://requestmap.webperf.tools). Instead of plotting the domains on a site, the [new requestmap](https://requestmap.herokuapp.com) plots every. single. request. As you might imagine this can get messy, I'm still working on how best to represent such a large number of data points.

For now, this new version works well on relatively simple websites. Such as this blog. The number of requests to load this page should be under ten: an HTML document, a CSS bundle and a few images. No JavaScript, well except for Google Analytics. Oh, and Disqus.

I use Disqus for comments as this site is hosted on GitHub, there is no server-side environment to manage comments myself. Besides, why have a database and server-side code when a third-party will do it for free?

The requestmap below shows every request Chrome makes when loading a blog post on my site. The area highlighted in green is content that *I* am in control of. The rest? That's Disqus.

Content I've added to my site in green, everything else is from Disqus.

I found this out by chance while testing requestmap. When I first added Disqus comments there were *no* unexpected requests. I'm not sure what's changed, but I assume that this is how Disqus monetises their free service.

Beyond the number of third-party requests that I was subjecting my visitors to, the impact on CPU was pretty huge.

TODO

There were also requests to non-secure endpoints, which is worrying. Luckily Chrome will block these to prevent data leakage, other browsers are catching up...

Warnings from Edge due to insecure content, thanks to Disqus.

So what do I do now? I don't want to remove comments from my blog, and Disqus is the easiest for most people to use. Content Security Policy (CSP) to the rescue!

CSP is a header which allows website owners to declare approved origins of content, with control as granular as defining which domains can execute scripts or load webfonts.

As CSP is an HTTP header, you need a server to set the header. [All major servers support CSP headers](https://content-security-policy.com/#server), which is great if you use a server. This static blog is served from GitHub pages, via CloudFlare. I have no server to set the CSP headers on!

```meta``` tag to the rescue. CSP definitions can be set in a ```<meta http-equiv="Content-Security-Policy" content="">``` declaration, meaning you can create CSPs for static sites!

I used the Chrome extension [Caspr: Enforcer](https://chrome.google.com/webstore/detail/caspr-enforcer/fekcdjkhlbjngkimekikebfegbijjafd) and the online service [CSP is awesome](http://cspisawesome.com/) to create the perfect rules, testing on multiple page categories. I added a ```_csp.html``` asset in my ```includes``` directory and included it in my ```_head.html``` file. A few seconds after commit I could see the page had updated to include the CSP. Sorted, my CSP is enforced! Or so I thought.

Loading the page in Chrome showed that the CSP was being ignored. The third-party requests kept on flowing.


text:
using System;

namespace Nuterra.Build.ModuleImport
{
	/// <summary>
	/// Line location
	/// </summary>
	public struct LineLocation
	{
		/// <summary>
		/// Line, 0-based
		/// </summary>
		public int Line { get; }

		/// <summary>
		/// Column, 0-based
		/// </summary>
		public int Character { get; }

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="line">Line, 0-based</param>
		/// <param name="character">Column, 0-based</param>
		public LineLocation(int line, int character)
		{
			if (line < 0)
				throw new ArgumentOutOfRangeException(nameof(line));
			if (character < 0)
				throw new ArgumentOutOfRangeException(nameof(line));
			Line = line;
			Character = character;
		}

		/// <summary>
		/// ToString()
		/// </summary>
		/// <returns></returns>
		public override string ToString() => $"({Line + 1},{Character + 1})";
	}
}


text:
package org.optaplanner.core.impl.heuristic.selector.entity.decorator;

import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

import org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType;
import org.optaplanner.core.impl.domain.entity.descriptor.EntityDescriptor;
import org.optaplanner.core.impl.heuristic.selector.common.SelectionCacheLifecycleBridge;
import org.optaplanner.core.impl.heuristic.selector.common.SelectionCacheLifecycleListener;
import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory;
import org.optaplanner.core.impl.heuristic.selector.entity.AbstractEntitySelector;
import org.optaplanner.core.impl.heuristic.selector.entity.EntitySelector;
import org.optaplanner.core.impl.score.director.ScoreDirector;
import org.optaplanner.core.impl.solver.random.RandomUtils;
import org.optaplanner.core.impl.solver.scope.DefaultSolverScope;

public class ProbabilityEntitySelector extends AbstractEntitySelector implements SelectionCacheLifecycleListener {

    protected final EntitySelector childEntitySelector;
    protected final SelectionCacheType cacheType;
    protected final SelectionProbabilityWeightFactory probabilityWeightFactory;

    protected NavigableMap<Double, Object> cachedEntityMap = null;
    protected double probabilityWeightTotal = -1.0;

    public ProbabilityEntitySelector(EntitySelector childEntitySelector, SelectionCacheType cacheType,
            SelectionProbabilityWeightFactory probabilityWeightFactory) {
        this.childEntitySelector = childEntitySelector;
        this.cacheType = cacheType;
        this.probabilityWeightFactory = probabilityWeightFactory;
        if (childEntitySelector.isNeverEnding()) {
            throw new IllegalStateException("The selector (" + this
                    + ") has a childEntitySelector (" + childEntitySelector
                    + ") with neverEnding (" + childEntitySelector.isNeverEnding() + ").");
        }
        phaseLifecycleSupport.addEventListener(childEntitySelector);
        if (cacheType.isNotCached()) {
            throw new IllegalArgumentException("The selector (" + this
                    + ") does not support the cacheType (" + cacheType + ").");
        }
        phaseLifecycleSupport.addEventListener(new SelectionCacheLifecycleBridge(cacheType, this));
    }

    @Override
    public SelectionCacheType getCacheType() {
        return cacheType;
    }

    // ************************************************************************
    // Worker methods
    // ************************************************************************

    @Override
    public void constructCache(DefaultSolverScope solverScope) {
        cachedEntityMap = new TreeMap<>();
        ScoreDirector scoreDirector = solverScope.getScoreDirector();
        double probabilityWeightOffset = 0L;
        for (Object entity : childEntitySelector) {
            double probabilityWeight = probabilityWeightFactory.createProbabilityWeight(
                    scoreDirector, entity);
            cachedEntityMap.put(probabilityWeightOffset, entity);
            probabilityWeightOffset += probabilityWeight;
        }
        probabilityWeightTotal = probabilityWeightOffset;
    }

    @Override
    public void disposeCache(DefaultSolverScope solverScope) {
        probabilityWeightTotal = -1.0;
    }

    @Override
    public EntityDescriptor getEntityDescriptor() {
        return childEntitySelector.getEntityDescriptor();
    }

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

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

    @Override
    public long getSize() {
        return cachedEntityMap.size();
    }

    @Override
    public Iterator<Object> iterator() {
        return new Iterator<Object>() {
            @Override
            public boolean hasNext() {
                return true;
            }

            @Override
            public Object next() {
                double randomOffset = RandomUtils.nextDouble(workingRandom, probabilityWeightTotal);
                Map.Entry<Double, Object> entry = cachedEntityMap.floorEntry(randomOffset);
                // entry is never null because randomOffset < probabilityWeightTotal
                return entry.getValue();
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("The optional operation remove() is not supported.");
            }
        };
    }

    @Override
    public ListIterator<Object> listIterator() {
        throw new IllegalStateException("The selector (" + this
                + ") does not support a ListIterator with randomSelection (true).");
    }

    @Override
    public ListIterator<Object> listIterator(int index) {
        throw new IllegalStateException("The selector (" + this
                + ") does not support a ListIterator with randomSelection (true).");
    }

    @Override
    public Iterator<Object> endingIterator() {
        return childEntitySelector.endingIterator();
    }

    @Override
    public String toString() {
        return "Probability(" + childEntitySelector + ")";
    }

}


text:
<!DOCTYPE html>
<hmtl lang="en">

	<title>Akbarkereső</title>
	<meta charset="utf-8">

	<link rel="stylesheet" media="screen" type="text/css" href="css/styles.css" />
	<link href='http://fonts.googleapis.com/css?family=Open+Sans:300,600,700' rel='stylesheet' type='text/css'>

Akbarkereső

by Félholdra Verve

				Találd meg az összes magát bevándorlónak álcázó terroristát. Bal gombbal nyilvántartásba veheted a migránst, aki erre egyből eltűnik mint a kámfor, de vigyázz mert ha felfegyverzett terrorista volt, akkor felrobbantja magát! Jobb gombbal jelölheted meg a terroristákat. Ne feledd, nem elég elkergetned az összes magát ártalmatlannak feltüntető migránst, a terroristákat is meg kell jelölni, az összeset!

				<canvas id="board" width="800" height="400" oncontextmenu="return false;">

Unfortunately, your browser does not seem to support the canvas element.

				</canvas>

Unfortunately, your javascript is disabled. You will need to enable it in order to play the game.

Küldetés indítása

Döntsd el hány terroristát akarsz likvidálni.

					<button id="easybtn">Néhányat</button>
					<button id="mediumbtn">Jópárat</button>
					<button id="insanebtn">Sokat</button>

Sikeres küldetések

							Név
							Terroristák
							Másodpercek

Küldetés indul!

Kattints egy iszlamistára a küldetés megkezdéséhez

					<button id="reset">Újrakezdés</button>
					<button id="switchscreens">Terroristaszám megváltoztatása</button>

0 másodperc telt el


text:
CefDOMDocument::Type CefDOMDocumentCToCpp::GetType()
{
  if (CEF_MEMBER_MISSING(struct_, get_type))
    return DOM_DOCUMENT_TYPE_UNKNOWN;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_dom_document_type_t _retval = struct_->get_type(struct_);

  // Return type: simple
  return _retval;
}

CefRefPtr<CefDOMNode> CefDOMDocumentCToCpp::GetDocument()
{
  if (CEF_MEMBER_MISSING(struct_, get_document))
    return NULL;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_domnode_t* _retval = struct_->get_document(struct_);

  // Return type: refptr_same
  return CefDOMNodeCToCpp::Wrap(_retval);
}

CefRefPtr<CefDOMNode> CefDOMDocumentCToCpp::GetBody()
{
  if (CEF_MEMBER_MISSING(struct_, get_body))
    return NULL;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_domnode_t* _retval = struct_->get_body(struct_);

  // Return type: refptr_same
  return CefDOMNodeCToCpp::Wrap(_retval);
}

CefRefPtr<CefDOMNode> CefDOMDocumentCToCpp::GetHead()
{
  if (CEF_MEMBER_MISSING(struct_, get_head))
    return NULL;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_domnode_t* _retval = struct_->get_head(struct_);

  // Return type: refptr_same
  return CefDOMNodeCToCpp::Wrap(_retval);
}

CefString CefDOMDocumentCToCpp::GetTitle()
{
  if (CEF_MEMBER_MISSING(struct_, get_title))
    return CefString();

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_string_userfree_t _retval = struct_->get_title(struct_);

  // Return type: string
  CefString _retvalStr;
  _retvalStr.AttachToUserFree(_retval);
  return _retvalStr;
}

CefRefPtr<CefDOMNode> CefDOMDocumentCToCpp::GetElementById(const CefString& id)
{
  if (CEF_MEMBER_MISSING(struct_, get_element_by_id))
    return NULL;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Verify param: id; type: string_byref_const
  DCHECK(!id.empty());
  if (id.empty())
    return NULL;

  // Execute
  cef_domnode_t* _retval = struct_->get_element_by_id(struct_,
      id.GetStruct());

  // Return type: refptr_same
  return CefDOMNodeCToCpp::Wrap(_retval);
}

CefRefPtr<CefDOMNode> CefDOMDocumentCToCpp::GetFocusedNode()
{
  if (CEF_MEMBER_MISSING(struct_, get_focused_node))
    return NULL;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_domnode_t* _retval = struct_->get_focused_node(struct_);

  // Return type: refptr_same
  return CefDOMNodeCToCpp::Wrap(_retval);
}

bool CefDOMDocumentCToCpp::HasSelection()
{
  if (CEF_MEMBER_MISSING(struct_, has_selection))
    return false;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  int _retval = struct_->has_selection(struct_);

  // Return type: bool
  return _retval?true:false;
}

CefRefPtr<CefDOMNode> CefDOMDocumentCToCpp::GetSelectionStartNode()
{
  if (CEF_MEMBER_MISSING(struct_, get_selection_start_node))
    return NULL;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_domnode_t* _retval = struct_->get_selection_start_node(struct_);

  // Return type: refptr_same
  return CefDOMNodeCToCpp::Wrap(_retval);
}

int CefDOMDocumentCToCpp::GetSelectionStartOffset()
{
  if (CEF_MEMBER_MISSING(struct_, get_selection_start_offset))
    return 0;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  int _retval = struct_->get_selection_start_offset(struct_);

  // Return type: simple
  return _retval;
}

CefRefPtr<CefDOMNode> CefDOMDocumentCToCpp::GetSelectionEndNode()
{
  if (CEF_MEMBER_MISSING(struct_, get_selection_end_node))
    return NULL;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_domnode_t* _retval = struct_->get_selection_end_node(struct_);

  // Return type: refptr_same
  return CefDOMNodeCToCpp::Wrap(_retval);
}

int CefDOMDocumentCToCpp::GetSelectionEndOffset()
{
  if (CEF_MEMBER_MISSING(struct_, get_selection_end_offset))
    return 0;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  int _retval = struct_->get_selection_end_offset(struct_);

  // Return type: simple
  return _retval;
}

CefString CefDOMDocumentCToCpp::GetSelectionAsMarkup()
{
  if (CEF_MEMBER_MISSING(struct_, get_selection_as_markup))
    return CefString();

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_string_userfree_t _retval = struct_->get_selection_as_markup(struct_);

  // Return type: string
  CefString _retvalStr;
  _retvalStr.AttachToUserFree(_retval);
  return _retvalStr;
}

CefString CefDOMDocumentCToCpp::GetSelectionAsText()
{
  if (CEF_MEMBER_MISSING(struct_, get_selection_as_text))
    return CefString();

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_string_userfree_t _retval = struct_->get_selection_as_text(struct_);

  // Return type: string
  CefString _retvalStr;
  _retvalStr.AttachToUserFree(_retval);
  return _retvalStr;
}

CefString CefDOMDocumentCToCpp::GetBaseURL()
{
  if (CEF_MEMBER_MISSING(struct_, get_base_url))
    return CefString();

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_string_userfree_t _retval = struct_->get_base_url(struct_);

  // Return type: string
  CefString _retvalStr;
  _retvalStr.AttachToUserFree(_retval);
  return _retvalStr;
}

CefString CefDOMDocumentCToCpp::GetCompleteURL(const CefString& partialURL)
{
  if (CEF_MEMBER_MISSING(struct_, get_complete_url))
    return CefString();

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Verify param: partialURL; type: string_byref_const
  DCHECK(!partialURL.empty());
  if (partialURL.empty())
    return CefString();

  // Execute
  cef_string_userfree_t _retval = struct_->get_complete_url(struct_,
      partialURL.GetStruct());

  // Return type: string
  CefString _retvalStr;
  _retvalStr.AttachToUserFree(_retval);
  return _retvalStr;
}

#ifndef NDEBUG
template<> long CefCToCpp<CefDOMDocumentCToCpp, CefDOMDocument,
    cef_domdocument_t>::DebugObjCt = 0;
#endif


text:
package concretis.util;

import lombok.Data;
import lombok.RequiredArgsConstructor;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import java.util.List;
import java.util.stream.IntStream;

import static java.util.stream.Collectors.toList;

/**
 * @author Evgeniy Khyst
 */
@Named
@ApplicationScoped
public class PaginationUtils {

    @Data
    @RequiredArgsConstructor
    public static class Pagination {

        private final List<Integer> pages;
        private final int size;
    }

    public Pagination getPagination(int paginationSize, int elementsQuantity, int pageSize, int pageNumber) {
        int pagesQuantity = (int) Math.ceil(((double) elementsQuantity) / pageSize);
        return getPagination(paginationSize, pagesQuantity, pageNumber);
    }

    public Pagination getPagination(int paginationSize, int pagesQuantity, int pageNumber) {
        int firstPageNumber = Math.min(Math.max(pageNumber - paginationSize / 2, 0), Math.max(pagesQuantity - paginationSize, 0));
        int lastPageNumber = Math.min(firstPageNumber + paginationSize, pagesQuantity);
        List<Integer> pages = IntStream.range(firstPageNumber, lastPageNumber).boxed().collect(toList());
        return new Pagination(pages, pagesQuantity);
    }
}


text:
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.payments;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;

import org.chromium.base.Log;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.components.payments.PaymentManifestVerifier.ManifestVerifyCallback;
import org.chromium.components.payments.intent.WebPaymentIntentHelper;
import org.chromium.payments.mojom.PaymentDetailsModifier;
import org.chromium.payments.mojom.PaymentMethodData;
import org.chromium.url.GURL;

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

/**
 * Finds installed native Android payment apps and verifies their signatures according to the
 * payment method manifests. The manifests are located based on the payment method name, which is a
 * URL that starts with "https://" (localhosts can be "http://", however). The W3C-published non-URL
 * payment method names are exceptions: these are common payment method names that do not have a
 * manifest and can be used by any payment app.
 */
public class AndroidPaymentAppFinder implements ManifestVerifyCallback {
    private static final String TAG = "PaymentAppFinder";

    private static final String PLAY_STORE_PACKAGE_NAME = "com.android.vending";

    /** The maximum number of payment method manifests to download. */
    private static final int MAX_NUMBER_OF_MANIFESTS = 10;

    /** The name of the intent for the service to check whether an app is ready to pay. */
    public static final String ACTION_IS_READY_TO_PAY =
            "org.chromium.intent.action.IS_READY_TO_PAY";

    /**
     * Meta data name of an app's supported payment method names.
     */
    public static final String META_DATA_NAME_OF_PAYMENT_METHOD_NAMES =
            "org.chromium.payment_method_names";

    /**
     * Meta data name of an app's supported default payment method name.
     */
    public static final String META_DATA_NAME_OF_DEFAULT_PAYMENT_METHOD_NAME =
            "org.chromium.default_payment_method_name";

    /**
     * Meta data name of an app's supported delegations' list.
     */
    public static final String META_DATA_NAME_OF_SUPPORTED_DELEGATIONS =
            "org.chromium.payment_supported_delegations";

    private final Set<GURL> mUrlPaymentMethods = new HashSet<>();
    private final PaymentManifestDownloader mDownloader;
    private final PaymentManifestWebDataService mWebDataService;
    private final PaymentManifestParser mParser;
    private final PackageManagerDelegate mPackageManagerDelegate;
    private final PaymentAppFactoryDelegate mFactoryDelegate;
    private final PaymentAppFactoryInterface mFactory;
    private final boolean mIsOffTheRecord;

    /**
     * The app stores that supports app-store billing methods.
     *
     * key: the app-store app's package name, e.g., "com.google.vendor" (Google Play Store).
     * value: the app-store app's billing method identifier, e.g.,
     * "https://play.google.com/billing". Only valid GURLs are allowed.
     */
    private final Map<String, GURL> mAppStores = new HashMap();

    /**
     * A mapping from an Android package name to the payment app with that package name. The apps
     * will be sent to the PaymentAppFactoryDelegate once all of their payment methods
     * have been validated. The package names are used for identification because they are unique on
     * Android. Example contents:
     *
     * {"com.bobpay.app.v1": androidPaymentApp1, "com.alicepay.app.v1": androidPaymentApp2}
     */
    private final Map<String, AndroidPaymentApp> mValidApps = new HashMap<>();

    /**
     * A mapping from origins of payment apps to the URL payment methods of these apps. Used to look
     * up payment apps in mVerifiedPaymentMethods based on the supported origins that
     * have been verified in PaymentManifestVerifier. Example contents:
     *
     * {"https://bobpay.com": ("https://bobpay.com/personal", "https://bobpay.com/business")}
     */
    private final Map<GURL, Set<GURL>> mOriginToUrlDefaultMethodsMapping = new HashMap<>();

    /**
     * A mapping from URL payment methods to the applications that support this payment method,
     * but not as their default payment method. Used to find all apps that claim support for a given
     * URL payment method when the payment manifest of this method contains
     * "supported_origins": "*". Example contents:
     *
     * {"https://bobpay.com/public-standard": (resolveInfo1, resolveInfo2, resolveInfo3)}
     */
    private final Map<GURL, Set<ResolveInfo>> mMethodToSupportedAppsMapping = new HashMap<>();

    /** Contains information about a URL payment method. */
    private static final class PaymentMethod {
        /** The default applications for this payment method. */
        public final Set<ResolveInfo> defaultApplications = new HashSet<>();

        /** The supported origins of this payment method. */
        public final Set<GURL> supportedOrigins = new HashSet<>();
    }

    /**
     * A mapping from URL payment methods to the verified information about these methods. Used to
     * accumulate the incremental information that arrives from
     * PaymentManifestVerifiers for each of the payment method manifests that need to
     * be downloaded. Example contents:
     *
     * { "https://bobpay.com/business": method1, "https://bobpay.com/personal": method2}
     */
    private final Map<GURL, PaymentMethod> mVerifiedPaymentMethods = new HashMap<>();

    /*
     * A mapping from package names to their IS_READY_TO_PAY service names, e.g.:
     *
     * {"com.bobpay.app": "com.bobpay.app.IsReadyToPayService"}
     */
    private final Map<String, String> mIsReadyToPayServices = new HashMap<>();

    private int mPendingVerifiersCount;
    private int mPendingIsReadyToPayQueries;
    private int mPendingResourceUsersCount;
    private boolean mBypassIsReadyToPayServiceInTest;

    /**
     * Builds a finder for native Android payment apps.
     *
     * @param webDataService The web data service to cache manifest.
     * @param downloader The manifest downloader.
     * @param parser The manifest parser.
     * @param packageManagerDelegate The package information retriever.
     * @param factoryDelegate The merchant requested data and the asynchronous delegate to be
     *         invoked (on the UI thread) when all Android payment apps have been found.
     * @param factory The factory to be used in the delegate.onDoneCreatingPaymentApps(factory)
     *         call.
     */
    public AndroidPaymentAppFinder(PaymentManifestWebDataService webDataService,
            PaymentManifestDownloader downloader, PaymentManifestParser parser,
            PackageManagerDelegate packageManagerDelegate,
            PaymentAppFactoryDelegate factoryDelegate, PaymentAppFactoryInterface factory) {
        mFactoryDelegate = factoryDelegate;

        mAppStores.put(PLAY_STORE_PACKAGE_NAME, new GURL(MethodStrings.GOOGLE_PLAY_BILLING));
        for (GURL method : mAppStores.values()) {
            assert method.isValid();
        }

        mDownloader = downloader;
        mWebDataService = webDataService;
        mParser = parser;
        mPackageManagerDelegate = packageManagerDelegate;
        mFactory = factory;
        assert mFactoryDelegate.getParams() != null;
        mIsOffTheRecord = mFactoryDelegate.getParams().isOffTheRecord();
    }

    private void findAppStoreBillingApp(List<ResolveInfo> allInstalledPaymentApps) {
        assert !mFactoryDelegate.getParams().hasClosed();
        String twaPackageName = mFactoryDelegate.getParams().getTwaPackageName();
        if (TextUtils.isEmpty(twaPackageName)) return;
        ResolveInfo twaApp = findAppWithPackageName(allInstalledPaymentApps, twaPackageName);
        if (twaApp == null) return;
        List<String> agreedAppStoreMethods = new ArrayList<>();
        for (GURL appStoreUriMethod : mAppStores.values()) {
            assert appStoreUriMethod != null;
            assert appStoreUriMethod.isValid();
            String appStoreMethod = removeTrailingSlash(appStoreUriMethod.getSpec());
            assert appStoreMethod != null;
            if (!mFactoryDelegate.getParams().getMethodData().containsKey(appStoreMethod)) continue;
            if (!paymentAppSupportsUriMethod(twaApp, appStoreUriMethod)) continue;
            agreedAppStoreMethods.add(appStoreMethod);
        }

        boolean allowTwaInstalledFromAnySource = PaymentFeatureList.isEnabled(
                PaymentFeatureList.WEB_PAYMENTS_APP_STORE_BILLING_DEBUG);
        if (!allowTwaInstalledFromAnySource) {
            String installerPackageName =
                    mPackageManagerDelegate.getInstallerPackage(twaPackageName);
            if (installerPackageName == null) return;
            GURL appStoreUriMethod = mAppStores.get(installerPackageName);
            if (appStoreUriMethod == null) return;
            assert appStoreUriMethod.isValid();

            String method = appStoreUriMethod.getSpec();
            if (!agreedAppStoreMethods.contains(method)) return;
            onValidPaymentAppForPaymentMethodName(twaApp, method);
        } else {
            for (String appStoreMethod : agreedAppStoreMethods) {
                onValidPaymentAppForPaymentMethodName(twaApp, appStoreMethod);
            }
        }

        AndroidPaymentApp app = mValidApps.get(twaPackageName);
        if (app != null) app.setIsPreferred(true);
    }

    private boolean paymentAppSupportsUriMethod(ResolveInfo app, GURL urlMethod) {
        String defaultMethod = app.activityInfo.metaData == null
                ? null
                : app.activityInfo.metaData.getString(
                        META_DATA_NAME_OF_DEFAULT_PAYMENT_METHOD_NAME);
        GURL defaultUrlMethod = new GURL(defaultMethod);
        assert urlMethod.isValid();
        return (getSupportedPaymentMethods(app.activityInfo).contains(urlMethod.getSpec()))
                || (urlMethod.equals(defaultUrlMethod));
    }

    private ResolveInfo findAppWithPackageName(List<ResolveInfo> apps, String packageName) {
        assert packageName != null;
        for (int i = 0; i < apps.size(); i++) {
            ResolveInfo app = apps.get(i);
            String appPackageName = app.activityInfo.packageName;
            if (packageName.equals(appPackageName)) return app;
        }
        return null;
    }

    /**
     * Finds and validates the installed android payment apps that support the payment method names
     * that the merchant is using.
     */
    public void findAndroidPaymentApps() {
        if (mFactoryDelegate.getParams().hasClosed()) return;
        for (String method : mFactoryDelegate.getParams().getMethodData().keySet()) {
            assert !TextUtils.isEmpty(method);
            GURL url = new GURL(method); // Only URL payment method names are supported.
            if (mAppStores.containsValue(url)) continue;
            if (UrlUtil.isValidUrlBasedPaymentMethodIdentifier(url)) {
                mUrlPaymentMethods.add(url);
            }
        }

        List<ResolveInfo> allInstalledPaymentApps =
                mPackageManagerDelegate.getActivitiesThatCanRespondToIntentWithMetaData(
                        new Intent(WebPaymentIntentHelper.ACTION_PAY));
        if (allInstalledPaymentApps.isEmpty()) {
            onAllAppsFoundAndValidated();
            return;
        }

        if (!mIsOffTheRecord) {
            List<ResolveInfo> services = mPackageManagerDelegate.getServicesThatCanRespondToIntent(
                    new Intent(ACTION_IS_READY_TO_PAY));
            int numberOfServices = services.size();
            for (int i = 0; i < numberOfServices; i++) {
                ServiceInfo service = services.get(i).serviceInfo;
                mIsReadyToPayServices.put(service.packageName, service.name);
            }
        }

        if (!PaymentOptionsUtils.requestAnyInformation(
                    mFactoryDelegate.getParams().getPaymentOptions())
                && PaymentFeatureList.isEnabled(
                        PaymentFeatureList.WEB_PAYMENTS_APP_STORE_BILLING)) {
            findAppStoreBillingApp(allInstalledPaymentApps);
        }

        // All URL methods for which manifests should be downloaded. For example, if merchant
        // supports "https://bobpay.com/personal" payment method, but user also has Alice Pay app
        // that has the default payment method name of "https://alicepay.com/webpay" that claims to
        // support "https://bobpay.com/personal" method as well, then both of these methods will be
        // in this set:
        //
        // ("https://bobpay.com/personal", "https://alicepay.com/webpay")
        Set<GURL> urlMethods = new HashSet<>(mUrlPaymentMethods);

        // A mapping from all known payment method names to the corresponding payment apps that
        // claim to support these payment methods. Example contents:
        //
        // {"basic-card": (bobPay, alicePay), "https://alicepay.com/webpay": (alicePay)}
        //
        // In case of non-URL payment methods, such as "basic-card", all apps that claim to support
        // it are considered valid. In case of URL payment methods, if no apps claim to support a
        // URL method, then no information will be downloaded for this method.
        Map<String, Set<ResolveInfo>> methodToAppsMapping = new HashMap<>();

        // A mapping from URL payment method names to the corresponding default payment apps. The
        // payment manifest verifiers compare these apps against the information in
        // "default_applications" of the payment method manifests to determine the validity of these
        // apps. Example contents:
        //
        // {"https://bobpay.com/personal": (bobPay), "https://alicepay.com/webpay": (alicePay)}
        Map<GURL, Set<ResolveInfo>> urlMethodToDefaultAppsMapping = new HashMap<>();

        // A mapping from URL payment method names to the origins of the payment apps that support
        // that method name. The payment manifest verifiers compare these origins against the
        // information in "supported_origins" of the payment method manifests to determine validity
        // of these origins. Example contents:
        //
        // {"https://bobpay.com/personal": ("https://alicepay.com")}
        Map<GURL, Set<GURL>> urlMethodToSupportedOriginsMapping = new HashMap<>();

        for (int i = 0; i < allInstalledPaymentApps.size(); i++) {
            ResolveInfo app = allInstalledPaymentApps.get(i);

            String defaultMethod = app.activityInfo.metaData == null
                    ? null
                    : app.activityInfo.metaData.getString(
                            META_DATA_NAME_OF_DEFAULT_PAYMENT_METHOD_NAME);

            GURL appOrigin = null;
            GURL defaultUrlMethod = null;
            if (!TextUtils.isEmpty(defaultMethod)) {
                defaultUrlMethod = new GURL(defaultMethod);

                // Do not download any manifests for the app whose default payment method identifier
                // is an app store payment method identifier, because app store method URLs are used
                // only for identification and do not host manifest files.
                if (mAppStores.values().contains(defaultUrlMethod)) {
                    continue;
                }

                if (UrlUtil.isURLValid(defaultUrlMethod)) {
                    defaultMethod = urlToStringWithoutTrailingSlash(defaultUrlMethod);
                }
                if (!methodToAppsMapping.containsKey(defaultMethod)) {
                    methodToAppsMapping.put(defaultMethod, new HashSet<ResolveInfo>());
                }
                methodToAppsMapping.get(defaultMethod).add(app);

                if (UrlUtil.isURLValid(defaultUrlMethod)) {
                    urlMethods.add(defaultUrlMethod);

                    if (!urlMethodToDefaultAppsMapping.containsKey(defaultUrlMethod)) {
                        urlMethodToDefaultAppsMapping.put(
                                defaultUrlMethod, new HashSet<ResolveInfo>());
                    }
                    urlMethodToDefaultAppsMapping.get(defaultUrlMethod).add(app);

                    appOrigin = defaultUrlMethod.getOrigin();
                    if (!mOriginToUrlDefaultMethodsMapping.containsKey(appOrigin)) {
                        mOriginToUrlDefaultMethodsMapping.put(appOrigin, new HashSet<GURL>());
                    }
                    mOriginToUrlDefaultMethodsMapping.get(appOrigin).add(defaultUrlMethod);
                }
            }

            // Note that a payment app with non-URL default payment method (e.g., "basic-card")
            // can support URL payment methods (e.g., "https://bobpay.com/public-standard").
            Set<String> supportedMethods = getSupportedPaymentMethods(app.activityInfo);
            for (String supportedMethod : supportedMethods) {
                GURL supportedUrlMethod = new GURL(supportedMethod);
                if (!UrlUtil.isURLValid(supportedUrlMethod)) supportedUrlMethod = null;
                if (supportedUrlMethod != null && supportedUrlMethod.equals(defaultUrlMethod)) {
                    continue;
                }

                // Ignore payment method identifiers of app stores, because app store method URLs
                // are used only for identification and do not host manifest files.
                if (mAppStores.values().contains(supportedUrlMethod)) {
                    continue;
                }

                if (!methodToAppsMapping.containsKey(supportedMethod)) {
                    methodToAppsMapping.put(supportedMethod, new HashSet<ResolveInfo>());
                }
                methodToAppsMapping.get(supportedMethod).add(app);

                if (supportedUrlMethod == null) continue;

                if (!mMethodToSupportedAppsMapping.containsKey(supportedUrlMethod)) {
                    mMethodToSupportedAppsMapping.put(
                            supportedUrlMethod, new HashSet<ResolveInfo>());
                }
                mMethodToSupportedAppsMapping.get(supportedUrlMethod).add(app);

                if (appOrigin == null) continue;

                if (!urlMethodToSupportedOriginsMapping.containsKey(supportedUrlMethod)) {
                    urlMethodToSupportedOriginsMapping.put(supportedUrlMethod, new HashSet<GURL>());
                }
                urlMethodToSupportedOriginsMapping.get(supportedUrlMethod).add(appOrigin);
            }

            // Record the total number of payment methods that this activity `ResolveInfo app`
            // declares to support in its metadata.
            if (!TextUtils.isEmpty(defaultMethod)) supportedMethods.add(defaultMethod);
            RecordHistogram.recordCustomCountHistogram(
                    /*name=*/"PaymentRequest.NumberOfSupportedMethods.AndroidApp",
                    /*sample=*/supportedMethods.size(),
                    /*min=*/1, /*max=*/10, /*numBuckets=*/10);
        }

        List<PaymentManifestVerifier> manifestVerifiers = new ArrayList<>();
        for (GURL urlMethodName : urlMethods) {
            if (!methodToAppsMapping.containsKey(urlToStringWithoutTrailingSlash(urlMethodName))) {
                continue;
            }

            if (!mParser.isNativeInitialized()) {
                mParser.createNative(mFactoryDelegate.getParams().getWebContents());
            }

            // Initialize the native side of the downloader, once we know that a manifest file needs
            // to be downloaded.
            if (!mDownloader.isInitialized()) {
                mDownloader.initialize(mFactoryDelegate.getParams().getWebContents());
            }

            manifestVerifiers.add(new PaymentManifestVerifier(
                    mFactoryDelegate.getParams().getPaymentRequestSecurityOrigin(), urlMethodName,
                    urlMethodToDefaultAppsMapping.get(urlMethodName),
                    urlMethodToSupportedOriginsMapping.get(urlMethodName), mWebDataService,
                    mDownloader, mParser, mPackageManagerDelegate, this /* callback */));

            if (manifestVerifiers.size() == MAX_NUMBER_OF_MANIFESTS) {
                Log.e(TAG, "Reached maximum number of allowed payment app manifests.");
                break;
            }
        }

        if (manifestVerifiers.isEmpty()) {
            onAllAppsFoundAndValidated();
            return;
        }

        mPendingVerifiersCount = mPendingResourceUsersCount = manifestVerifiers.size();
        for (PaymentManifestVerifier manifestVerifier : manifestVerifiers) {
            manifestVerifier.verify();
        }
    }

    /**
     * Queries the Android app metadata for the names of the non-default payment methods that the
     * given app supports.
     *
     * @param activityInfo The application information to query.
     * @return The set of non-default payment method names that this application supports. Never
     *         null.
     */
    private Set<String> getSupportedPaymentMethods(ActivityInfo activityInfo) {
        Set<String> result = new HashSet<>();
        String[] nonDefaultPaymentMethodNames =
                getStringArrayMetaData(activityInfo, META_DATA_NAME_OF_PAYMENT_METHOD_NAMES);
        if (nonDefaultPaymentMethodNames == null) return result;

        // Normalize methods that look like URLs in the same way they will be normalized in
        // #findAndroidPaymentApps.
        for (String method : nonDefaultPaymentMethodNames) {
            GURL urlMethod = new GURL(method);
            result.add(UrlUtil.isURLValid(urlMethod) ? urlToStringWithoutTrailingSlash(urlMethod)
                                                     : method);
        }

        return result;
    }

    /**
     * Queries the Android app metadata for a string array.
     * @param activityInfo The application information to query.
     * @param metaDataName The name of the string array meta data to be retrieved.
     * @return The string array.
     */
    @Nullable
    private String[] getStringArrayMetaData(ActivityInfo activityInfo, String metaDataName) {
        if (activityInfo.metaData == null) return null;

        int resId = activityInfo.metaData.getInt(metaDataName);
        if (resId == 0) return null;

        return mPackageManagerDelegate.getStringArrayResourceForApplication(
                activityInfo.applicationInfo, resId);
    }

    @Override
    public void onValidDefaultPaymentApp(GURL methodName, ResolveInfo resolveInfo) {
        getOrCreateVerifiedPaymentMethod(methodName).defaultApplications.add(resolveInfo);
    }

    @Override
    public void onValidSupportedOrigin(GURL methodName, GURL supportedOrigin) {
        getOrCreateVerifiedPaymentMethod(methodName).supportedOrigins.add(supportedOrigin);
    }

    private PaymentMethod getOrCreateVerifiedPaymentMethod(GURL methodName) {
        PaymentMethod verifiedPaymentManifest = mVerifiedPaymentMethods.get(methodName);
        if (verifiedPaymentManifest == null) {
            verifiedPaymentManifest = new PaymentMethod();
            mVerifiedPaymentMethods.put(methodName, verifiedPaymentManifest);
        }
        return verifiedPaymentManifest;
    }

    @Override
    public void onVerificationError(String errorMessage) {
        mFactoryDelegate.onPaymentAppCreationError(errorMessage, AppCreationFailureReason.UNKNOWN);
    }

    @Override
    public void onFinishedVerification() {
        mPendingVerifiersCount--;
        if (mPendingVerifiersCount != 0) return;

        for (Map.Entry<GURL, PaymentMethod> nameAndMethod : mVerifiedPaymentMethods.entrySet()) {
            GURL methodName = nameAndMethod.getKey();
            if (!mUrlPaymentMethods.contains(methodName)) continue;

            PaymentMethod method = nameAndMethod.getValue();
            String methodNameString = urlToStringWithoutTrailingSlash(methodName);
            for (ResolveInfo app : method.defaultApplications) {
                onValidPaymentAppForPaymentMethodName(app, methodNameString);
            }

            for (GURL supportedOrigin : method.supportedOrigins) {
                Set<GURL> supportedAppMethodNames =
                        mOriginToUrlDefaultMethodsMapping.get(supportedOrigin);
                if (supportedAppMethodNames == null) continue;

                for (GURL supportedAppMethodName : supportedAppMethodNames) {
                    PaymentMethod supportedAppMethod =
                            mVerifiedPaymentMethods.get(supportedAppMethodName);
                    if (supportedAppMethod == null) continue;

                    for (ResolveInfo supportedApp : supportedAppMethod.defaultApplications) {
                        onValidPaymentAppForPaymentMethodName(supportedApp, methodNameString);
                    }
                }
            }
        }

        onAllAppsFoundAndValidated();
    }

    /**
     * Queries the IS_READY_TO_PAY service of all valid payment apps. Only valid payment apps
     * receive IS_READY_TO_PAY query to avoid exposing browsing history to malicious apps.
     *
     * Must be done after all verifiers have finished because some manifest files may validate
     * multiple apps and some apps may require multiple manifest file for verification.
     */
    private void onAllAppsFoundAndValidated() {
        assert mPendingVerifiersCount == 0;

        mFactoryDelegate.onCanMakePaymentCalculated(mValidApps.size() > 0);
        if (mValidApps.isEmpty() || mFactoryDelegate.getParams().hasClosed()) {
            mFactoryDelegate.onDoneCreatingPaymentApps(mFactory);
            return;
        }

        mPendingIsReadyToPayQueries = mValidApps.size();
        for (Map.Entry<String, AndroidPaymentApp> entry : mValidApps.entrySet()) {
            AndroidPaymentApp app = entry.getValue();
            if (mBypassIsReadyToPayServiceInTest) app.bypassIsReadyToPayServiceInTest();
            app.maybeQueryIsReadyToPayService(
                    filterMethodDataForApp(mFactoryDelegate.getParams().getMethodData(),
                            app.getInstrumentMethodNames()),
                    mFactoryDelegate.getParams().getTopLevelOrigin(),
                    mFactoryDelegate.getParams().getPaymentRequestOrigin(),
                    mFactoryDelegate.getParams().getCertificateChain(),
                    filterModifiersForApp(mFactoryDelegate.getParams().getUnmodifiableModifiers(),
                            app.getInstrumentMethodNames()),
                    this::onIsReadyToPayResponse);
        }
    }

    @VisibleForTesting
    public void bypassIsReadyToPayServiceInTest() {
        mBypassIsReadyToPayServiceInTest = true;
    }

    private static Map<String, PaymentMethodData> filterMethodDataForApp(
            Map<String, PaymentMethodData> methodData, Set<String> appMethodNames) {
        Map<String, PaymentMethodData> filtered = new HashMap<>();
        for (String methodName : appMethodNames) {
            if (methodData.containsKey(methodName)) {
                filtered.put(methodName, methodData.get(methodName));
            }
        }
        return filtered;
    }

    private static Map<String, PaymentDetailsModifier> filterModifiersForApp(
            Map<String, PaymentDetailsModifier> modifiers, Set<String> appMethodNames) {
        Map<String, PaymentDetailsModifier> filtered = new HashMap<>();
        for (String methodName : appMethodNames) {
            if (modifiers.containsKey(methodName)) {
                filtered.put(methodName, modifiers.get(methodName));
            }
        }
        return filtered;
    }

    private void onIsReadyToPayResponse(AndroidPaymentApp app, boolean isReadyToPay) {
        if (isReadyToPay) mFactoryDelegate.onPaymentAppCreated(app);
        if (--mPendingIsReadyToPayQueries == 0) {
            mFactoryDelegate.onDoneCreatingPaymentApps(mFactory);
        }
    }

    /**
     * Enables the given payment app to use this method name.
     *
     * @param resolveInfo The payment app that's allowed to use the method name.
     * @param methodName  The method name that can be used by the app.
     */
    private void onValidPaymentAppForPaymentMethodName(ResolveInfo resolveInfo, String methodName) {
        if (mFactoryDelegate.getParams().hasClosed()) return;
        String packageName = resolveInfo.activityInfo.packageName;

        SupportedDelegations appSupportedDelegations =
                getAppsSupportedDelegations(resolveInfo.activityInfo);
        // Allow-lists the Play Billing method for this feature in order for the Play Billing case
        // to skip the sheet in this case.
        if (PaymentFeatureList.isEnabled(PaymentFeatureList.ENFORCE_FULL_DELEGATION)
                || methodName.equals(MethodStrings.GOOGLE_PLAY_BILLING)) {
            if (!appSupportedDelegations.providesAll(
                        mFactoryDelegate.getParams().getPaymentOptions())) {
                Log.e(TAG, ErrorStrings.SKIP_APP_FOR_PARTIAL_DELEGATION.replace("$", packageName));
                return;
            }
        }

        AndroidPaymentApp app = mValidApps.get(packageName);
        if (app == null) {
            CharSequence label = mPackageManagerDelegate.getAppLabel(resolveInfo);
            if (TextUtils.isEmpty(label)) {
                Log.e(TAG, "Skipping \"%s\" because of empty label.", packageName);
                return;
            }

            // Dedupe corresponding payment handler which is registered with the default
            // payment method name as the scope and the scope is used as the app Id.
            String webAppIdCanDeduped = resolveInfo.activityInfo.metaData == null
                    ? null
                    : resolveInfo.activityInfo.metaData.getString(
                            META_DATA_NAME_OF_DEFAULT_PAYMENT_METHOD_NAME);
            app = new AndroidPaymentApp(new AndroidPaymentApp.LauncherImpl(
                                                mFactoryDelegate.getParams().getWebContents()),
                    packageName, resolveInfo.activityInfo.name,
                    mIsReadyToPayServices.get(packageName), label.toString(),
                    mPackageManagerDelegate.getAppIcon(resolveInfo), mIsOffTheRecord,
                    webAppIdCanDeduped, appSupportedDelegations);
            mValidApps.put(packageName, app);
        }

        // The same method may be added multiple times.
        app.addMethodName(methodName);
    }

    private SupportedDelegations getAppsSupportedDelegations(ActivityInfo activityInfo) {
        String[] supportedDelegationNames =
                getStringArrayMetaData(activityInfo, META_DATA_NAME_OF_SUPPORTED_DELEGATIONS);
        return SupportedDelegations.createFromStringArray(supportedDelegationNames);
    }

    @Override
    public void onFinishedUsingResources() {
        mPendingResourceUsersCount--;
        if (mPendingResourceUsersCount != 0) return;

        mWebDataService.destroy();
        if (mDownloader.isInitialized()) mDownloader.destroy();
        if (mParser.isNativeInitialized()) mParser.destroyNative();
    }

    /**
     * Converts the given URL to a string without a trailing slash, because payment method
     * identifiers typically omit trailing slashes, e.g., "https://google.com/pay" is correct,
     * whereas "https://google.com/pay/" is incorrect. This is important because matching payment
     * apps to payment requests happens by string equality. Note that GURL.getSpec() can append
     * trailing slashes in some instances.
     * @param url The URL to stringify.
     * @return The URL string without a trailing slash, or null if the input parameter is null.
     */
    @Nullable
    private static String urlToStringWithoutTrailingSlash(@Nullable GURL url) {
        if (url == null) return null;
        return removeTrailingSlash(url.getSpec());
    }

    @Nullable
    private static String removeTrailingSlash(@Nullable String string) {
        if (string == null) return null;
        return string.endsWith("/") ? string.substring(0, string.length() - 1) : string;
    }

    /**
     * Add an app store for testing.
     *
     * @param packageName The package name of the app store.
     * @param paymentMethod The payment method identifier of the app store.
     */
    @VisibleForTesting
    public void addAppStoreForTest(String packageName, GURL paymentMethod) {
        assert paymentMethod.isValid();
        mAppStores.put(packageName, paymentMethod);
    }
}


text:
package org.apache.taverna.workbench.reference.config;

import javax.swing.JPanel;

import org.apache.taverna.configuration.Configurable;
import org.apache.taverna.configuration.ConfigurationUIFactory;
import org.apache.taverna.configuration.database.DatabaseConfiguration;
import org.apache.taverna.configuration.database.DatabaseManager;

public class DataManagementConfigurationUIFactory implements
		ConfigurationUIFactory {
	private DatabaseConfiguration databaseConfiguration;
	private DatabaseManager databaseManager;

	private DataManagementConfigurationPanel configPanel;

	@Override
	public boolean canHandle(String uuid) {
		return uuid.equals(getConfigurable().getUUID());
	}

	@Override
	public JPanel getConfigurationPanel() {
		if (configPanel == null)
			configPanel = new DataManagementConfigurationPanel(
					databaseConfiguration, databaseManager);
		configPanel.resetFields();
		return configPanel;
	}

	@Override
	public Configurable getConfigurable() {
		return databaseConfiguration;
	}

	public void setDatabaseConfiguration(
			DatabaseConfiguration databaseConfiguration) {
		this.databaseConfiguration = databaseConfiguration;
	}

	public void setDatabaseManager(DatabaseManager databaseManager) {
		this.databaseManager = databaseManager;
	}
}


text:
<?php namespace Maduser\Minimal\Controllers;

use Maduser\Minimal\Controllers\Contracts\FrontControllerInterface;
use Maduser\Minimal\Controllers\Exceptions\MethodNotExistsException;
use Maduser\Minimal\Controllers\Factories\Contracts\ControllerFactoryInterface;
use Maduser\Minimal\Controllers\Factories\Contracts\ModelFactoryInterface;
use Maduser\Minimal\Controllers\Factories\Contracts\ViewFactoryInterface;
use Maduser\Minimal\Http\Contracts\ResponseInterface;
use Maduser\Minimal\Routing\Contracts\RouteInterface;
use Maduser\Minimal\Routing\Contracts\RouterInterface;

/**
 * Class FrontController
 *
 * @package Maduser\Minimal\Core
 */
class FrontController implements FrontControllerInterface
{
    /**
     * @var RouterInterface
     */
    private $router;

    /**
     * @var ResponseInterface
     */
    private $response;

    /**
     * @var ResponseInterface
     */
    protected $modelFactory;

    /**
     * @var ResponseInterface
     */
    protected $viewFactory;

    /**
     * @var ControllerFactoryInterface
     */
    protected $controllerFactory;

    /**
     * @var RouteInterface
     */
    private $route;

    /**
     * @var
     */
    private $model;

    /**
     * @var
     */
    private $method;

    /**
     * @var
     */
    private $controller;

    /**
     * @var
     */
    private $action;

    /**
     * @var
     */
    private $view;

    /**
     * @var
     */
    private $result;

    /**
     * @var
     */
    private $modelResult;

    /**
     * @var
     */
    private $controllerResult;

    /**
     * @var
     */
    private $viewResult;

    /**
     * @var
     */
    private $params;

    /**
     * @return RouterInterface
     */
    public function getRouter(): RouterInterface
    {
        return $this->router;
    }

    /**
     * @param RouterInterface $router
     */
    public function setRouter(RouterInterface $router)
    {
        $this->router = $router;
    }

    /**
     * @return ResponseInterface
     */
    public function getResponse(): ResponseInterface
    {
        return $this->response;
    }

    /**
     * @param ResponseInterface $response
     */
    public function setResponse(ResponseInterface $response)
    {
        $this->response = $response;
    }

    /**
     * @return mixed
     */
    public function getRoute()
    {
        return $this->route;
    }

    /**
     * @param mixed $route
     */
    public function setRoute($route)
    {
        $this->route = $route;
    }

    /**
     * @return mixed
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * @param mixed $model
     */
    public function setModel($model)
    {
        $this->model = $model;
    }

    /**
     * @return mixed
     */
    public function getMethod()
    {
        return $this->method;
    }

    /**
     * @param mixed $method
     */
    public function setMethod($method)
    {
        $this->method = $method;
    }

    /**
     * @return mixed
     */
    public function getController()
    {
        return $this->controller;
    }

    /**
     * @param mixed $controller
     */
    public function setController($controller)
    {
        $this->controller = $controller;
    }

    /**
     * @return mixed
     */
    public function getAction()
    {
        return $this->action;
    }

    /**
     * @param mixed $action
     */
    public function setAction($action)
    {
        $this->action = $action;
    }

    /**
     * @return mixed
     */
    public function getView()
    {
        return $this->view;
    }

    /**
     * @param mixed $view
     */
    public function setView($view)
    {
        $this->view = $view;
    }

    /**
     * @param \Closure $function
     *
     * @return mixed
     */
    public function getResult(\Closure $function = null)
    {
        if (is_callable($function)) {
            return $function();
        }

        return ((!empty($this->viewResult)
            && !is_null($this->viewResult)
            && $this->viewResult !== false) ?
            $this->viewResult :
            (!empty($this->controllerResult)
                && !is_null($this->controllerResult)
                && $this->controllerResult !== false) ?
                $this->controllerResult : null);
    }

    /**
     * @param mixed $result
     */
    public function setResult($result)
    {
        $this->result = $result;
    }

    /**
     * @return mixed
     */
    public function getModelResult()
    {
        return $this->modelResult;
    }

    /**
     * @param mixed $modelResult
     */
    public function setModelResult($modelResult)
    {
        $this->modelResult = $modelResult;
    }

    /**
     * @return mixed
     */
    public function getControllerResult()
    {
        return $this->controllerResult;
    }

    /**
     * @param mixed $controllerResult
     */
    public function setControllerResult($controllerResult)
    {
        $this->controllerResult = $controllerResult;
    }

    /**
     * @return mixed
     */
    public function getViewResult()
    {
        return $this->viewResult;
    }

    /**
     * @param mixed $viewResult
     */
    public function setViewResult($viewResult)
    {
        $this->viewResult = $viewResult;
    }

    /**
     * @return mixed
     */
    public function getParams()
    {
        return $this->params;
    }

    /**
     * @param mixed $params
     */
    public function setParams($params)
    {
        $this->params = $params;
    }

    /**
     * FrontController constructor.
     *
     * @param RouterInterface            $router
     * @param ResponseInterface          $response
     * @param ModelFactoryInterface      $modelFactory
     * @param ViewFactoryInterface       $viewFactory
     * @param ControllerFactoryInterface $controllerFactory
     */
    public function __construct(
        RouterInterface $router,
        ResponseInterface $response,
        ModelFactoryInterface $modelFactory,
        ViewFactoryInterface $viewFactory,
        ControllerFactoryInterface $controllerFactory
    ) {
        /** @var \Maduser\Minimal\Providers\RouterProvider $router */
        $this->router = $router;
        $this->response = $response;
        $this->modelFactory = $modelFactory;
        $this->viewFactory = $viewFactory;
        $this->controllerFactory = $controllerFactory;
        $this->route = $this->router->getRoute();
    }

    /**
     * @param            $model
     * @param null       $method
     * @param array|null $params
     */
    public function handleModel($model, $method = null, array $params = null)
    {
        $this->setModel(
            $this->modelFactory->create($params, $model)
        );

        if (!is_null($method)) {
            $this->setModelResult(
                $this->executeMethod($this->getModel(), $method, $params)
            );
        }

    }

    /**
     * @param            $view
     * @param null       $method
     * @param array|null $params
     */
    public function handleView($view, $method = null, array $params = null)
    {
        $this->setView(
            $this->viewFactory->create($params, $view)
        );

        if (!is_null($method)) {
            $this->setViewResult(
                $this->executeMethod($this->getView(), $method)
            );
        }

    }

    /**
     * @param            $controller
     * @param null       $action
     * @param array|null $params
     */
    public function handleController(
        $controller,
        $action = null,
        array $params = null
    ) {

        $this->setController(
            $this->controllerFactory->create($params, $controller)
        );

        if (!is_null($action)) {
            $this->setControllerResult(
                $this->executeMethod($this->getController(), $action, $params)
            );
        }
    }

    /**
     * @param            $class
     * @param            $method
     * @param array|null $params
     *
     * @return mixed
     * @throws MethodNotExistsException
     */
    public function executeMethod($class, $method, array $params = null)
    {
        if (!method_exists($class, $method)) {
            throw new MethodNotExistsException(
                "Method '" . $method . "' does not exist in "
                . get_class($class)
            );
        }

        $params = $params ? $params : [];

        return call_user_func_array([$class, $method], $params);
    }

    public function dispatchController()
    {
        if (!empty($this->route->getController())) {
            $this->handleController(
                $this->route->getController(),
                $this->route->getAction(),
                $this->route->getParams()
            );
        };
    }

    public function dispatchModel()
    {
        if (!empty($this->route->getModel())) {
            $this->handleModel(
                $this->route->getModel(),
                $this->route->getMethod(),
                $this->route->getParams()
            );
        };
    }

    public function dispatchView()
    {
        if (!empty($this->route->getView())) {
            $this->handleView(
                $this->route->getView(),
                $this->route->getMethod(),
                $this->route->getParams()
            );
        };
    }

    /**
     * @param RouteInterface|null $route
     * @param \Closure            $function
     *
     * @return $this
     */
    public function dispatch(RouteInterface $route = null, \Closure $function = null)
    {
        /** @var RouteInterface $route */
        is_null($route) || $this->setRoute($route);

        if (is_callable($function)) {

            $this->setControllerResult($function($this));

        } elseif ($route->hasClosure()) {
            $this->setControllerResult(call_user_func_array(
                $route->getClosure(), $route->getParams())
            );

        } else {

            $this->dispatchController();
            $this->dispatchModel();
            $this->dispatchView();

        }

        return $this;
    }

    /**
     * @return mixed
     */
    public function respond()
    {
        $this->response->setContent($this->getResult())->send();

        return $this;
    }

    /**
     *
     */
    public function terminate()
    {
        $this->response->terminate();
    }
}


text:
// This is a generated file. Not intended for manual editing.
package com.intellij.plugins.haxe.lang.psi.impl;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypes.*;
import com.intellij.plugins.haxe.lang.psi.*;

public class HaxeExternClassDeclarationImpl extends AbstractHaxePsiClass implements HaxeExternClassDeclaration {

  public HaxeExternClassDeclarationImpl(ASTNode node) {
    super(node);
  }

  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof HaxeVisitor) ((HaxeVisitor)visitor).visitExternClassDeclaration(this);
    else super.accept(visitor);
  }

  @Override
  @Nullable
  public HaxeComponentName getComponentName() {
    return findChildByClass(HaxeComponentName.class);
  }

  @Override
  @Nullable
  public HaxeExternClassDeclarationBody getExternClassDeclarationBody() {
    return findChildByClass(HaxeExternClassDeclarationBody.class);
  }

  @Override
  @NotNull
  public HaxeExternKeyWord getExternKeyWord() {
    return findNotNullChildByClass(HaxeExternKeyWord.class);
  }

  @Override
  @Nullable
  public HaxeGenericParam getGenericParam() {
    return findChildByClass(HaxeGenericParam.class);
  }

  @Override
  @Nullable
  public HaxeInheritList getInheritList() {
    return findChildByClass(HaxeInheritList.class);
  }

  @Override
  @Nullable
  public HaxeMacroClassList getMacroClassList() {
    return findChildByClass(HaxeMacroClassList.class);
  }

  @Override
  @Nullable
  public HaxePrivateKeyWord getPrivateKeyWord() {
    return findChildByClass(HaxePrivateKeyWord.class);
  }

}


text:
ACCEPTED

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

#### Published in
Can. J. Bot. 50: 207 (1972)

#### Original name
Hydnum casearium Morgan, 1887

### Remarks
null


text:
title: Robert Klein

authors:
- robertklein

superuser: no

# Role/position
role: Student

# Organizations/Affiliations
organizations:
- name: Florida State University
  url: "https://fsu.edu"

# Short bio (displayed in user profile at end of posts)
bio: The author, a student at Florida State University, was enrolled in the digital microhistory lab in Spring 2020.

interests:
- I am on the club waterpolo team here at Florida State University, and I also always enjoy playing video games with my friends.
- I am pursuing a career in Biomedical Engineering.

social:
- icon: github
  icon_pack: fab
  link: https://github.com/skyylartheswimmer

user_groups:
- Writers
---
The author, a student at Florida State University, was enrolled in the digital microhistory lab in spring 2020.


text:
package com.bimass.internal;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class HelloWorldService {
    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String msg) {
        String output = "Service says : " + msg;
        return Response.status(200).entity(output).build();
    }

}


text:
void expected_results()
{
   //
   // Define the max and mean errors expected for
   // various compilers and platforms.
   //
   add_expected_result(
      ".*",                          // compiler
      ".*",                          // stdlib
      ".*",                          // platform
      ".*gmp.*",                     // test type(s)
      ".*",                          // test data group
      ".*", 3000, 1500);             // test function
   add_expected_result(
      ".*",                          // compiler
      ".*",                          // stdlib
      ".*",                          // platform
      ".*mpfr_float_backend<18>.*",  // test type(s)
      ".*",                          // test data group
      ".*", 750, 150);               // test function
   add_expected_result(
      ".*",                          // compiler
      ".*",                          // stdlib
      ".*",                          // platform
      ".*",                          // test type(s)
      ".*",                          // test data group
      ".*", 100, 20);                // test function
   //
   // Finish off by printing out the compiler/stdlib/platform names,
   // we do this to make it easier to mark up expected error rates.
   //
   std::cout << "Tests run with " << BOOST_COMPILER << ", "
      << BOOST_STDLIB << ", " << BOOST_PLATFORM << std::endl;
}

int test_main(int, char* [])
{
   using namespace boost::multiprecision;
   expected_results();
   //
   // Test at:
   // 18 decimal digits: tests 80-bit long double approximations
   // 30 decimal digits: tests 128-bit long double approximations
   // 35 decimal digits: tests arbitrary precision code
   //
#ifdef TEST_MPF_50
   // We have accuracy issues with gmp_float<18> - our argument reduction in std::sin isn't accurate enough:
   test_binomial(number<gmp_float<18> >(), "number<gmp_float<18> >");
   test_binomial(number<gmp_float<30> >(), "number<gmp_float<30> >");
   test_binomial(number<gmp_float<35> >(), "number<gmp_float<35> >");
   // there should be at least one test with expression templates off:
   test_binomial(number<gmp_float<35>, et_off>(), "number<gmp_float<35>, et_off>");
#endif
#ifdef TEST_MPFR_50
   test_binomial(number<mpfr_float_backend<18> >(), "number<mpfr_float_backend<18> >");
   test_binomial(number<mpfr_float_backend<30> >(), "number<mpfr_float_backend<30> >");
   test_binomial(number<mpfr_float_backend<35> >(), "number<mpfr_float_backend<35> >");
#endif
#ifdef TEST_CPP_DEC_FLOAT
   test_binomial(number<cpp_dec_float<18> >(), "number<cpp_dec_float<18> >");
   test_binomial(number<cpp_dec_float<30> >(), "number<cpp_dec_float<30> >");
   test_binomial(number<cpp_dec_float<35, long long, std::allocator<void> > >(), "number<cpp_dec_float<35, long long, std::allocator<void> > >");
#endif
   return 0;
}


text:
@interface KSCrashReportSinkVictory ()

@property(nonatomic,readwrite,retain) NSURL* url;
@property(nonatomic,readwrite,retain) NSString* userName;
@property(nonatomic,readwrite,retain) NSString* userEmail;

@property(nonatomic,readwrite,retain) KSReachableOperationKSCrash* reachableOperation;

@end

@implementation KSCrashReportSinkVictory

@synthesize url = _url;
@synthesize userName = _userName;
@synthesize userEmail = _userEmail;
@synthesize reachableOperation = _reachableOperation;

+ (KSCrashReportSinkVictory*) sinkWithURL:(NSURL*) url
                                   userName:(NSString*) userName
                                  userEmail:(NSString*) userEmail
{
    return [[self alloc] initWithURL:url userName:userName userEmail:userEmail];
}

- (id) initWithURL:(NSURL*) url
          userName:(NSString*) userName
         userEmail:(NSString*) userEmail
{
    if((self = [super init]))
    {
        self.url = url;
        if (userName == nil || [userName length] == 0) {
#if KSCRASH_HAS_UIDEVICE
            self.userName = UIDevice.currentDevice.name;
#else
            self.userName = @"unknown";
#endif
        }
        else {
            self.userName = userName;
        }
        self.userEmail = userEmail;
    }
    return self;
}

- (id <KSCrashReportFilter>) defaultCrashReportFilterSet
{
    return self;
}

- (void) filterReports:(NSArray*) reports
          onCompletion:(KSCrashReportFilterCompletion) onCompletion
{
    // update user information in reports with KVC
    for (NSDictionary *report in reports) {
        NSDictionary *userDict = [report objectForKey:@"user"];
        if (userDict) {
            // user member is exist
            [userDict setValue:self.userName forKey:@"name"];
            [userDict setValue:self.userEmail forKey:@"email"];
        }
        else {
            // no user member, append user dictionary
            [report setValue:@{@"name": self.userName, @"email": self.userEmail} forKey:@"user"];
        }
    }

    NSError* error = nil;
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:self.url
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:15];
    KSHTTPMultipartPostBody* body = [KSHTTPMultipartPostBody body];
    NSData* jsonData = [KSJSONCodec encode:reports
                                   options:KSJSONEncodeOptionSorted
                                     error:&error];
    if(jsonData == nil)
    {
        kscrash_i_callCompletion(onCompletion, reports, NO, error);
        return;
    }

    [body appendData:jsonData
                name:@"reports"
         contentType:@"application/json"
            filename:@"reports.json"];

    // POST http request
    // Content-Type: multipart/form-data; boundary=xxx
    // Content-Encoding: gzip
    request.HTTPMethod = @"POST";
    request.HTTPBody = [[body data] gzippedWithCompressionLevel:-1 error:nil];
    [request setValue:body.contentType forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
    [request setValue:@"KSCrashReporter" forHTTPHeaderField:@"User-Agent"];

    self.reachableOperation = [KSReachableOperationKSCrash operationWithHost:[self.url host]
                                                                   allowWWAN:YES
                                                                       block:^
    {
        [[KSHTTPRequestSender sender] sendRequest:request
                                        onSuccess:^(__unused NSHTTPURLResponse* response, __unused NSData* data)
         {
             kscrash_i_callCompletion(onCompletion, reports, YES, nil);
         } onFailure:^(NSHTTPURLResponse* response, NSData* data)
         {
             NSString* text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             kscrash_i_callCompletion(onCompletion, reports, NO,
                                      [NSError errorWithDomain:[[self class] description]
                                                          code:response.statusCode
                                                   description:text]);
         } onError:^(NSError* error2)
         {
             kscrash_i_callCompletion(onCompletion, reports, NO, error2);
         }];
    }];
}

@end


text:
package com.sys1yagi.mydicontainer.container;

public interface Provider<T> {

    T get();
}


text:
import Router from 'koa-router';
import qiniu from 'qiniu';
import fetch from 'node-fetch';
import fs from 'fs';
import invariant from 'invariant';
import { name as packageName } from '../package.json';

const router = new Router();
const BASE64_URL = 'http://up.qiniu.com/putb64/-1';
const noop = () => {};

const removeFiles = (files) => Object
	.keys(files)
	.forEach((name) => {
		[].concat(files[name]).forEach((f) => fs.unlink(f.path, noop));
	})
;

const throwError = (missingParamName) => {
	throw new Error(`[${packageName}] missing param \`${missingParamName}\`.`);
};

const uploadBase64 = (token, file) => fetch(BASE64_URL, {
	method: 'POST',
	headers: {
		Authorization: `UpToken ${token}`,
	},
	body: file.split(',')[1],
})
.then((res) => res.json());

const uploadFile = (token, file) => new Promise((resolve, reject) => {
	const extra = new qiniu.io.PutExtra();
	qiniu.io.putFile(token, null, file, extra, (err, res) => {
		if (!err) { resolve(res); }
		else { reject(err); }
	});
});

export default (config) => {
	const {
		accessKey,
		secretKey,
		baseURL,
		bucket = 'my_bucket',
		fileFormName = 'file',
		base64FormName = 'base64',
		fileUploadPathName = '/upload',
		base64UploadPathName = '/upload/base64',
		onError = noop,
		filesBodyParser = (ctx) => ctx.request.body.files,
	} = config;

	['accessKey', 'secretKey', 'baseURL'].forEach((p) => {
		invariant(config[p], `[${packageName}] missing param: ${p}`);
	});

	const getUptoken = () => {
		const putPolicy = new qiniu.rs.PutPolicy(bucket);
		return putPolicy.token();
	};

	const response = (ctx, file, upload) =>
		upload(getUptoken(), file).then(({ key }) =>
			ctx.body = { url: baseURL + key }
		)
	;

	qiniu.conf.ACCESS_KEY = accessKey;
	qiniu.conf.SECRET_KEY = secretKey;

	router.post(fileUploadPathName, function * () {
		try {
			const files = filesBodyParser(this);
			const file = [].concat(files[fileFormName])[0];
			if (file) {
				yield response(this, file.path, uploadFile);
				removeFiles(files);
			}
			else {
				throwError(fileFormName);
			}
		}
		catch (error) {
			removeFiles(this.request.body.files);
			onError.call(this, error, this);
		}
	});

	router.post(base64UploadPathName, function * () {
		try {
			const base64 = this.request.body[base64FormName];
			if (base64) {
				yield response(this, base64, uploadBase64);
			}
			else {
				throwError(base64FormName);
			}
		}
		catch (error) {
			onError.call(this, error, this);
		}
	});

	return router.middleware();
};