text:
<?php

namespace Sylius\Bundle\CoreBundle\EventListener;

use Sylius\Bundle\CoreBundle\Mailer\Emails;
use Sylius\Component\Core\Model\CustomerInterface;
use Sylius\Component\Mailer\Sender\SenderInterface;
use Sylius\Component\Order\Model\CommentInterface;
use Sylius\Component\Resource\Exception\UnexpectedTypeException;
use Symfony\Component\EventDispatcher\GenericEvent;

/**
 * Generic mailer listener.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class MailerListener
{
    /**
     * @var SenderInterface
     */
    protected $emailSender;

    /**
     * @param SenderInterface $emailSender
     */
    public function __construct(SenderInterface $emailSender)
    {
        $this->emailSender = $emailSender;
    }

    /**
     * @param GenericEvent $event
     *
     * @throws UnexpectedTypeException
     */
    public function sendUserConfirmationEmail(GenericEvent $event)
    {
        $customer = $event->getSubject();

        if (!$customer instanceof CustomerInterface) {
            throw new UnexpectedTypeException(
                $customer,
                CustomerInterface::class
            );
        }

        if (null === ($user = $customer->getUser())) {
            return;
        }

        if (!$user->isEnabled()) {
            return;
        }

        if (null === ($email = $customer->getEmail()) || empty($email)) {
            return;
        }

        $this->emailSender->send(Emails::USER_CONFIRMATION, [$email], ['user' => $user]);
    }

    /**
     * @param GenericEvent $event
     *
     * @throws UnexpectedTypeException
     */
    public function sendOrderCommentEmail(GenericEvent $event)
    {
        $comment = $event->getSubject();

        if (!$comment instanceof CommentInterface) {
            throw new UnexpectedTypeException(
                $comment,
                'Sylius\Component\Order\Model\CommentInterface'
            );
        }

        if (!$comment->getNotifyCustomer()) {
            return;
        }

        if (null === $order = $comment->getOrder()) {
            return;
        }

        if (null === $order->getCustomer()) {
            return;
        }

        if (null === ($email = $order->getCustomer()->getEmail()) || empty($email)) {
            return;
        }

        $this->emailSender->send(
            Emails::ORDER_COMMENT,
            [$email],
            [
                'order' => $order,
                'comment' => $comment,
            ]
        );
    }
}


text:
[[2017-05-08] Challenge #314 [Easy] Concatenated Integers](https://www.reddit.com/r/dailyprogrammer/comments/69y21t/20170508_challenge_314_easy_concatenated_integers/)

# Description

Given a list of integers separated by a single space on standard input, print out the largest and smallest values that can be obtained by concatenating the integers together on their own line. This is from [Five programming problems every Software Engineer should be able to solve in less than 1 hour](http://www.shiftedup.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour), problem 4. Leading 0s are not allowed (e.g. 01234 is not a valid entry).

This is an easier version of [#312I](https://www.reddit.com/r/dailyprogrammer/comments/67q3s6/20170426_challenge_312_intermediate_next_largest/?utm_content=title&utm_medium=hot&utm_source=reddit&utm_name=dailyprogrammer).

# Sample Input

You'll be given a handful of integers per line. Example:

	5 56 50

# Sample Output

You should emit the smallest and largest integer you can make, per line. Example:

	50556 56550

# Challenge Input

	79 82 34 83 69
	420 34 19 71 341
	17 32 91 7 46

# Challenge Output

	3469798283 8382796934
	193413442071 714203434119
	173246791 917463217

# Bonus

**EDIT** My solution uses permutations, which is inefficient. Try and come up with a more efficient approach.

redpajama_set_name: RedPajamaGithub


text:
/**
 * Provides classes to manage all JRebirth facades.
 *
 * Define All ***Ready interfaces to create components compliant with JRebirth  basis.
 */
package org.jrebirth.core.facade;


text:
<?php

namespace EOSUser;
/**
 * Description of Module
 *
 * @author ennio
 */
class Module
{

    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'EOSUser\Auth\DoctrineAdapter' => function($sm){
                    return Auth\DoctrineAdapter($sm->get('Doctrine\ORM\EntityManager'));
                }
            )
        );
    }

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

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


text:
<?php

namespace Orchestra\Tests\Controller;

use Illuminate\Support\Facades\Route;
use Orchestra\Foundation\Testing\Installation;

class LogoutTest extends TestCase
{
    use Installation;

    /** @test */
    public function it_can_logout_an_admin()
    {
        $this->actingAs($this->adminUser)
            ->makeRequest('POST', 'admin/logout', ['_method' => 'DELETE'])
            ->seePageIs('admin/login');

        $this->dontSeeIsAuthenticated();
    }

    /** @test */
    public function it_can_logout_an_admin_with_redirection()
    {
        Route::get('welcome', function () {
            return 'Hello world';
        });

        $this->actingAs($this->adminUser)
            ->makeRequest('POST', 'admin/logout', ['_method' => 'DELETE', 'redirect' => 'welcome'])
            ->seePageIs('welcome')
            ->seeText('Hello world');

        $this->dontSeeIsAuthenticated();
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Fast 'n Curious</title>
  <link href="<?php echo base_url('/vendors/css/bootstrap.min.css');?>" rel="stylesheet">
  <link href="<?php echo base_url('/vendors/css/animate.min.css');?>" rel="stylesheet">
  <link href="<?php echo base_url('/vendors/css/font-awesome.min.css');?>" rel="stylesheet">
  <link href="<?php echo base_url('/vendors/css/lightbox.css');?>" rel="stylesheet">

  <link id="css-preset" href="<?php echo base_url('/vendors/css/presets/preset1.css');?>" rel="stylesheet">
  <link href="<?php echo base_url('/vendors/css/main.css');?>" rel="stylesheet">
  <link href="<?php echo base_url('/vendors/css/responsive.css');?>" rel="stylesheet">

  <link href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700' rel='stylesheet' type='text/css'>
  <link rel="shortcut icon" href="<?php echo base_url('/vendors/images/favicon.ico');?>">
    <link rel="stylesheet" href="<?php echo base_url('/vendors/css/blueimp-gallery.min.css');?>">

Restoran

        <div class="item active" style="background-image: url(<?php echo base_url('/vendors/images/Background/Wallpapers-fruit-flowers-black-background-hd-desktop-wallpapers.jpg');?>)">

              <img class="media-object displayPicture img-circle  letakMediaRestoran" src="<?php echo base_url('/vendors/images/Background/337094-zero.jpg');?>" alt="Generic placeholder image">

 <?php echo $resto->NAMA_RESTORAN ;?>

 <?php echo ' '.$resto->ALAMAT_RESTORAN ;?>

 <?php echo  ' '.$resto->NO_TELEPON_RESTORAN ;?>

 <?php echo  ' '.$resto->HARI_BUKA_RESTORAN.','.$resto->JAM_BUKA_RESTORAN ;?>

<?php echo  ' '.$resto->STATUS ;?>

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>
          <a class="navbar-brand" href="<?php echo site_url('fatncurious');?>">
            <img class="img-responsive" src="<?php echo base_url('vendors/images/logo.png'); ?>" alt="logo">

<a href="<?php echo site_url('/fatncurious') ?>">Home

About Us

      					FilterBy

Biggest Promo

Restaurant Names

Menu

Credit Cards

Contact Us

  			<?php
  				if(isset($kodeUser)){
  			?>

              <img src="<?php echo base_url('vendors/images/team/2.jpg'); ?>" class="img-circle displayPictureNavBar">

Profile

Ganti Password

Logout

  			<?php
  				}
  			?>

 Give Rating

 <span class="glyphicon <?php echo $glyphicon1;?> bintang" data-val="1" aria-hidden="true">
                      <span class="glyphicon <?php echo $glyphicon2;?> bintang" data-val="2" aria-hidden="true">
                      <span class="glyphicon <?php echo $glyphicon3;?> bintang" data-val="3" aria-hidden="true">
                      <span class="glyphicon <?php echo $glyphicon4;?> bintang" data-val="4" aria-hidden="true">
                      <span class="glyphicon <?php echo $glyphicon5;?> bintang" aria-hidden="true" data-val="5">

Sorted By :

                  <li role="presentation" class="<?php echo $active1.' ';?> toogleNavBar"><a href="<?php echo site_url('/fatncurious/sortByPromoRestoran/'.$resto->KODE_RESTORAN.'') ?>">Promo

                  <li role="presentation" class="<?php echo $active2.' ';?> toogleNavBar"><a href="<?php echo site_url('/fatncurious/sortByKreditRestoran/'.$resto->KODE_RESTORAN.'') ?>">Kartu Kredit

                  <li role="presentation" class="<?php echo $active3.' ';?> toogleNavBar"><a href="<?php echo site_url('/fatncurious/sortByMenuRestoran/'.$resto->KODE_RESTORAN.'') ?>">Jenis Menu

Lihat Review Restoran

        <?php
			if(isset($promo)){
				foreach($promo as $p){
					echo "
";
						echo "
";
						echo "";
		?>
							<img class="media-object img-rounded img-responsive fotoPromo"  src="<?php echo base_url('/vendors/images/promo/'.$p->FOTO_PROMO);?>" alt="...">
		<?php
						echo "";
						echo "
";
					echo "";
				}
			}
		?>

		<?php
		$adaMenu=false;
		//===========MAKANAN=========
			if(isset($menu)){
        $ctrRow = 0;
				echo "
MAKANAN
";
				foreach($menu as $m){

					if($m->KODE_JENIS_MENU == 'JM001'){
						$adaMenu=true;
						echo "
";
							echo "
";
			?>
							<img class="media-object displayPicture displayPictureMenu img-rounded"  src="<?php echo base_url('/vendors/images/menu/nasi goreng/1.jpg');?>" alt="..." row-id="<?php echo $ctrRow; ?>">
			<?php
							echo "
";
						  echo "
";
							echo "
".$m->NAMA_MENU."
";
							echo $m->DESKRIPSI_MENU;
							echo "
";
              if(isset($review[$m->KODE_MENU])){
                foreach($review[$m->KODE_MENU] as $r){
                  echo "
";?>
                    <img class="media-object displayPictureComment img-circle" src="<?php echo base_url('/vendors/images/team/1.jpg');?>" alt="Generic placeholder image">
      <?php
                  echo "
";
                  echo "
";
                  echo "
" . $r->NAMA ."
";
                  echo $r->DESKRIPSI_REVIEW;
                  echo "
";
                  echo "
";
                }
              }

              echo form_open('fatncurious/sortByMenuRestoran');
							echo "
";
              echo "<input type='text' class='form-control' placeholder='Tuliskan Komen disini..' name='txtReview'>";
              echo "";
              echo form_hidden('menu',$m->KODE_MENU);
              echo form_hidden('resto',$m->KODE_RESTORAN);
              $arr = ['class'=>'btn btn-default img-rounded','name'=>'btnGo','value'=>'Go!'];
              echo form_submit($arr);
              echo "";
							echo "
";
              echo form_close();
              echo "
";
              echo "
";
            }
            //gallery
    				echo "
";
    					echo "
";
    						echo "
";
    							echo "
";
                  $ctr=1;
    								foreach($fotoMenu as $f){
                      if($f->KODE_MENU == $m->KODE_MENU){
                        echo "
";
      									?>
      										<a href="<?php echo base_url('/vendors/images/menu/'.$m->KODE_RESTORAN.'/'.$m->KODE_MENU.'/'.$ctr.'.jpg');?>">
      											<img src="<?php echo base_url('/vendors/images/menu/'.$m->KODE_RESTORAN.'/'.$m->KODE_MENU.'/'.$ctr.'.jpg');?>" class="img-responsive">

      									<?php
      									echo "
";
      									$ctr++;
                      }
    								}
    							echo "
";
    						echo "
";
    					echo "
";
    				echo "
";

            $ctrRow++;
            //gallery
				}
				if($adaMenu==false){
					echo "
Tidak Ada Menu Makanan
";
				}
			}

			//===========MAKANAN=========
		?>

		<?php
		$adaMenu=false;
		//===========MINUMAN=========
			if(isset($menu)){
				echo "
MINUMAN
";
        foreach($menu as $m){
					if($m->KODE_JENIS_MENU == 'JM002'){
						$adaMenu=true;
						echo "
";
							echo "
";
			?>
							<img class="media-object displayPicture displayPictureMenu img-rounded"  src="<?php echo base_url('/vendors/images/menu/nasi goreng/1.jpg');?>" alt="..." row-id="<?php echo $ctrRow; ?>">
			<?php
							echo "
";
						  echo "
";
							echo "
".$m->NAMA_MENU."
";
							echo $m->DESKRIPSI_MENU;
							echo "
";
              if(isset($review[$m->KODE_MENU])){
                foreach($review[$m->KODE_MENU] as $r){
                  echo "
";?>
                    <img class="media-object displayPictureComment img-circle" src="<?php echo base_url('/vendors/images/team/1.jpg');?>" alt="Generic placeholder image">
      <?php
                  echo "
";
                  echo "
";
                  echo "
" . $r->NAMA ."
";
                  echo $r->DESKRIPSI_REVIEW;
                  echo "
";
                  echo "
";
                }
              }
              echo form_open('fatncurious/sortByMenuRestoran');
							echo "
";
              echo "<input type='text' class='form-control' placeholder='Tuliskan Komen disini..' name='txtReview'>";
              echo "";
              echo form_hidden('menu',$m->KODE_MENU);
              echo form_hidden('resto',$m->KODE_RESTORAN);
              $arr = ['class'=>'btn btn-default img-rounded','name'=>'btnGo','value'=>'Go!'];
              echo form_submit($arr);
              echo "";
							echo "
";
              echo form_close();
              echo "
";
              echo "
";
            }

            //gallery
            echo "
";
              echo "
";
                echo "
";
                  echo "
";
                  $ctr=1;
                    foreach($fotoMenu as $f){
                      if($f->KODE_MENU == $m->KODE_MENU){
                        echo "
";
                        ?>
                          <a href="<?php echo base_url('/vendors/images/menu/'.$m->KODE_RESTORAN.'/'.$m->KODE_MENU.'/'.$ctr.'.jpg');?>">
                            <img src="<?php echo base_url('/vendors/images/menu/'.$m->KODE_RESTORAN.'/'.$m->KODE_MENU.'/'.$ctr.'.jpg');?>" class="img-responsive">

                        <?php
                        echo "
";
                        $ctr++;
                      }
                    }
                  echo "
";
                echo "
";
              echo "
";
            echo "
";

            $ctrRow++;
            //gallery
				}
				if($adaMenu==false){
					echo "
Tidak Ada Menu Minuman
";
				}
			}
			//===========MINUMAN=========
		?>

		<?php
		$adaMenu=false;
		//===========SNACK=========
			if(isset($menu)){
				echo "
SNACK
";
				foreach($menu as $m){

					if($m->KODE_JENIS_MENU == 'JM003'){
						$adaMenu=true;
						echo "
";
							echo "
";
			?>
							<img class="media-object displayPicture displayPictureMenu img-rounded"  src="<?php echo base_url('/vendors/images/menu/nasi goreng/1.jpg');?>" alt="..." row-id="<?php echo $ctrRow; ?>">
			<?php
							echo "
";
						  echo "
";
							echo "
".$m->NAMA_MENU."
";
							echo $m->DESKRIPSI_MENU;
							echo "
";
              if(isset($review[$m->KODE_MENU])){
                foreach($review[$m->KODE_MENU] as $r){
                  echo "
";?>
                    <img class="media-object displayPictureComment img-circle" src="<?php echo base_url('/vendors/images/team/1.jpg');?>" alt="Generic placeholder image">
      <?php
                  echo "
";
                  echo "
";
                  echo "
" . $r->NAMA ."
";
                  echo $r->DESKRIPSI_REVIEW;
                  echo "
";
                  echo "
";
                }
              }
              echo form_open('fatncurious/sortByMenuRestoran');
							echo "
";
              echo "<input type='text' class='form-control' placeholder='Tuliskan Komen disini..' name='txtReview'>";
              echo "";
              echo form_hidden('menu',$m->KODE_MENU);
              echo form_hidden('resto',$m->KODE_RESTORAN);
              $arr = ['class'=>'btn btn-default img-rounded','name'=>'btnGo','value'=>'Go!'];
              echo form_submit($arr);
              echo "";
							echo "
";
              echo form_close();
              echo "
";
              echo "
";
            }

            //gallery
            echo "
";
              echo "
";
                echo "
";
                  echo "
";
                  $ctr=1;
                    foreach($fotoMenu as $f){
                      if($f->KODE_MENU == $m->KODE_MENU){
                        echo "
";
                        ?>
                          <a href="<?php echo base_url('/vendors/images/menu/'.$m->KODE_RESTORAN.'/'.$m->KODE_MENU.'/'.$ctr.'.jpg');?>">
                            <img src="<?php echo base_url('/vendors/images/menu/'.$m->KODE_RESTORAN.'/'.$m->KODE_MENU.'/'.$ctr.'.jpg');?>" class="img-responsive">

                        <?php
                        echo "
";
                        $ctr++;
                      }
                    }
                  echo "
";
                echo "
";
              echo "
";
            echo "
";

            $ctrRow++;
            //gallery
				}
				if($adaMenu==false){
					echo "
Tidak Ada Menu Snack
";
				}
			}
			//===========SNACK=========
		?>

		<?php
		$adaMenu=false;
		//===========Kredit=========
			if(isset($kartu)){
				echo "
Kartu Kredit
";
				foreach($kartu as $k){
					echo "
";
						echo "
";
			?>
						<img class="media-object displayPicture displayPictureMenu img-rounded"  src="<?php echo base_url('/vendors/images/menu/nasi goreng/1.jpg');?>" alt="...">
			<?php
						echo "
";
					echo "
";
						echo "
".$k->KARTU."
";
						echo "Deskripsi : ".$k->DESKRIPSI_PROMO."
";
						echo "Persentase : ".$k->PERSENTASE_PROMO."
";
						echo "
";
							echo "
";
			?>
							<img class="media-object displayPictureComment img-circle" src="<?php echo base_url('/vendors/images/team/1.jpg');?>" alt="Generic placeholder image">
			<?php
							echo "
";
							echo "
";
								echo "
Michelle Withney
";
								echo "Promo Termurahh.....";
							echo "
";
						echo "
";
						echo "
";
						echo "
";
							echo "<input type='text' class='form-control' placeholder='Tuliskan Komen disini..'>";
							echo "";
								echo "<button class='btn btn-default img-rounded' type='button'>Go!</button>";
							echo "";
						echo "
";
					echo "
";
					echo "
";
				}
			}
			//===========Kredit=========
		?>

        ‹
        ›
        ×


text:
from __future__ import print_function

import re
import copy
import os,sys
import requests
from time import sleep
from bs4 import BeautifulSoup
from contextlib import closing
from selenium import webdriver
from selenium.webdriver.common import keys
from selenium.common.exceptions import NoSuchElementException

class ProgressBar(object):
	""" to show a simple progress-bar """

	def __init__(self, title, count=0.0, run_status=None, fin_status=None,
		total=100.0, unit='', sep='/', chunk_size=1.0):
		super(ProgressBar, self).__init__()
		self.info = "[%s] %s %.2f %s %s %.2f %s"
		self.title = title
		self.count = count
		self.status = run_status or ""
		self.fin_status = fin_status or " "*len(self.status)
		self.total = total
		self.unit = unit
		self.sep = sep
		self.chunk_size = chunk_size

	def __get_info(self):
		_info = self.info %(self.title, self.status, self.count/self.chunk_size, \
			self.unit, self.sep, self.total/self.chunk_size, self.unit)
		return _info

	def refresh(self, count=1, status=None):
		self.count += count
		self.status = status or self.status
		end_str = "\r"
		if self.count >= self.total:
			end_str = "\n"
			self.status = status or self.fin_status
		print(self.__get_info(), end=end_str)

class PaperDownloader(object):
	""" Download the exact paper given the title on
	http://ieeexplore.ieee.org/ (find the first one)"""

	def __init__(self, title):
		self.title  = title
		#self.driver = webdriver.PhantomJS('/home/rumia/WebDrivers/PhantomJS/phantomjs')
		self.driver = webdriver.PhantomJS('/root/dingcc/PhantomJS/phantomjs')
		self.driver.implicitly_wait(10)
		self.search = 'http://ieeexplore.ieee.org/search/searchresult.jsp?&queryText=' + title
		self.headers = {
			'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \
			(KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36'
		}

	def __get_download_page(self):
		print('[*] Searching for paper <%s>' %(self.title))
		self.driver.get(self.search)
		try:
			element = self.driver.find_element_by_class_name('icon-pdf')
			element.click()
			download_page = copy.copy(self.driver.current_url)
			print('[+] Find download page ==> %s' %(download_page))
			self.driver.quit()
			return download_page
		except Exception, error:
			print('[-]', error)
			self.driver.quit()
			return None

	def get_pdf_url(self):
		download_page = self.__get_download_page()
		if download_page != None:
			r = requests.get(download_page, headers=self.headers)
		else:
			print('[-] Failed to get PDF url <%s>' %(self.title))
			return None
		if r.status_code == 200:
			soup = BeautifulSoup(r.content, 'lxml')
			r.close()
		tag = soup.find('frame', src=re.compile(r'http://.*'))
		try:
			print('[+] Get PDF url for <%s>' %(self.title))
			return tag['src']
		except Exception, error:
			print('[-]', error)
			return None

	def download_pdf(self):
		filename = self.title.replace('/', '\\')
		filename = filename.replace(' ', '+') + '.pdf'
		if filename in os.listdir(os.getcwd()):
			print('[-] File already exists <%s>\n' %(filename))
			return None
		pdf_url = self.get_pdf_url()
		if pdf_url == None:
			print('[-] Failed to download <%s>\n' %(self.title))
			return None
		else:
			with closing(requests.get(pdf_url, headers=self.headers, stream=True)) as r:
				try:
					content_size = int(r.headers['content-length'])
				except:
					print('[-] Unknown content-length')
					return None
				progress = ProgressBar('Target PDF', total=content_size, unit='KB', \
				chunk_size=1024, run_status='Downloading', fin_status='Downloaded')
				try:
					with open(filename, 'wb') as dst_file:
						for chunk in r.iter_content(chunk_size=1024):
							dst_file.write(chunk)
							dst_file.flush()
							progress.refresh(count=len(chunk))
					print('[+] Downloaded <%s>\n' %(self.title))
				except Exception, error:
					print('[-]', error)
					print('[-] Failed to download\n <%s>' %(self.title))
					return None
				return filename

#####################
##### TEST PART #####
#####################

"""
PD = PaperDownloader('Cruncher: Distributed in-memory processing for location-based services')
PD.download_pdf()
"""


text:
package org.apache.usergrid;

import java.util.UUID;

import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.usergrid.cassandra.CassandraResource;
import org.apache.usergrid.mq.QueueManagerFactory;
import org.apache.usergrid.persistence.EntityManagerFactory;
import org.apache.usergrid.persistence.IndexBucketLocator;
import org.apache.usergrid.persistence.cassandra.CassandraService;
import org.apache.usergrid.utils.JsonUtils;

public class CoreITSetupImpl implements CoreITSetup {
    private static final Logger LOG = LoggerFactory.getLogger( CoreITSetupImpl.class );

    protected EntityManagerFactory emf;
    protected QueueManagerFactory qmf;
    protected IndexBucketLocator indexBucketLocator;
    protected CassandraService cassandraService;
    protected CassandraResource cassandraResource;
    protected boolean enabled = false;

    public CoreITSetupImpl( CassandraResource cassandraResource ) {
        this.cassandraResource = cassandraResource;
    }

    @Override
    public Statement apply( Statement base, Description description ) {
        return statement( base, description );
    }

    private Statement statement( final Statement base, final Description description ) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                before( description );

                try {
                    base.evaluate();
                }
                finally {
                    after( description );
                }
            }
        };
    }

    /**
     * Sets up the resources for the test here.
     *
     * @throws Throwable if setup fails (which will disable {@code after}
     */
    protected void before( Description description ) throws Throwable {
        LOG.info( "Setting up for {}", description.getDisplayName() );
        initialize();
    }

    private void initialize() {
        if ( !enabled ) {
            emf = cassandraResource.getBean( EntityManagerFactory.class );
            qmf = cassandraResource.getBean( QueueManagerFactory.class );
            indexBucketLocator = cassandraResource.getBean( IndexBucketLocator.class );
            cassandraService = cassandraResource.getBean( CassandraService.class );
            enabled = true;
        }
    }

    /** Override to tear down your specific external resource. */
    protected void after( Description description ) {
        LOG.info( "Tearing down for {}", description.getDisplayName() );
    }

    @Override
    public EntityManagerFactory getEmf() {
        if ( emf == null ) {
            initialize();
        }

        return emf;
    }

    @Override
    public QueueManagerFactory getQmf() {
        if ( qmf == null ) {
            initialize();
        }

        return qmf;
    }

    @Override
    public IndexBucketLocator getIbl() {
        if ( indexBucketLocator == null ) {
            initialize();
        }

        return indexBucketLocator;
    }

    @Override
    public CassandraService getCassSvc() {
        if ( cassandraService == null ) {
            initialize();
        }

        return cassandraService;
    }

    @Override
    public UUID createApplication( String organizationName, String applicationName ) throws Exception {
        if ( USE_DEFAULT_APPLICATION ) {
            return CassandraService.DEFAULT_APPLICATION_ID;
        }

        if ( emf == null ) {
            emf = cassandraResource.getBean( EntityManagerFactory.class );
        }

        return emf.createApplication( organizationName, applicationName );
    }

    @Override
    public void dump( String name, Object obj ) {
        if ( obj != null && LOG.isInfoEnabled() ) {
            LOG.info( name + ":\n" + JsonUtils.mapToFormattedJsonString( obj ) );
        }
    }
}


text:
FactoryBot.define do
  factory :solar_edge_installation do
    school
    sequence(:site_id, (100000..900000).cycle)  { |n| n }
    amr_data_feed_config
    sequence(:mpan)   { |n| n }
    sequence(:api_key)   { |n| "api_key_#{n}" }

    factory :solar_edge_installation_with_meters_and_validated_readings do

      transient do
        reading_count { 1 }
        config        { create(:amr_data_feed_config, process_type: :solar_edge_api) }
      end

      after(:create) do |solar_edge_installation, evaluator|
        electricity_meter = create(:electricity_meter_with_validated_reading, mpan_mprn: 60000000000000 + solar_edge_installation.mpan.to_i, pseudo: true, solar_edge_installation: solar_edge_installation)
        solar_pv_meter = create(:electricity_meter_with_validated_reading, mpan_mprn: 70000000000000 + solar_edge_installation.mpan.to_i, pseudo: true, solar_edge_installation: solar_edge_installation)
        solar_pv_meter.update(meter_type: :solar_pv)
        export_meter = create(:electricity_meter_with_validated_reading, mpan_mprn: 90000000000000 + solar_edge_installation.mpan.to_i, pseudo: true, solar_edge_installation: solar_edge_installation)
        export_meter.update(meter_type: :exported_solar_pv)
      end
    end

  end
end


text:
var ChunkInterface = require('./chunkinterface')
  , util   = require('util')

module.exports = KeyFrame
util.inherits(KeyFrame, ChunkInterface)

function KeyFrame(game, id) {
    ChunkInterface.call(this, game, id)
    this.isKeyFrame = true
}

KeyFrame.prototype.getNextChunkId = function() {
    return this.info.nextChunkId
}

KeyFrame.prototype.downloadUrl = function() {
    return this.game.baseUrl + 'consumer/getKeyFrame/' + this.game.region + '/' + this.game.id + '/' + this.id + '/token'
}


text:
@interface AKAssetsGroupController : UITableViewController

@end


text:
package com.google.cloud.apigeeregistry.v1.samples;

// [START apigeeregistry_v1_generated_Registry_GetApiSpecContents_Apispecname_sync]
import com.google.api.HttpBody;
import com.google.cloud.apigeeregistry.v1.ApiSpecName;
import com.google.cloud.apigeeregistry.v1.RegistryClient;

public class SyncGetApiSpecContentsApispecname {

  public static void main(String[] args) throws Exception {
    syncGetApiSpecContentsApispecname();
  }

  public static void syncGetApiSpecContentsApispecname() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (RegistryClient registryClient = RegistryClient.create()) {
      ApiSpecName name = ApiSpecName.of("[PROJECT]", "[LOCATION]", "[API]", "[VERSION]", "[SPEC]");
      HttpBody response = registryClient.getApiSpecContents(name);
    }
  }
}
// [END apigeeregistry_v1_generated_Registry_GetApiSpecContents_Apispecname_sync]


text:
package org.ovirt.engine.core.bll;

import java.util.ArrayList;
import java.util.List;

import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.common.action.PermissionsOperationsParametes;
import org.ovirt.engine.core.common.businessentities.DbUser;
import org.ovirt.engine.core.common.businessentities.ad_groups;
import org.ovirt.engine.core.common.businessentities.permissions;
import org.ovirt.engine.core.common.businessentities.Role;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.CustomLogField;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.CustomLogFields;

@CustomLogFields({ @CustomLogField("RoleName"), @CustomLogField("VdcObjectType"), @CustomLogField("VdcObjectName"),
        @CustomLogField("SubjectName") })
public abstract class PermissionsCommandBase<T extends PermissionsOperationsParametes> extends CommandBase<T> {
    private static final long serialVersionUID = -2515073672998232982L;

    /**
     * Constructor for command creation when compensation is applied on startup
     *
     * @param commandId
     */
    protected PermissionsCommandBase(Guid commandId) {
        super(commandId);
    }

    public PermissionsCommandBase(T parameters) {
        super(parameters);
    }

    protected DbUser _dbUser;
    protected ad_groups _adGroup;

    /**
     * Get the object translated type (e.g Host , VM), on which the MLA operation has been executed on.
     *
     * @see VdcObjectType
     * @return Translated object type.
     */
    public String getVdcObjectType() {
        return getParameters().getPermission().getObjectType().getVdcObjectTranslation();
    }

    /**
     * Get the object name, which the MLA operation occurs on. If no entity found, returns null.
     *
     * @return Object name.
     */
    public String getVdcObjectName() {
        permissions perms = getParameters().getPermission();
        return getDbFacade().getEntityNameByIdAndType(perms.getObjectId(), perms.getObjectType());
    }

    public String getRoleName() {
        Role role = getRoleDao().get(getParameters().getPermission().getrole_id());
        return role == null ? null : role.getname();
    }

    public String getSubjectName() {
        // we may have to load user/group from db first.
        // it would be nice to handle this from command execution rather than
        // audit log messages
        initUserAndGroupData();
        return _dbUser == null ? (_adGroup == null ? "" : _adGroup.getname()) : _dbUser.getusername();
    }

    public void initUserAndGroupData() {
        if (_dbUser == null) {
            _dbUser = getDbUserDAO().get(getParameters().getPermission().getad_element_id());
        }
        if (_adGroup == null) {
            _adGroup = getAdGroupDAO().get(getParameters().getPermission().getad_element_id());
        }
    }

    protected boolean isSystemSuperUser() {
        permissions superUserPermission =
                getPermissionDAO()
                        .getForRoleAndAdElementAndObjectWithGroupCheck(
                                PredefinedRoles.SUPER_USER.getId(),
                                getCurrentUser().getUserId(),
                                MultiLevelAdministrationHandler.SYSTEM_OBJECT_ID);
        return superUserPermission != null;
    }

    // TODO - this code is shared with addPermissionCommand - check if
    // addPermission can extend this command
    @Override
    public List<PermissionSubject> getPermissionCheckSubjects() {
        List<PermissionSubject> permissionList = new ArrayList<PermissionSubject>();
        permissions permission = getParameters().getPermission();
        permissionList.add(new PermissionSubject(permission.getObjectId(),
                permission.getObjectType(),
                getActionType().getActionGroup()));
        return permissionList;
    }
}


text:
/*
 * error-common.h
 *
 *  Created on: Oct 31, 2014
 *      Author: ed
 * (c) 2015, Framez Inc
 */
#ifndef ERROR_COMMON_H_
#define ERROR_COMMON_H_

#include "nan.h"
#include <string.h>
#include <stdlib.h>

#include <v8.h>

#include <errno.h>
#if !defined(_MSC_VER)
#include <unistd.h>
#endif
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>

// https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
#define xstr(s) str(s)
#define str(s) #s

// concept from node.js src/node_constants.cc
//#define _ERRCMN_DEFINE_CONSTANT(target, constant)
//  (target)->Set(v8::String::NewSymbol(#constant),
//                v8::Number::New(constant),
//                static_cast<v8::PropertyAttribute>(
//                    v8::ReadOnly|v8::DontDelete))

#define _ERRCMN_DEFINE_CONSTANT(target, constant)                         \
  Nan::ForceSet(target,Nan::New(#constant).ToLocalChecked(),               \
                Nan::New((uint32_t)constant),                                \
                static_cast<v8::PropertyAttribute>(                       \
                    v8::ReadOnly|v8::DontDelete))

//// our mode - this is the same thing, with a reverse lookup key also
//#define _ERRCMN_DEFINE_CONSTANT_WREV(target, constant)
//  (target)->Set(v8::String::NewSymbol(#constant),
//                v8::Number::New(constant),
//                static_cast<v8::PropertyAttribute>(
//                    v8::ReadOnly|v8::DontDelete));
//  (target)->Set(v8::String::New( xstr(constant) ),
//                v8::String::New(#constant),
//                static_cast<v8::PropertyAttribute>(
//                    v8::ReadOnly|v8::DontDelete));

#define _ERRCMN_DEFINE_CONSTANT_WREV(target, constant)                    \
  Nan::ForceSet(target,Nan::New(#constant).ToLocalChecked(),                 \
                Nan::New((uint32_t)constant),                                \
                static_cast<v8::PropertyAttribute>(                       \
                    v8::ReadOnly|v8::DontDelete));                        \
  Nan::ForceSet(target, Nan::New( xstr(constant) ).ToLocalChecked(),        \
                Nan::New(#constant).ToLocalChecked(),                         \
                static_cast<v8::PropertyAttribute>(                       \
                    v8::ReadOnly|v8::DontDelete));                        \

// custom error codes should be above this value
#define _ERRCMN_CUSTOM_ERROR_CUTOFF  4000

#define GREASE_UNKNOWN_FAILURE 4001
#define GREASE_UNKNOWN_TTY 4002
#define GREASE_UNKNOWN_NO_PATH 4003

namespace _errcmn {

	void DefineConstants(v8::Handle<v8::Object> target);

	char *get_error_str(int _errno);
	void free_error_str(char *b);
	v8::Local<v8::Value> errno_to_JS(int _errno, const char *prefix = NULL);
	v8::Local<v8::Value> errno_to_JSError(int _errno, const char *prefix = NULL);
	struct err_ev {
		char *errstr;
		int _errno;
		err_ev(void) : errstr(NULL), _errno(0) {};
		void setError(int e,const char *m=NULL);
		err_ev(int e) : err_ev() {
			setError(e);
		}
		err_ev(const err_ev &o) = delete;
		inline err_ev &operator=(const err_ev &o) = delete;
		inline err_ev &operator=(err_ev &&o) {
			this->errstr = o.errstr;  // transfer string to other guy...
			this->_errno = o._errno;
			o.errstr = NULL; o._errno = 0;
			return *this;
		}
		inline void clear() {
			if(errstr) ::free(errstr); errstr = NULL;
			_errno = 0;
		}
		~err_ev() {
			if(errstr) ::free(errstr);
		}
		bool hasErr() { return (_errno != 0); }
	};
	v8::Handle<v8::Value> err_ev_to_JS(err_ev &e, const char *prefix);
}

#ifndef NO_ERROR_CMN_OUTPUT  // if define this, you must define these below yourself

// ensure we get the XSI compliant strerror_r():
// see: http://man7.org/linux/man-pages/man3/strerror.3.html

#ifdef __cplusplus
extern "C" {
#endif
extern int __xpg_strerror_r (int __errnum, char *__buf, size_t __buflen);
#ifdef __cplusplus
};
#endif

#define ERR_STRERROR_R(ernum,b,len) __xpg_strerror_r(ernum, b, len)

#ifdef ERRCMN_DEBUG_BUILD
#pragma message "Build is Debug"
// confused? here: https://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html
#define ERROR_OUT(s,...) fprintf(stderr, "**ERROR** " s "\n", ##__VA_ARGS__ )
//#define ERROR_PERROR(s,...) fprintf(stderr, "*****ERROR***** " s, ##__VA_ARGS__ );
#define ERROR_PERROR(s,E,...) { char *__S=_errcmn::get_error_str(E); fprintf(stderr, "**ERROR** [ %s ] " s "\n", __S, ##__VA_ARGS__ ); _errcmn::free_error_str(__S); }

#define DBG_OUT(s,...) fprintf(stderr, "**DEBUG** " s "\n", ##__VA_ARGS__ )
#define IF_DBG( x ) { x }
#else
#define ERROR_OUT(s,...) fprintf(stderr, "**ERROR** " s, ##__VA_ARGS__ )//#define ERROR_PERROR(s,...) fprintf(stderr, "*****ERROR***** " s, ##__VA_ARGS__ );
#define ERROR_PERROR(s,E,...) { char *__S=_errcmn::get_error_str(E); fprintf(stderr, "**ERROR** [ %s ] " s, __S, ##__VA_ARGS__ ); _errcmn::free_error_str(__S); }
#define DBG_OUT(s,...) {}
#define IF_DBG( x ) {}
#endif

#else

#define ERROR_OUT(s,...) {} //#define ERROR_PERROR(s,...) fprintf(stderr, "*****ERROR***** " s, ##__VA_ARGS__ );
#define ERROR_PERROR(s,E,...) {}
#define DBG_OUT(s,...) {}
#define IF_DBG( x ) {}

#endif // NO_ERROR_CMN_OUTPUT

#endif /* ERROR_COMMON_H_ */


text:
package stainless
package termination

import scala.collection.mutable.{Map => MutableMap, ListBuffer => MutableList}

trait TerminationChecker { self =>
  val program: Program { val trees: Trees }
  val context: inox.Context

  import program.trees._
  import program.symbols.{given, _}

  def terminates(fd: FunDef): TerminationGuarantee

  /* Caches for inductive lemmas */
  type Postconditions  = MutableMap[Identifier, Lambda]
  type Applications    = MutableMap[(Identifier, Identifier, Identifier), Seq[ValDef] => Expr]
  type InductiveLemmas = Option[(Postconditions, Applications)]
  /* End caches for inductive lemmas */

  sealed abstract class TerminationGuarantee {
    def isGuaranteed: Boolean
  }

  case class Terminates(reason: String, measure: Option[Expr], lemmas: InductiveLemmas) extends TerminationGuarantee {
    override def isGuaranteed: Boolean = true
  }

  sealed abstract class NonTerminating extends TerminationGuarantee {
    override def isGuaranteed: Boolean = false

    def asString(using PrinterOptions): String = this match {
      case NotWellFormed(sorts) =>
        s"ADTs ${sorts.map(_.id.asString).mkString(", ")} are ill-formed"
      case LoopsGivenInputs(fi) =>
        if (fi.args.nonEmpty) {
          val max = fi.tfd.params.map(_.asString.length).max
          val model = for ((vd, e) <- fi.tfd.params zip fi.args) yield {
            ("%-" + max + "s -> %s").format(vd.asString, e.asString)
          }
          s"Function ${fi.id.asString} loops given inputs:\n${model.mkString("\n")}"
        } else {
          s"Function ${fi.id.asString} loops when called"
        }
      case MaybeLoopsGivenInputs(fi) =>
        if (fi.args.nonEmpty) {
          val max = fi.tfd.params.map(_.asString.length).max
          val model = for ((vd, e) <- fi.tfd.params zip fi.args) yield {
            ("%-" + max + "s -> %s").format(vd.asString, e.asString)
          }
          s"Function ${fi.id.asString} maybe loops given inputs:\n${model.mkString("\n")}"
        } else {
          s"Function ${fi.id.asString} maybe loops when called"
        }
      case CallsNonTerminating(calls) =>
        s"Calls non-terminating functions ${calls.map(_.id.asString).mkString(", ")}"
      case DecreasesFailed(fd) =>
        s"Decreases check failed for ${fd.id.asString}"
    }
  }

  case class NotWellFormed(sorts: Set[ADTSort]) extends NonTerminating
  case class LoopsGivenInputs(fi: FunctionInvocation) extends NonTerminating
  case class MaybeLoopsGivenInputs(fi: FunctionInvocation) extends NonTerminating
  case class CallsNonTerminating(calls: Set[FunDef]) extends NonTerminating
  case class DecreasesFailed(fd: FunDef) extends NonTerminating

  case object NoGuarantee extends TerminationGuarantee {
    override def isGuaranteed: Boolean = false
  }

  object measureCache {
    private val cache: MutableMap[FunDef, Expr] = MutableMap.empty

    def add(p: (FunDef, Expr)) = cache += p
    def get = cache
  }

  val integerOrdering: StructuralSize with SolverProvider {
    val checker: self.type
  }

  val lexicographicOrdering: StructuralSize with SolverProvider {
    val checker: self.type
  }

  val bvOrdering: StructuralSize with SolverProvider {
    val checker: self.type
  }

  def get = {
    integerOrdering.functions ++
    lexicographicOrdering.functions ++
    bvOrdering.functions
  }
}

object TerminationChecker {

  def apply(p: Program { val trees: Trees }, ctx: inox.Context)(sze: SizeFunctions { val trees: p.trees.type })
      : TerminationChecker { val program: p.type } = {

    class EncoderImpl(override val s: p.trees.type, override val t: stainless.trees.type)
      extends inox.transformers.TreeTransformer {
      override def transform(e: s.Expr): t.Expr = e match {
        case s.Decreases(measure, body) => transform(body)
        case _                          => super.transform(e)
      }
    }

    val encoderImpl = new EncoderImpl(p.trees, stainless.trees)

    class ProcessingPipelineImpl(override val program: p.type, override val context: inox.Context) extends ProcessingPipeline {
      self =>

      class CFAImpl(override val program: self.program.type)
        extends CICFA(program, self.context)
      val cfa = new CFAImpl(self.program)

      class IntegerOrderingImpl(override val checker: self.type, override val sizes: sze.type,
                                override val cfa: self.cfa.type, override val encoder: encoderImpl.type)
        extends SumOrdering with StructuralSize with Strengthener with RelationBuilder with ChainBuilder
      // We explicitly widen integerOrdering because scalac seems to ignore some of the mixed traits if we don't do so.
      val integerOrdering: SumOrdering with StructuralSize with Strengthener with RelationBuilder with ChainBuilder {
        val checker: self.type
      } = new IntegerOrderingImpl(self, sze, self.cfa, encoderImpl)

      class LexicographicOrderingImpl(override val checker: self.type, override val sizes: sze.type,
                                      override val cfa: self.cfa.type, override val encoder: encoderImpl.type)
        extends LexicographicOrdering with StructuralSize with Strengthener with RelationBuilder
      // Ditto
      val lexicographicOrdering: LexicographicOrdering with StructuralSize with Strengthener with RelationBuilder {
        val checker: self.type
      } = new LexicographicOrderingImpl(self, sze, self.cfa, encoderImpl)

      class BVOrderingImpl(override val checker: self.type, override val sizes: sze.type,
                           override val cfa: self.cfa.type, override val encoder: encoderImpl.type)
        extends BVOrdering with StructuralSize with Strengthener with RelationBuilder
      // Ditto
      val bvOrdering: BVOrdering with StructuralSize with Strengthener with RelationBuilder {
        val checker: self.type
      } = new BVOrderingImpl(self, sze, self.cfa, encoderImpl)

      class RecursionProcessorImpl(override val checker: self.type,
                                   override val ordering: integerOrdering.type)
        extends RecursionProcessor(checker, ordering)
      val recursionProcessor = new RecursionProcessorImpl(self, integerOrdering)

      class DecreasesProcessorImpl(override val checker: self.type, override val ordering: integerOrdering.type)
        extends DecreasesProcessor(checker, ordering)
      val decreasesProcessor = new DecreasesProcessorImpl(self, integerOrdering)

      class SelfCallsProcessorImpl(override val checker: self.type)
        extends SelfCallsProcessor(checker)
      val selfCallsProcessor = new SelfCallsProcessorImpl(self)

      class IntegerProcessorImpl(override val checker: self.type, override val ordering: integerOrdering.type)
        extends RelationProcessor(checker, ordering)
      val integerProcessor = new IntegerProcessorImpl(self, integerOrdering)

      class LexicographicProcessorImpl(override val checker: self.type, override val ordering: lexicographicOrdering.type)
        extends RelationProcessor(checker, ordering)
      val lexicographicProcessor = new LexicographicProcessorImpl(self, lexicographicOrdering)

      class BVProcessorImpl(override val checker: self.type, override val ordering: bvOrdering.type)
        extends RelationProcessor(checker, ordering)
      val bvProcessor = new BVProcessorImpl(self, bvOrdering)

      class ChainProcessorImpl(override val checker: self.type, override val ordering: integerOrdering.type)
        extends ChainProcessor(checker, ordering)
      val chainProcessor = new ChainProcessorImpl(self, integerOrdering)

      class LoopProcessorImpl(override val checker: self.type, override val ordering: integerOrdering.type)
        extends LoopProcessor(checker, ordering)
      val loopProcessor = new LoopProcessorImpl(self, integerOrdering)

      val processors = {
        List(
          recursionProcessor,
          selfCallsProcessor,
          decreasesProcessor,
          integerProcessor,
          lexicographicProcessor,
          bvProcessor,
          chainProcessor,
          loopProcessor,
        )
      }
    }
    new ProcessingPipelineImpl(p, ctx)
  }
}


text:
var nunjucksEscapedInclude = require("./nunjucks/escaped-include-tag"),
  nunjucksRender = require("gulp-nunjucks-render"),
  nunjucksGulp = {};

function environmentManager(env) {
  nunjucksEscapedInclude.register(env);
}

function pipe(config) {
  config = config || {};
  return nunjucksRender({
    manageEnv: environmentManager,
    path: config.templateDir,
  });
}

module.exports = pipe;


text:
<?php
function sgPopupMediaButton()
{
	global $pagenow, $typenow;

	$showCurrentUser = SGFunctions::isShowMenuForCurrentUser();
	if(!$showCurrentUser) {return;}
	$buttonTitle = 'Insert popup';
	$output = '';

	$pages = array(
		'post.php',
		'page.php',
		'post-new.php',
		'post-edit.php',
		'widgets.php'
	);

	/* For show in plugins page when package is pro */
	if(POPUP_BUILDER_PKG !== POPUP_BUILDER_PKG_FREE) {
		array_push($pages, "admin.php");
	}

	$checkPage = in_array(
		$pagenow,
		$pages
	);

	if ($checkPage && $typenow != 'download') {

		wp_enqueue_script('jquery-ui-dialog');
		wp_register_style('sg_jQuery_ui', SG_APP_POPUP_URL . "/style/jQueryDialog/jquery-ui.css");
		wp_enqueue_style('sg_jQuery_ui');
		$img = '';
		$output = ''. $img.$buttonTitle.'';
	}
	echo $output;
}

add_action('media_buttons', 'sgPopupMediaButton', 11);

function sgPopupMediaButtonThickboxs()
{
	global $pagenow, $typenow;
	$currentPageParams = get_object_vars(get_current_screen());

	$showCurrentUser = SGFunctions::isShowMenuForCurrentUser();
	if(!$showCurrentUser) {return;}

	$pages = array(
		'post.php',
		'page.php',
		'post-new.php',
		'post-edit.php',
		'widgets.php'
	);

	if(POPUP_BUILDER_PKG !== POPUP_BUILDER_PKG_FREE) {
		array_push($pages, "admin.php");
	}

	$checkPage = in_array(
		$pagenow,
		$pages
	);

	if ($checkPage && $typenow != 'download') : ?>

Insert the shortcode for showing a Popup.

						Select Popup
						<select id="sg-insert-popup-id" style="margin-bottom: 5px;">
							<option value="">Please select...</option>
							<?php
								global $wpdb;
								$proposedTypes = array();
								$orderBy = 'id DESC';
								$allPopups = SGPopup::findAll($orderBy);
								foreach ($allPopups as $popup) :
									if((isset($_GET['id']) && $popup->getId() == (int)@$_GET['id'] || $popup->getType() == 'exitIntent') && $currentPageParams['id'] == 'popup-builder_page_edit-popup') {
										continue;
									}
								?>
									<option value="<?php echo $popup->getId()?>"><?php echo $popup->getTitle();?><?php echo " - ".$popup->getType();?></option>;
								<?php endforeach; ?>
						</select>

					<?php /* Becouse in popup content must be have only click */
					   		if($pagenow !== 'admin.php'): ?>

						Select Event
						<select id="openEvent">
							<option value="onload">On load</option>
							<option value="click">Click</option>
							<option value="hover">Hover</option>
						</select>

				<?php endif;?>

					<input type="button" id="sg-ptp-popup-insert" class="button-primary dashicons-welcome-widgets-menus" value="Insert"/>
					Cancel

	<?php endif;
}

add_action('admin_footer', 'sgPopupMediaButtonThickboxs');


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TriplesOfLetters
{
    class Program
    {
        static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());
            for (int num = 0; num < n; num++)
                for (int num1 = 0; num1 < n; num1++)
                    for (int num2 = 0; num2 < n; num2++)
                    {
                        char letter = (char)('a' + num);
                        char letter1 = (char)('a' + num1);
                        char letter2 = (char)('a' + num2);
                        Console.WriteLine("{0}{1}{2}", letter, letter1, letter2);
                    }
        }
    }
}


text:
"""
.. See the NOTICE file distributed with this work for additional information
   regarding copyright ownership.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
"""

from __future__ import print_function

import os
import sys

from utils import logger

try:
    if hasattr(sys, '_run_from_cmdl') is True:
        raise ImportError
    from pycompss.api.parameter import FILE_IN, FILE_OUT, IN, OUT
    from pycompss.api.task import task
    # from pycompss.api.api import compss_wait_on
except ImportError:
    logger.warn("[Warning] Cannot import \"pycompss\" API packages.")
    logger.warn("          Using mock decorators.")

    from utils.dummy_pycompss import FILE_IN, FILE_OUT, IN, OUT  # pylint: disable=ungrouped-imports
    from utils.dummy_pycompss import task  # pylint: disable=ungrouped-imports
    # from utils.dummy_pycompss import compss_wait_on  # pylint: disable=ungrouped-imports

from basic_modules.tool import Tool
from basic_modules.metadata import Metadata

from tool.fastqreader import fastqreader
from tool.common import common

# ------------------------------------------------------------------------------

class fastq_splitter(Tool):  # pylint: disable=invalid-name
    """
    Script for splitting up FASTQ files into manageable chunks
    """

    def __init__(self, configuration=None):
        """
        Initialise the tool with its configuration.

        Parameters
        ----------
        configuration : dict
            a dictionary containing parameters that define how the operation
            should be carried out, which are specific to each Tool.
        """
        logger.info("FASTQ Splitter")
        Tool.__init__(self)

        if configuration is None:
            configuration = {}

        self.configuration.update(configuration)

    @task(
        in_file1=FILE_IN, tag=IN,
        out_file=FILE_OUT, files_out=OUT,
        returns=list)
    def single_splitter(self, in_file1, out_file, tag='tmp'):  # pylint: disable=no-self-use
        """
        Function to divide the FastQ files into separate sub files of 1000000
        sequences so that the aligner can run in parallel.

        Parameters
        ----------
        in_file1 : str
            Location of first FASTQ file
        tag : str
            DEFAULT = tmp
            Tag used to identify the files. Useful if this is getting run
            manually on a single machine multiple times to prevent collisions of
            file names

        Returns
        -------
        Returns: Returns a list of the files that have been generated.
                 Each sub list containing the two paired end files for that
                 subset.
        paired_files : list
            List of lists of pair end files. Each sub list containing the two
            paired end files for that subset.
        """

        fqr = fastqreader()
        fqr.openFastQ(in_file1)
        file_loc_1_tmp = fqr.createOutputFiles(tag)

        fastq_chunk_size = 1000000
        if "fastq_chunk_size" in self.configuration:
            fastq_chunk_size = self.configuration["fastq_chunk_size"]

        record1 = fqr.next(1)

        count_r3 = 0

        tmp_dir = os.path.split(file_loc_1_tmp)[0]

        files_out = [[os.path.split(file_loc_1_tmp)[1]]]

        while fqr.eof(1) is False:
            fqr.writeOutput(record1, 1)
            record1 = fqr.next(1)
            count_r3 += 1

            if count_r3 % fastq_chunk_size == 0:
                file_loc_1_new = fqr.incrementOutputFiles()
                files_out.append([os.path.split(file_loc_1_new)[1]])

        fqr.closeFastQ()
        fqr.closeOutputFiles()

        untar_idx = True
        if "no-untar" in self.configuration and self.configuration["no-untar"] is True:
            untar_idx = False

        if untar_idx is True:
            if os.path.isfile(out_file):
                os.remove(out_file)

            output_file_pregz = out_file.replace('.tar.gz', '.tar')
            common.tar_folder(tmp_dir, output_file_pregz)
            common.zip_file(output_file_pregz, 2)

        return files_out

    @task(
        in_file1=FILE_IN, in_file2=FILE_IN, tag=IN,
        out_file=FILE_OUT, files_out=OUT,
        returns=list)
    def paired_splitter(self, in_file1, in_file2, out_file, tag='tmp'):  # pylint: disable=no-self-use,too-many-locals,too-many-statements
        """
        Function to divide the paired-end FastQ files into separte sub files
        of 1000000 sequences so that the aligner can run in parallel.

        Parameters
        ----------
        in_file1 : str
            Location of first paired end FASTQ file
        in_file2 : str
            Location of second paired end FASTQ file
        tag : str
            DEFAULT = tmp
            Tag used to identify the files. Useful if this is getting run
            manually on a single machine multiple times to prevent collisions of
            file names

        Returns
        -------
        Returns: Returns a list of lists of the files that have been generated.
                 Each sub list containing the two paired end files for that
                 subset.
        paired_files : list
            List of lists of pair end files. Each sub list containing the two
            paired end files for that subset.
        """

        fqr = fastqreader()
        fqr.openFastQ(in_file1, in_file2)
        file_loc_1_tmp, file_loc_2_tmp = fqr.createOutputFiles(tag)

        fastq_chunk_size = 1000000
        if "fastq_chunk_size" in self.configuration:
            fastq_chunk_size = self.configuration["fastq_chunk_size"]

        record1 = fqr.next(1)
        record2 = fqr.next(2)

        count_r1 = 0
        count_r2 = 0
        count_r3 = 0

        tmp_dir = os.path.split(file_loc_1_tmp)[0]

        files_out = [[
            os.path.split(file_loc_1_tmp)[1],
            os.path.split(file_loc_2_tmp)[1]
        ]]

        while fqr.eof(1) is False and fqr.eof(2) is False:
            r1_id = record1["id"].split(" ")
            r2_id = record2["id"].split(" ")

            if r1_id[0] == r2_id[0]:
                fqr.writeOutput(record1, 1)
                fqr.writeOutput(record2, 2)

                record1 = fqr.next(1)
                record2 = fqr.next(2)

                count_r1 += 1
                count_r2 += 1
                count_r3 += 1
            elif r1_id[0] < r2_id[0]:
                record1 = fqr.next(1)
                count_r1 += 1
            else:
                record2 = fqr.next(2)
                count_r2 += 1

            if count_r3 % fastq_chunk_size == 0:
                file_loc_1_new, file_loc_2_new = fqr.incrementOutputFiles()
                files_out.append([
                    os.path.split(file_loc_1_new)[1],
                    os.path.split(file_loc_2_new)[1]
                ])

        fqr.closeFastQ()
        fqr.closeOutputFiles()

        untar_idx = True
        if "no-untar" in self.configuration and self.configuration["no-untar"] is True:
            untar_idx = False

        if untar_idx is True:
            if os.path.isfile(out_file):
                os.remove(out_file)

            output_file_pregz = out_file.replace('.tar.gz', '.tar')
            common.tar_folder(tmp_dir, output_file_pregz)
            common.zip_file(output_file_pregz, 2)

        return files_out

    def run(self, input_files, input_metadata, output_files):
        """
        The main function to run the splitting of FASTQ files (single or
        paired) so that they can aligned in a distributed manner

        Parameters
        ----------
        input_files : dict
            List of input fastq file locations
        metadata : dict
        output_files : dict

        Returns
        -------
        output_file : str
            Location of compressed (.tar.gz) of the split FASTQ files
        output_names : list
            List of file names in the compressed file

        """

        sources = [input_files["fastq1"]]

        if "fastq2" in input_files:
            sources.append(input_files["fastq2"])
            self.paired_splitter(
                input_files["fastq1"], input_files["fastq2"],
                output_files["output"]
            )
        else:
            self.single_splitter(
                input_files["fastq1"],
                output_files["output"],
            )

        # results = compss_wait_on(results)

        fastq_tar_meta = Metadata(
            data_type=input_metadata["fastq1"].data_type,
            file_type="TAR",
            file_path=output_files["output"],
            sources=sources,
            taxon_id=input_metadata["fastq1"].taxon_id,
            meta_data={
                "tool": "fastq_splitter"
            }
        )

        return (
            {"output": output_files["output"]},
            {"output": fastq_tar_meta}
        )

# ------------------------------------------------------------------------------


text:
return {
	light_bomber              = require("shipgraphics.light_bomber"),
	closed_orbital_defense_station = require("shipgraphics.closed_orbital_defense_station"),
	medium_fighter            = require("shipgraphics.medium_fighter"),
	colonization_ship         = require("shipgraphics.colonization_ship"),
	speeder                   = require("shipgraphics.speeder"),
	light_scout               = require("shipgraphics.light_scout"),
	orbital_defense_station   = require("shipgraphics.orbital_defense_station"),
}


text:
package com.sumzerotrading.realtime.bar;

import com.sumzerotrading.data.BarData.LengthUnit;
import com.sumzerotrading.data.Ticker;
import com.sumzerotrading.historicaldata.IHistoricalDataProvider;
import com.sumzerotrading.historicaldata.IHistoricalDataProvider.ShowProperty;
import java.util.Objects;

/**
 *
 * @author Rob Terpilowski
 */
public class RealtimeBarRequest {

    protected int requestId;
    protected Ticker ticker;
    protected int timeInterval;
    protected LengthUnit timeUnit;
    protected IHistoricalDataProvider.ShowProperty showProperty = IHistoricalDataProvider.ShowProperty.TRADES;

    public RealtimeBarRequest(int requestId, Ticker ticker, int timeInteval, LengthUnit timeUnit) {
        this.requestId = requestId;
        this.ticker = ticker;
        this.timeInterval = timeInteval;
        this.timeUnit = timeUnit;
    }

    public RealtimeBarRequest(int requestId, Ticker ticker, int timeInterval, LengthUnit timeUnit, ShowProperty showProperty ) {
        this(requestId, ticker, timeInterval, timeUnit);
        this.showProperty = this.showProperty;
    }

    public int getRequestId() {
        return requestId;
    }

    public Ticker getTicker() {
        return ticker;
    }

    public int getTimeInterval() {
        return timeInterval;
    }

    public LengthUnit getTimeUnit() {
        return timeUnit;
    }

    public ShowProperty getShowProperty() {
        return showProperty;
    }

    public void setShowProperty(ShowProperty showProperty) {
        this.showProperty = showProperty;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 79 * hash + this.requestId;
        hash = 79 * hash + Objects.hashCode(this.ticker);
        hash = 79 * hash + this.timeInterval;
        hash = 79 * hash + Objects.hashCode(this.timeUnit);
        hash = 79 * hash + Objects.hashCode(this.showProperty);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final RealtimeBarRequest other = (RealtimeBarRequest) obj;
        if (this.requestId != other.requestId) {
            return false;
        }
        if (this.timeInterval != other.timeInterval) {
            return false;
        }
        if (!Objects.equals(this.ticker, other.ticker)) {
            return false;
        }
        if (this.timeUnit != other.timeUnit) {
            return false;
        }
        if (this.showProperty != other.showProperty) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "RealtimeBarRequest{" + "requestId=" + requestId + ", ticker=" + ticker + ", timeInteval=" + timeInterval + ", timeUnit=" + timeUnit + ", showProperty=" + showProperty + '}';
    }

}


text:
<?php

namespace Estaty\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20141229135142 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE User (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_EMAIL (email), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE User');
    }
}


text:
module Prisc {
    export class DrawingContext {
        public color: Color;
        public font: Font;
        public tool: DrawingTools;
        constructor() {
            this.color = new Color();
            this.font = new Font();
            this.tool = DrawingTools.RectTool;
        }
        updateColor(colorCode: string): boolean {
            // TODO: validate return false
            this.color.code = colorCode;
            return true;
        }
        updateTool(tool: DrawingTools): boolean {
            // TODO: validate return false
            this.tool = DrawingTools[DrawingTools[tool]];
            return true;
        }
        updateFontValue(fontValue: string): boolean {
            this.font.value = fontValue;
            return true;
        }
        updateFontSize(fontSize: string): boolean {
            // TODO: validate return false
            this.font.size = fontSize;
            return true;
        }
        updateFontFamily(fontFamily: string): boolean {
            // TODO: validate return false
            this.font.family = fontFamily;
            return true;
        }
    }
    export class Color {
        constructor(public code: string = '#000000') {}
    }
    export class Font {
        constructor(
            public value: string = '',
            public size: string = '4em',
            public family: string = 'Helvetica'
        ) {}
    }
    export enum DrawingTools {
        RectTool,
        PenTool,
        TrimTool,
        TextTool,
        LineTool,
        DropperTool
    }
}


text:
export const ALL = 'all';
export const DEFAULT = 'default';
export const MENTION = 'mention';
export const NONE = 'none';

export default {
    ALL,
    DEFAULT,
    MENTION,
    NONE,
};


text:
title: 'Ngaihsutbeh Ding'
date: 24/04/2020
---

E.G.White, "The Scriptures a Safeguard" laimai 593–602, The Great Controversysungpan simin.

Taangh upna, phutkhakthu, ngeina, ngaihsutna leh Laisiangtho cihte in Pasian'thute tungah hong huzaap mahmah hi. Zuau thudotna khatah: Hih atung ateng lakpan, i biakna sungah, koipen in huzaap neipen hiam? Laisiangtho hi i cihpah ding hi a, Khasiangtho na sepna hangin, Laisiangtho in i nuntakzia kheelsak ding hihang.

"Mihingte hotkhiatna ding a kisam bangbangin, Pasian in Laisiangtho hongpia hi. Tua Laisiangtho pen vangliatna tawh a kidim leh, a khialtheilo Pasian'deihna ahihi. I zia i tong ding hi a, upna thukhun ding leh, i phutkhakte ettel nading ahihi."—Ellen G. White, the Great Controversy, p. 9.

**Kikup ding dotnate**:

`1. Pasian'thukham khawng nuntakpih ding, lungsim khempeuhtawh Pasian it ding leh, vengte eimah bangin itding sangin, mihing taangh upna khawng nuntakpih, banghang in baihzaw hiam? (Mate 22:37– 40).`

`2. Sundayni dotna nunungpen kikum kik dihun. Taangh upna in pawlsungah bang dinmun la hiam? Biakna taangngeina sungah, thupha leh tona koi tengah kimu hiam?`

`3. Taang upna in bangzah in hoihmahleh, tuate in Pasian'kammal khengin vangliatna a neihloh na'ng bangci hih ding hiam?`

`4. Mikhat in, Topa genkholhna sang a mangman in, laisiangthothak hun a ding Sundayni in, tawlngakni mantaktak hi cih kilak leh, tua mipa thugente na bangci dawn ding a, Pasian kammal bekmah tawh kiteh ding cih na koici hilh ding hiam?`

`5. Na pawlpi ki tuiphumzia kikum dih unla: tua ngeina in naupna bangzah huzaap hiam? Taanglai pawlpi tangthu i leh-etkik ciangin, ngeina thupisaklua uh a hih manun, a lum a let suak uhhi. Tuabang khialhna i bawl khakloh na'ng, eite bang pilna hongpia naci hiam?`


text:
package comport_gui;

import java.io.IOException;
import java.io.OutputStream;

/**
 * The class for sending a byte of message through commport.
 *
 * @author Yixing Lao
 * @author Zhixin Xu
 *
 */
public class ComportSender {
  static OutputStream out;

  /**
   * Set the data Stream to be written to
   *
   * @param out
   */
  public static void setWriterStream(OutputStream out) {
    ComportSender.out = out;
  }

  /**
   * Send the byte via comport.
   *
   * @param b
   *          The byte to be sent.
   */
  public static void send(byte b) {
    try {
      System.out.println("Sending: " + ByteStrConverter.byte2str(b));
      // sending through serial port is simply writing into OutputStream
      out.write(b);
      out.flush();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}


text:
#include "ofxCvImage.h"
#include "ofxCvGrayscaleImage.h"
#include "ofxCvColorImage.h"
#include "ofxCvFloatImage.h"
#include "ofxCvBlob.h"

//--------------------------------------------------------------------------------
ofxCvImage::ofxCvImage() {
    width			= 0;
    height			= 0;
    bUseTexture		= true;
    bTextureDirty   = true;
	bAllocated		= false;
    bPixelsDirty    = true;
    bRoiPixelsDirty = true;
}

//--------------------------------------------------------------------------------
ofxCvImage::~ofxCvImage() {
    clear();
}

//--------------------------------------------------------------------------------
void ofxCvImage::allocate( int w, int h ) {
	if (bAllocated == true){
		ofLog(OF_LOG_VERBOSE, "in allocate, reallocating a ofxCvImage");
		clear();
	}

	if( w == 0 || h == 0 ){
		ofLog(OF_LOG_ERROR, "in allocate, width or height cannot be 0");
		return;
	}

	cvImage = cvCreateImage( cvSize(w,h), ipldepth, iplchannels );
	cvImageTemp	= cvCreateImage( cvSize(w,h), ipldepth, iplchannels );

	width = w;
	height = h;
	bAllocated = true;

    if( bUseTexture ) {
        tex.allocate( width, height, glchannels );
        bTextureDirty = true;
    }
}

//--------------------------------------------------------------------------------
void ofxCvImage::clear() {

	if (bAllocated == true){
		if (width > 0 && height > 0){
			cvReleaseImage( &cvImage );
			cvReleaseImage( &cvImageTemp );
		}
        pixels.clear();
        bPixelsDirty = true;
        bRoiPixelsDirty = true;

		width = 0;
		height = 0;

		if( bUseTexture ) {
			tex.clear();
            bTextureDirty = true;
		}

		bAllocated = false;
	}
}

//--------------------------------------------------------------------------------
float ofxCvImage::getWidth(){
	return width;
}

//--------------------------------------------------------------------------------
float ofxCvImage::getHeight(){
	return height;
}

//--------------------------------------------------------------------------------
void ofxCvImage::setUseTexture( bool bUse ) {
	bUseTexture = bUse;
}

//--------------------------------------------------------------------------------
ofTexture& ofxCvImage::getTextureReference() {
	return tex;
}

//--------------------------------------------------------------------------------
void ofxCvImage::flagImageChanged() {
    bTextureDirty = true;
    bPixelsDirty = true;
    bRoiPixelsDirty = true;
}

// ROI - region of interest

//--------------------------------------------------------------------------------
void ofxCvImage::setROI( int x, int y, int w, int h ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in setROI, image is not allocated");
		return;
	}
    x = (int)ofClamp(x, 0, (int)width-1);
    y = (int)ofClamp(y, 0, (int)height-1);
    w = (int)ofClamp(w, 0, (int)width - x);
    h = (int)ofClamp(h, 0, (int)height - y);

    cvSetImageROI( cvImage, cvRect(x,y, w,h) );
    cvSetImageROI( cvImageTemp, cvRect(x,y, w,h) );
    flagImageChanged();
}

//--------------------------------------------------------------------------------
void ofxCvImage::setROI( const ofRectangle& rect ) {
    setROI( (int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height );
}

//--------------------------------------------------------------------------------
ofRectangle ofxCvImage::getROI() {
    CvRect rect = cvGetImageROI(cvImage);
    return ofRectangle((float)rect.x, (float)rect.y, (float)rect.width, (float)rect.height);
}

//--------------------------------------------------------------------------------
void ofxCvImage::resetROI() {
    cvResetImageROI( cvImage );
    cvResetImageROI( cvImageTemp );
}

//--------------------------------------------------------------------------------
ofRectangle ofxCvImage::getIntersectionROI( const ofRectangle& r1, const ofRectangle& r2 ) {
    // Calculates the intersection rectangle of two overlapping rectangles.
    // The following pattern can be used to do image operation
    // on the intersection (overlapping part) of two ROIs
    //
    // ofRectangle iRoi = img1.getIntersectionROI( img1.getROI(), img2.getROI() );
    // if( iRoi.width > 0 && iRoi.height > 0 ) {
    //     img1.pushROI();
    //     img1.setROI( iRoi );
    //     img2.pushROI();
    //     img2.setROI( iRoi );
    //
    //     // do image operation here
    //
    //     img1.popROI();
    //     img2.popROI();
    // }
    //

    int r1x1 = (int)r1.x;
    int r1y1 = (int)r1.y;
    int r1x2 = (int)(r1.x+r1.width);
    int r1y2 = (int)(r1.y+r1.height);

    int r2x1 = (int)r2.x;
    int r2y1 = (int)r2.y;
    int r2x2 = (int)(r2.x+r2.width);
    int r2y2 = (int)(r2.y+r2.height);

    int r3x1 = 0;
    int r3y1 = 0;
    int r3x2 = 0;
    int r3y2 = 0;

    bool bIntersect =  ( ( ofInRange(r2x1, r1x1,r1x2) || ofInRange(r1x1, r2x1,r2x2) ) &&
                         ( ofInRange(r2y1, r1y1,r1y2) || ofInRange(r1y1, r2y1,r2y2) ) );

    if( bIntersect ){
        r3x1 = MAX( r1x1, r2x1 );
        r3y1 = MAX( r1y1, r2y1 );

        r3x2 = MIN( r1x2, r2x2 );
        r3y2 = MIN( r1y2, r2y2 );

        return ofRectangle( r3x1,r3y1, r3x2-r3x1,r3y2-r3y1 );

    } else {
        return ofRectangle( 0,0, 0,0 );
    }
}

// Set Pixel Data

//--------------------------------------------------------------------------------
void  ofxCvImage::operator = ( const IplImage* mom ) {
	if( mom->width == 0 || mom->height == 0 ){
		ofLog(OF_LOG_ERROR, "in =, mom width or height is 0");
		return;
	}

	if( mom->nChannels == cvImage->nChannels && mom->depth == cvImage->depth ){
		if( !bAllocated ){ 	//lets allocate if needed
			allocate(mom->width, mom->height);
		}else if( mom->width != width || mom->height != height ){
            ofLog(OF_LOG_ERROR, "in =, width / height mismatch");
			return;
		}
		cvCopy( mom, cvImage );
        flagImageChanged();
	} else {
        ofLog(OF_LOG_ERROR, "in =, images need to match in channels, and depth");
	}
}

//--------------------------------------------------------------------------------
void ofxCvImage::operator -= ( float value ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in -=, need to allocate image first");
		return;
	}
	cvSubS( cvImage, cvScalar(value), cvImageTemp );
	swapTemp();
    flagImageChanged();
}

//--------------------------------------------------------------------------------
void ofxCvImage::operator += ( float value ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in -=, need to allocate image first");
		return;
	}
	cvAddS( cvImage, cvScalar(value), cvImageTemp );
	swapTemp();
    flagImageChanged();
}

//--------------------------------------------------------------------------------
void ofxCvImage::operator -= ( ofxCvImage& mom ) {
	if( !mom.bAllocated ){
		ofLog(OF_LOG_ERROR, "in -=, mom needs to be allocated");
		return;
	}
	if( !bAllocated ){
		ofLog(OF_LOG_NOTICE, "in -=, allocating to match dimensions");
		allocate(mom.getWidth(), mom.getHeight());
	}

	if( mom.getCvImage()->nChannels == cvImage->nChannels &&
        mom.getCvImage()->depth == cvImage->depth )
    {
        if( matchingROI(getROI(), mom.getROI()) ) {
            cvSub( cvImage, mom.getCvImage(), cvImageTemp );
            swapTemp();
            flagImageChanged();
        } else {
            ofLog(OF_LOG_ERROR, "in -=, ROI mismatch");
        }
	} else {
        ofLog(OF_LOG_ERROR, "in -=, images need to have matching type");
	}
}

//--------------------------------------------------------------------------------
void ofxCvImage::operator += ( ofxCvImage& mom ) {
	if( !mom.bAllocated ){
		ofLog(OF_LOG_ERROR, "in +=, mom needs to be allocated");
		return;
	}
	if( !bAllocated ){
		ofLog(OF_LOG_NOTICE, "in +=, allocating to match dimensions");
		allocate(mom.getWidth(), mom.getHeight());
	}

	if( mom.getCvImage()->nChannels == cvImage->nChannels &&
        mom.getCvImage()->depth == cvImage->depth )
    {
        if( matchingROI(getROI(), mom.getROI()) ) {
            cvAdd( cvImage, mom.getCvImage(), cvImageTemp );
            swapTemp();
            flagImageChanged();
        } else {
            ofLog(OF_LOG_ERROR, "in +=, ROI mismatch");
        }
	} else {
        ofLog(OF_LOG_ERROR, "in +=, images need to have matching type");
	}
}

//--------------------------------------------------------------------------------
void ofxCvImage::operator *= ( ofxCvImage& mom ) {
	if( !mom.bAllocated ){
		ofLog(OF_LOG_ERROR, "in *=, mom needs to be allocated");
		return;
	}
	if( !bAllocated ){
		ofLog(OF_LOG_NOTICE, "in *=, allocating to match dimensions");
		allocate(mom.getWidth(), mom.getHeight());
	}

	if( mom.getCvImage()->nChannels == cvImage->nChannels &&
        mom.getCvImage()->depth == cvImage->depth )
    {
        if( matchingROI(getROI(), mom.getROI()) ) {
            float scalef = 1.0f / 255.0f;
            cvMul( cvImage, mom.getCvImage(), cvImageTemp, scalef );
            swapTemp();
            flagImageChanged();
        } else {
            ofLog(OF_LOG_ERROR, "in *=, ROI mismatch");
        }
	} else {
        ofLog(OF_LOG_ERROR, "in *=, images need to have matching type");
	}
}

//--------------------------------------------------------------------------------
void ofxCvImage::operator &= ( ofxCvImage& mom ) {
	if( !mom.bAllocated ){
		ofLog(OF_LOG_ERROR, "in &=, mom needs to be allocated");
		return;
	}
	if( !bAllocated ){
		ofLog(OF_LOG_NOTICE, "in &=, allocating to match dimensions");
		allocate(mom.getWidth(), mom.getHeight());
	}

	if( mom.getCvImage()->nChannels == cvImage->nChannels &&
        mom.getCvImage()->depth == cvImage->depth )
    {
        if( matchingROI(getROI(), mom.getROI()) ) {
            cvAnd( cvImage, mom.getCvImage(), cvImageTemp );
            swapTemp();
            flagImageChanged();
        } else {
            ofLog(OF_LOG_ERROR, "in &=, ROI mismatch");
        }
	} else {
        ofLog(OF_LOG_ERROR, "in &=, images need to have matching type");
	}
}

//--------------------------------------------------------------------------------
void  ofxCvImage::drawBlobIntoMe( ofxCvBlob& blob, int color ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in drawBlobIntoMe, need to allocate image first");
		return;
	}
	if( blob.pts.size() > 0 ) {
	   CvPoint* pts = new CvPoint[blob.nPts];
	   for( int i=0; i < blob.nPts ; i++ ) {
		   pts[i].x = (int)blob.pts[i].x;
		   pts[i].y = (int)blob.pts[i].y;
	   }
	   int nPts = blob.nPts;
	   cvFillPoly( cvImage, &pts, &nPts, 1,
				   CV_RGB(color,color,color) );
	   delete pts;
	}
}

// Draw Image

//--------------------------------------------------------------------------------
void ofxCvImage::draw( float x, float y ) {
    draw( x,y, width, height );
}

//----------------------------------------------------------
void ofxCvImage::draw(const ofPoint & point){
	draw(point.x, point.y);
}

//----------------------------------------------------------
void ofxCvImage::draw(const ofRectangle & rect){
	draw(rect.x, rect.y, rect.width, rect.height);
}

//--------------------------------------------------------------------------------
void ofxCvImage::updateTexture(){
	if(!bAllocated) {
		ofLog(OF_LOG_WARNING, "in updateTexture, image is not allocated");
	} else if(bUseTexture ) {
		if( bTextureDirty ) {
			if(tex.getWidth() != width || tex.getHeight() != height) {
				//ROI was changed
				// reallocating texture - this could be faster with ROI support
				tex.clear();
				tex.allocate( width, height, glchannels );
			}
			tex.loadData( getPixelsRef() );
			bTextureDirty = false;
		}
	}
}

//--------------------------------------------------------------------------------
void ofxCvImage::draw( float x, float y, float w, float h ) {
    if( bUseTexture ) {
    	updateTexture();
        tex.draw(x,y, w,h);
    } else {
        #ifdef TARGET_OPENGLES
            ofLog(OF_LOG_ERROR, "texture-less drawing not supported in OpenGL ES");
        #else
            // this is slower than the typical draw method based on textures
            // but useful when dealing with threads GL textures often don't work
            ofLog(OF_LOG_NOTICE, "in draw, using slow texture-less drawing");
            ofLog(OF_LOG_NOTICE, "texture-less drawing - be aware, unlike texture drawing, \
                              this always draws window aligned, rotation not supported");

            if( x == 0) {
                x += 0.01;
                ofLog(OF_LOG_NOTICE, "BUG: can't draw at x==0 in texture-less mode.");
            }

            if(bAnchorIsPct){
                x -= anchor.x * w;
                y -= anchor.y * h;
            }else{
                x -= anchor.x;
                y -= anchor.y;
            }

            glRasterPos2f( x, y+h );

            IplImage* tempImg;
            tempImg = cvCreateImage( cvSize((int)w, (int)h), ipldepth, iplchannels );
            cvResize( cvImage, tempImg, CV_INTER_NN );
            cvFlip( tempImg, tempImg, 0 );
            glDrawPixels( tempImg->width, tempImg->height ,
                          glchannels, gldepth, tempImg->imageData );
            cvReleaseImage( &tempImg );
        #endif
    }
}

//--------------------------------------------------------------------------------
void ofxCvImage::drawROI( float x, float y ) {
    ofRectangle roi = getROI();
    drawROI( x,y, roi.width, roi.height );
}

//--------------------------------------------------------------------------------
void ofxCvImage::drawROI( float x, float y, float w, float h ) {
    if( bUseTexture ) {
        ofRectangle roi = getROI();
        if( bTextureDirty ) {
            if(tex.getWidth() != roi.width || tex.getHeight() != roi.height) {
                //ROI was changed
                // reallocating texture - this could be faster with ROI support
                tex.clear();
                tex.allocate( (int)roi.width, (int)roi.height, glchannels );
            }
            tex.loadData( getRoiPixelsRef() );
            bTextureDirty = false;
        }

        tex.draw(x,y, w,h);

    } else {
        ofLog(OF_LOG_ERROR, "texture-less drawing not implemented for drawROI");
    }
}

//--------------------------------------------------------------------------------
void ofxCvImage::setAnchorPercent( float xPct, float yPct ){
    if( bUseTexture ) {
    	tex.setAnchorPercent(xPct,yPct);
    } else {
        anchor.x = xPct;
        anchor.y = yPct;

        bAnchorIsPct = true;
    }
}

//--------------------------------------------------------------------------------
void ofxCvImage::setAnchorPoint( float x, float y ){
    if( bUseTexture ) {
    	tex.setAnchorPoint(x,y);
    }else{
        anchor.x = x;
        anchor.y = y;

        bAnchorIsPct = false;
    }
}

//--------------------------------------------------------------------------------
void ofxCvImage::resetAnchor(){
    if( bUseTexture ) {
    	tex.resetAnchor();
    }else{
        anchor.set(0,0);
        bAnchorIsPct = false;
    }
}

// Image Filter Operations
//--------------------------------------------------------------------------------
void ofxCvImage::dilate() {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in dilate, need to allocate image first");
		return;
	}
	cvDilate( cvImage, cvImageTemp, 0, 1 );
	swapTemp();
    flagImageChanged();
}

//--------------------------------------------------------------------------------
void ofxCvImage::erode() {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in erode, need to allocate image first");
		return;
	}
	cvErode( cvImage, cvImageTemp, 0, 1 );
	swapTemp();
    flagImageChanged();
}

//--------------------------------------------------------------------------------
void ofxCvImage::blur( int value ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in blur, need to allocate image first");
		return;
	}
    if( value % 2 == 0 ) {
        ofLog(OF_LOG_NOTICE, "in blur, value not odd -> will add 1 to cover your back");
        value++;
    }
	cvSmooth( cvImage, cvImageTemp, CV_BLUR , value);
	swapTemp();
    flagImageChanged();
}

//--------------------------------------------------------------------------------
void ofxCvImage::blurGaussian( int value ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in blurGaussian, need to allocate image first");
		return;
	}
    if( value % 2 == 0 ) {
        ofLog(OF_LOG_NOTICE, "in blurGaussian, value not odd -> will add 1 to cover your back");
        value++;
    }
	cvSmooth( cvImage, cvImageTemp, CV_GAUSSIAN ,value );
	swapTemp();
    flagImageChanged();
}

//--------------------------------------------------------------------------------
void ofxCvImage::invert(){
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in invert, need to allocate image first");
		return;
	}
    cvNot(cvImage, cvImage);
    flagImageChanged();
}

// Image Transformation Operations

//--------------------------------------------------------------------------------
void ofxCvImage::mirror( bool bFlipVertically, bool bFlipHorizontally ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in mirror, need to allocate image first");
		return;
	}
	int flipMode = 0;

	if( bFlipVertically && !bFlipHorizontally ) flipMode = 0;
	else if( !bFlipVertically && bFlipHorizontally ) flipMode = 1;
	else if( bFlipVertically && bFlipHorizontally ) flipMode = -1;
	else return;

	cvFlip( cvImage, cvImageTemp, flipMode );
	swapTemp();
    flagImageChanged();
}

//--------------------------------------------------------------------------------
void ofxCvImage::translate( float x, float y ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in translate, need to allocate image first");
		return;
	}
    transform( 0, 0,0, 1,1, x,y );
    flagImageChanged();
}

//--------------------------------------------------------------------------------
void ofxCvImage::rotate( float angle, float centerX, float centerY ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in rotate, need to allocate image first");
		return;
	}
    transform( angle, centerX, centerY, 1,1, 0,0 );
    flagImageChanged();
}

//--------------------------------------------------------------------------------
void ofxCvImage::scale( float scaleX, float scaleY ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in scale, need to allocate image first");
		return;
	}
    transform( 0, 0,0, scaleX,scaleY, 0,0 );
    flagImageChanged();
}

//--------------------------------------------------------------------------------
void ofxCvImage::transform( float angle, float centerX, float centerY,
                            float scaleX, float scaleY,
                            float moveX, float moveY ){

	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in transform, need to allocate image first");
		return;
	}

    float sina = sin(angle * DEG_TO_RAD);
    float cosa = cos(angle * DEG_TO_RAD);
    CvMat*  transmat = cvCreateMat( 2,3, CV_32F );
    cvmSet( transmat, 0,0, scaleX*cosa );
    cvmSet( transmat, 0,1, scaleY*sina );
    cvmSet( transmat, 0,2, -centerX*scaleX*cosa - centerY*scaleY*sina + moveX + centerX );
    cvmSet( transmat, 1,0, -1.0*scaleX*sina );
    cvmSet( transmat, 1,1, scaleY*cosa );
    cvmSet( transmat, 1,2, -centerY*scaleY*cosa + centerX*scaleX*sina + moveY + centerY);

    cvWarpAffine( cvImage, cvImageTemp, transmat );
	swapTemp();
    flagImageChanged();

    cvReleaseMat( &transmat );
}

//--------------------------------------------------------------------------------
void ofxCvImage::undistort( float radialDistX, float radialDistY,
                            float tangentDistX, float tangentDistY,
                            float focalX, float focalY,
                            float centerX, float centerY ){

	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in undistort, need to allocate image first");
		return;
	}
    float camIntrinsics[] = { focalX, 0, centerX, 0, focalY, centerY, 0, 0, 1 };
    float distortionCoeffs[] = { radialDistX, radialDistY, tangentDistX, tangentDistY };
    cvUnDistortOnce( cvImage, cvImageTemp, camIntrinsics, distortionCoeffs, 1 );
	swapTemp();
    flagImageChanged();
}

//--------------------------------------------------------------------------------
void ofxCvImage::remap( IplImage* mapX, IplImage* mapY ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in remap, need to allocate image first");
		return;
	}
    cvRemap( cvImage, cvImageTemp, mapX, mapY );
	swapTemp();
    flagImageChanged();
}

/**
*    A  +-------------+  B
*      /               \
*     /                 \
*    /                   \
* D +-------------------- +  C
*/

//--------------------------------------------------------------------------------
void ofxCvImage::warpPerspective( const ofPoint& A, const ofPoint& B, const ofPoint& C, const ofPoint& D ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in warpPerspective, need to allocate image first");
		return;
	}
    // compute matrix for perspectival warping (homography)
    CvPoint2D32f cvsrc[4];
    CvPoint2D32f cvdst[4];
    CvMat* translate = cvCreateMat( 3,3, CV_32FC1 );
    cvSetZero( translate );

    cvdst[0].x = 0;
    cvdst[0].y = 0;
    cvdst[1].x = width;
    cvdst[1].y = 0;
    cvdst[2].x = width;
    cvdst[2].y = height;
    cvdst[3].x = 0;
    cvdst[3].y = height;

    cvsrc[0].x = A.x;
    cvsrc[0].y = A.y;
    cvsrc[1].x = B.x;
    cvsrc[1].y = B.y;
    cvsrc[2].x = C.x;
    cvsrc[2].y = C.y;
    cvsrc[3].x = D.x;
    cvsrc[3].y = D.y;

    cvWarpPerspectiveQMatrix( cvsrc, cvdst, translate );  // calculate homography
    cvWarpPerspective( cvImage, cvImageTemp, translate );
    swapTemp();
    flagImageChanged();
    cvReleaseMat( &translate );
}

//--------------------------------------------------------------------------------
void ofxCvImage::warpIntoMe( ofxCvImage& mom, const ofPoint src[4], const ofPoint dst[4] ){

	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in warpIntoMe, image not allocated");
		return;
	}
	if( !mom.bAllocated ){
		ofLog(OF_LOG_ERROR, "in warpIntoMe, mom not allocated");
		return;
	}

	if( mom.getCvImage()->nChannels == cvImage->nChannels &&
        mom.getCvImage()->depth == cvImage->depth ) {

    	// compute matrix for perspectival warping (homography)
    	CvPoint2D32f cvsrc[4];
    	CvPoint2D32f cvdst[4];
    	CvMat* translate = cvCreateMat( 3, 3, CV_32FC1 );
    	cvSetZero( translate );
    	for (int i = 0; i < 4; i++ ) {
    		cvsrc[i].x = src[i].x;
    		cvsrc[i].y = src[i].y;
    		cvdst[i].x = dst[i].x;
    		cvdst[i].y = dst[i].y;
    	}
    	cvWarpPerspectiveQMatrix( cvsrc, cvdst, translate );  // calculate homography
    	cvWarpPerspective( mom.getCvImage(), cvImage, translate);
        flagImageChanged();
    	cvReleaseMat( &translate );

    } else {
        ofLog(OF_LOG_ERROR, "in warpIntoMe: mom image type has to match");
    }
}

// Other Image Operations

//--------------------------------------------------------------------------------
int ofxCvImage::countNonZeroInRegion( int x, int y, int w, int h ) {
	if( !bAllocated ){
		ofLog(OF_LOG_ERROR, "in countNonZeroInRegion, need to allocate image first");
		return 0;
	}

    //TODO: test this method

	if (w == 0 || h == 0) return 0;
    int count = 0;

    // intersect the global ROI with the region to check
    ofRectangle iRoi = getIntersectionROI( getROI(), ofRectangle(x,y,w,h) );

    ofRectangle lastROI = getROI();
    setROI(iRoi);
	count = cvCountNonZero( cvImage );
    setROI(lastROI);

	return count;
}

// private methods

//--------------------------------------------------------------------------------
void ofxCvImage::swapTemp() {
	if (getROI().x != 0 ||
		getROI().y != 0 ||
		getROI().width != width ||
		getROI().height != height )
    {
		cvCopy( cvImageTemp, cvImage );
	} else {
		IplImage*  temp;
		temp = cvImage;
		cvImage	= cvImageTemp;
		cvImageTemp	= temp;
	}
}

//--------------------------------------------------------------------------------
void ofxCvImage::rangeMap( IplImage* img, float min1, float max1, float min2, float max2 ) {
    // map from min1-max1 to min2-max2
    float scale = (max2-min2)/(max1-min1);
    cvConvertScale( img, img, scale, -(min1*scale)+min2 );
}

//--------------------------------------------------------------------------------
void ofxCvImage::rangeMap( IplImage* mom, IplImage* kid, float min1, float max1, float min2, float max2 ) {
    // map from min1-max1 to min2-max2
    float scale = (max2-min2)/(max1-min1);
    cvConvertScale( mom, kid, scale, -(min1*scale)+min2 );
}

//--------------------------------------------------------------------------------
bool ofxCvImage::matchingROI( const ofRectangle& rec1, const ofRectangle& rec2 ) {
    if( rec1.width == rec2.width && rec1.height == rec2.height && rec1.width != 0 && rec1.height != 0 ) {
        return true;
    } else {
        return false;
    }
}

//--------------------------------------------------------------------------------
void  ofxCvImage::setImageROI( IplImage* img, const ofRectangle& roi ) {
    cvSetImageROI(img, cvRect((int)roi.x,(int)roi.y,(int)roi.width,(int)roi.height));
}

//--------------------------------------------------------------------------------
void  ofxCvImage::resetImageROI( IplImage* img ) {
    cvResetImageROI(img);
}

//--------------------------------------------------------------------------------
void ofxCvImage::setFromPixels( const ofPixels & pixels ){
	setFromPixels(pixels.getPixels(),pixels.getWidth(),pixels.getHeight());
}

//--------------------------------------------------------------------------------
void ofxCvImage::setRoiFromPixels( const ofPixels & pixels ){
	setRoiFromPixels(pixels.getPixels(),pixels.getWidth(),pixels.getHeight());
}

//--------------------------------------------------------------------------------
unsigned char*  ofxCvImage::getPixels(){
	return getPixelsRef().getPixels();
}

//--------------------------------------------------------------------------------
ofPixelsRef ofxCvImage::getPixelsRef(){
	if(!bAllocated) {
		ofLog(OF_LOG_WARNING, "in getPixelsRef, image is not allocated");
	} else if(bRoiPixelsDirty) {
		IplImage * cv8bit= getCv8BitsImage();

		//Note this possible introduces a bug where pixels doesn't contain the current image.
		//Also it means that modifying the pointer return by get pixels - affects the internal cvImage
		//Where as with the slower way below modifying the pointer doesn't change the image.
		if(  cv8bit->width*cv8bit->nChannels == cvImage->widthStep ){
			pixels.setFromExternalPixels((unsigned char*)cv8bit->imageData,width,height,cv8bit->nChannels);
		}else{
			pixels.setFromAlignedPixels((unsigned char*)cv8bit->imageData,width,height,cv8bit->nChannels,cv8bit->widthStep);
		}
		bPixelsDirty = false;
	}
	return pixels;
}

//--------------------------------------------------------------------------------
unsigned char*  ofxCvImage::getRoiPixels(){
	return getRoiPixelsRef().getPixels();
}

//--------------------------------------------------------------------------------
ofPixelsRef  ofxCvImage::getRoiPixelsRef(){
	if(!bAllocated) {
		ofLog(OF_LOG_WARNING, "in getRoiPixelsRef, image is not allocated");
	} else if(bRoiPixelsDirty) {
		IplImage * cv8bit= getCv8BitsRoiImage();
		ofRectangle roi = getROI();
		unsigned char * roi_ptr = (unsigned char*)cv8bit->imageData + ((int)(roi.y)*cv8bit->widthStep + (int)roi.x * cv8bit->nChannels);
		roiPixels.setFromAlignedPixels(roi_ptr,roi.width,roi.height,cv8bit->nChannels,cv8bit->widthStep);
		bRoiPixelsDirty = false;
	}
	return roiPixels;
}


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

<TITLE>
fr.cryptohash.test
</TITLE>

<META NAME="date" CONTENT="2011-07-20">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

fr.cryptohash.test

Classes

Speed

TestDigest