text:
/* eslint-disable no-unused-expressions */
import sinon from 'sinon';
import chai, { expect } from 'chai';
import sinonChai from 'sinon-chai';
import dns from 'dns';
import merge from 'lodash/merge';

import DnsClusterResolver from '../src/DnsClusterResolver';

chai.use(sinonChai);

function makeConfig(overrides = {}) {
  const config = {
    instance: {
      dataCenterInfo: { metadata: { 'availability-zone': '1b' } },
    },
    eureka: {
      host: 'eureka.mydomain.com',
      servicePath: '/eureka/v2/apps/',
      port: 9999,
      maxRetries: 0,
      ec2Region: 'my-region',
    },
  };
  return merge({}, config, overrides);
}

describe('DNS Cluster Resolver', () => {
  describe('DnsClusterResolver', () => {
    it('should throw error when ec2Region is undefined', () => {
      const config = makeConfig();
      config.eureka.ec2Region = undefined;
      function fn() {
        return new DnsClusterResolver(config);
      }
      expect(fn).to.throw();
    });
  });

  describe('startClusterRefresh()', () => {
    let dnsResolver;
    let refreshStub;
    let clock;
    beforeEach(() => {
      clock = sinon.useFakeTimers();
    });

    afterEach(() => {
      dnsResolver.refreshCurrentCluster.restore();
      clock.restore();
    });

    it('should start cluster refreshes on interval', () => {
      dnsResolver = new DnsClusterResolver(makeConfig({
        eureka: { clusterRefreshInterval: 300000 },
      }));
      refreshStub = sinon.stub(dnsResolver, 'refreshCurrentCluster');
      clock.tick(300000);
      expect(refreshStub).to.have.been.calledOnce;
      clock.tick(300000);
      expect(refreshStub).to.have.been.calledTwice;
      clock.restore();
    });

    it('should log warning on refresh failure', () => {
      dnsResolver = new DnsClusterResolver(makeConfig({
        eureka: { clusterRefreshInterval: 300000 },
      }));
      refreshStub = sinon.stub(dnsResolver, 'refreshCurrentCluster');
      refreshStub.yields(new Error('fail'));
      clock.tick(300000);
      expect(refreshStub).to.have.been.calledOnce;
      clock.tick(300000);
      expect(refreshStub).to.have.been.calledTwice;
      clock.restore();
    });
  });

  describe('resolveEurekaUrl()', () => {
    let dnsResolver;
    beforeEach(() => {
      dnsResolver = new DnsClusterResolver(makeConfig());
    });

    afterEach(() => {
      dnsResolver.resolveClusterHosts.restore();
    });

    it('should return base Eureka URL using current cluster host', () => {
      const resolveHostsStub = sinon.stub(dnsResolver, 'resolveClusterHosts');
      resolveHostsStub.yields(null, ['a.mydomain.com', 'b.mydomain.com', 'c.mydomain.com']);
      dnsResolver.resolveEurekaUrl((err, eurekaUrl) => {
        expect(eurekaUrl).to.equal('http://a.mydomain.com:9999/eureka/v2/apps/');
      });
    });

    it('should return base Eureka URL using next cluster host on retry', () => {
      const resolveHostsStub = sinon.stub(dnsResolver, 'resolveClusterHosts');
      resolveHostsStub.yields(null, ['a.mydomain.com', 'b.mydomain.com', 'c.mydomain.com']);
      dnsResolver.resolveEurekaUrl((err, eurekaUrl) => {
        expect(eurekaUrl).to.equal('http://b.mydomain.com:9999/eureka/v2/apps/');
        expect(dnsResolver.serverList).to.eql(['b.mydomain.com', 'c.mydomain.com',
          'a.mydomain.com']);
      }, 1);
    });

    it('should return error when resolve fails', () => {
      const resolveHostsStub = sinon.stub(dnsResolver, 'resolveClusterHosts');
      resolveHostsStub.yields(new Error('fail'));
      dnsResolver.resolveEurekaUrl((err) => {
        expect(err).to.not.equal(undefined);
        expect(err.message).to.equal('fail');
      });
    });
  });

  describe('getCurrentCluster()', () => {
    let dnsResolver;
    beforeEach(() => {
      dnsResolver = new DnsClusterResolver(makeConfig());
    });

    afterEach(() => {
      dnsResolver.resolveClusterHosts.restore();
    });

    it('should call cluster refresh if server list is undefined', () => {
      const resolveHostsStub = sinon.stub(dnsResolver, 'resolveClusterHosts');
      resolveHostsStub.onCall(0).yields(null, ['a', 'b', 'c']);
      resolveHostsStub.onCall(1).yields(null, ['f', 'a', 'c']);
      dnsResolver.getCurrentCluster((err, serverList) => {
        expect(serverList).to.include.members(['a', 'b', 'c']);
        dnsResolver.getCurrentCluster((errTwo, serverListTwo) => {
          expect(serverListTwo).to.include.members(['a', 'b', 'c']);
        });
      });
    });

    it('should return error when refresh fails', () => {
      const resolveHostsStub = sinon.stub(dnsResolver, 'resolveClusterHosts');
      resolveHostsStub.yields(new Error('fail'));
      dnsResolver.getCurrentCluster((err) => {
        expect(err).to.not.equal(undefined);
        expect(err.message).to.equal('fail');
      });
    });
  });

  describe('refreshCurrentCluster', () => {
    let dnsResolver;
    beforeEach(() => {
      dnsResolver = new DnsClusterResolver(makeConfig());
    });

    afterEach(() => {
      dnsResolver.resolveClusterHosts.restore();
    });

    it('should refresh server list', () => {
      const resolveHostsStub = sinon.stub(dnsResolver, 'resolveClusterHosts');
      resolveHostsStub.onCall(0).yields(null, ['a', 'b', 'c']);
      resolveHostsStub.onCall(1).yields(null, ['a', 'b', 'c', 'd']);
      dnsResolver.refreshCurrentCluster((err) => {
        expect(err).to.equal(undefined);
        expect(dnsResolver.serverList).to.eql(['a', 'b', 'c']);
        dnsResolver.refreshCurrentCluster((errTwo) => {
          expect(errTwo).to.equal(undefined);
          expect(dnsResolver.serverList).to.eql(['a', 'b', 'c', 'd']);
        });
      });
    });

    it('should maintain server list when cluster remains unchanged', () => {
      const resolveHostsStub = sinon.stub(dnsResolver, 'resolveClusterHosts');
      resolveHostsStub.onCall(0).yields(null, ['a', 'b', 'c']);
      resolveHostsStub.onCall(1).yields(null, ['c', 'a', 'b']);
      dnsResolver.refreshCurrentCluster((err) => {
        expect(err).to.equal(undefined);
        expect(dnsResolver.serverList).to.eql(['a', 'b', 'c']);
        dnsResolver.refreshCurrentCluster((errTwo) => {
          expect(errTwo).to.equal(undefined);
          expect(dnsResolver.serverList).to.eql(['a', 'b', 'c']);
        });
      });
    });

    it('should return error when resolve fails', () => {
      const resolveHostsStub = sinon.stub(dnsResolver, 'resolveClusterHosts');
      resolveHostsStub.yields(new Error('fail'));
      dnsResolver.refreshCurrentCluster((err) => {
        expect(err).to.not.equal(undefined);
        expect(err.message).to.equal('fail');
      });
    });
  });

  describe('resolveClusterHosts()', () => {
    const eurekaHosts = [
      '1a.eureka.mydomain.com',
      '1b.eureka.mydomain.com',
      '1c.eureka.mydomain.com',
    ];

    afterEach(() => {
      dns.resolveTxt.restore();
    });

    it('should resolve hosts using DNS', (done) => {
      const dnsResolver = new DnsClusterResolver(makeConfig());
      const resolveStub = sinon.stub(dns, 'resolveTxt');
      resolveStub.withArgs('txt.my-region.eureka.mydomain.com').yields(null, [eurekaHosts]);
      resolveStub.withArgs('txt.1a.eureka.mydomain.com').yields(null, [['1.2.3.4']]);
      resolveStub.withArgs('txt.1b.eureka.mydomain.com').yields(null, [['2.2.3.4']]);
      resolveStub.withArgs('txt.1c.eureka.mydomain.com').yields(null, [['3.2.3.4']]);
      dnsResolver.resolveClusterHosts((err, hosts) => {
        expect(hosts).to.include.members(['1.2.3.4', '2.2.3.4', '3.2.3.4']);
        done();
      });
    });

    it('should resolve hosts using DNS and zone affinity', (done) => {
      const dnsResolver = new DnsClusterResolver(makeConfig({
        eureka: { preferSameZone: true },
      }));
      const resolveStub = sinon.stub(dns, 'resolveTxt');
      resolveStub.withArgs('txt.my-region.eureka.mydomain.com').yields(null, [eurekaHosts]);
      resolveStub.withArgs('txt.1a.eureka.mydomain.com').yields(null, [['1.2.3.4']]);
      resolveStub.withArgs('txt.1b.eureka.mydomain.com').yields(null, [['2.2.3.4']]);
      resolveStub.withArgs('txt.1c.eureka.mydomain.com').yields(null, [['3.2.3.4']]);
      dnsResolver.resolveClusterHosts((err, hosts) => {
        expect(hosts[0]).to.equal('2.2.3.4');
        expect(hosts).to.include.members(['1.2.3.4', '2.2.3.4', '3.2.3.4']);
        dnsResolver.resolveClusterHosts((error, hostsTwo) => {
          expect(hostsTwo[0]).to.equal('2.2.3.4');
          expect(hostsTwo).to.include.members(['1.2.3.4', '2.2.3.4', '3.2.3.4']);
          done();
        });
      });
    });

    it('should resolve hosts when dataCenterInfo is undefined', (done) => {
      const config = {
        instance: {},
        eureka: {
          preferSameZone: true,
          host: 'eureka.mydomain.com',
          servicePath: '/eureka/v2/apps/',
          port: 9999,
          maxRetries: 0,
          ec2Region: 'my-region',
        },
      };
      const dnsResolver = new DnsClusterResolver(config);
      const resolveStub = sinon.stub(dns, 'resolveTxt');
      resolveStub.withArgs('txt.my-region.eureka.mydomain.com').yields(null, [eurekaHosts]);
      resolveStub.withArgs('txt.1a.eureka.mydomain.com').yields(null, [['1.2.3.4']]);
      resolveStub.withArgs('txt.1b.eureka.mydomain.com').yields(null, [['2.2.3.4']]);
      resolveStub.withArgs('txt.1c.eureka.mydomain.com').yields(null, [['3.2.3.4']]);
      dnsResolver.resolveClusterHosts((err, hosts) => {
        expect(hosts).to.include.members(['1.2.3.4', '2.2.3.4', '3.2.3.4']);
        dnsResolver.resolveClusterHosts((error, hostsTwo) => {
          expect(hostsTwo).to.include.members(['1.2.3.4', '2.2.3.4', '3.2.3.4']);
          done();
        });
      });
    });

    it('should return error when initial DNS lookup fails', () => {
      const resolveCb = sinon.spy();
      const dnsResolver = new DnsClusterResolver(makeConfig());
      const resolveStub = sinon.stub(dns, 'resolveTxt');
      resolveStub.withArgs('txt.my-region.eureka.mydomain.com')
        .yields(new Error('dns error'), null);

      function shouldNotThrow() {
        dnsResolver.resolveClusterHosts(resolveCb);
      }

      expect(shouldNotThrow).to.not.throw();
      expect(dns.resolveTxt).to.have.been.calledWithMatch('txt.my-region.eureka.mydomain.com');
      expect(resolveCb).to.have.been.calledWithMatch({
        message: 'Error resolving eureka cluster ' +
          'for region [my-region] using DNS: [Error: dns error]',
      });
    });

    it('should return error when DNS lookup fails for an individual zone', () => {
      const resolveCb = sinon.spy();
      const dnsResolver = new DnsClusterResolver(makeConfig({
        eureka: { host: 'eureka.mydomain.com', port: 9999, ec2Region: 'my-region' },
      }));
      const resolveStub = sinon.stub(dns, 'resolveTxt');
      resolveStub.withArgs('txt.my-region.eureka.mydomain.com').yields(null, [eurekaHosts]);
      resolveStub.withArgs('txt.1a.eureka.mydomain.com').yields(null, [['1.2.3.4']]);
      resolveStub.withArgs('txt.1b.eureka.mydomain.com').yields(new Error('dns error'), null);
      resolveStub.withArgs('txt.1c.eureka.mydomain.com').yields(null, [['3.2.3.4']]);

      function shouldNotThrow() {
        dnsResolver.resolveClusterHosts(resolveCb);
      }

      expect(shouldNotThrow).to.not.throw();
      expect(resolveCb).to.have.been.calledWithMatch({
        message: 'Error resolving cluster zone txt.1b.eureka.mydomain.com: [Error: dns error]',
      });
    });

    it('should return error when no hosts were found', (done) => {
      const dnsResolver = new DnsClusterResolver(makeConfig());
      const resolveStub = sinon.stub(dns, 'resolveTxt');
      resolveStub.withArgs('txt.my-region.eureka.mydomain.com').yields(null, [eurekaHosts]);
      resolveStub.withArgs('txt.1a.eureka.mydomain.com').yields(null, []);
      resolveStub.withArgs('txt.1b.eureka.mydomain.com').yields(null, []);
      resolveStub.withArgs('txt.1c.eureka.mydomain.com').yields(null, []);
      dnsResolver.resolveClusterHosts((err) => {
        expect(err).to.not.equal(undefined);
        expect(err.message).to.equal('Unable to locate any Eureka hosts in any ' +
          'zone via DNS @ txt.my-region.eureka.mydomain.com');
        done();
      });
    });
  });
});


text:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { UserProfileService } from './user-profile.service';

@Injectable()
export class LoginService {
  constructor(private userProfileService: UserProfileService) { }

  login() {
     return Observable.of(true)
        .delay(1000)
        .do(this.toggleLogState.bind(this));
  }

  logout() {
    this.toggleLogState(false);
  }

  private toggleLogState(val: boolean) {
    this.userProfileService.isLoggedIn = val;
  }
}

redpajama_set_name: RedPajamaGithub


text:
class CommentBox extends React.Component {
  render() {
    return(

Comments

2 comments

          <Comment author="Anne Droid" body="I want to know what love is..." />

    );
  }
}

class Comment extends React.Component {
  render() {
    return(

          {this.props.author}

          {this.props.body}

          Delete comment

    );
  }
}


text:
package diceroller.userinterface;

import java.awt.GridBagLayout;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;

public class EditRPGModPane {

	private JPanel panel;
	CustomSpinner ModTotalSpinner;
	CustomSpinner ModMultiplySpinner;

	public EditRPGModPane(int ModTotal, int ModMultiply)
	{
		panel = new JPanel();
        panel.setLayout(new GridLayout2());

        JPanel panelTotal= new JPanel();
        panelTotal.setLayout(new GridBagLayout());
        panelTotal.add(new JLabel("Mod total: "));
        ModTotalSpinner=new CustomSpinner(99,-99,ModTotal,1);
        panelTotal.add(ModTotalSpinner);
        panelTotal.add(new JLabel("   "));

        JPanel panelMultiply= new JPanel();
        panelMultiply.setLayout(new GridBagLayout());
        panelMultiply.add(new JLabel("   Mod per roll: "));
        ModMultiplySpinner=new CustomSpinner(99,-99,ModMultiply,1);
        panelMultiply.add(ModMultiplySpinner);

        panel.add(panelTotal);
        panel.add(new JSeparator(SwingConstants.VERTICAL));
        panel.add(panelMultiply);

	}
    public int displayGUI()
    {
        return JOptionPane.showConfirmDialog(null,
                        getPanel(),
                        "Edit Mods",
                        JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.PLAIN_MESSAGE);
    }

    private JPanel getPanel()
    {
        return panel;
    }
    public int getModTotal()
    {
    	return ModTotalSpinner.getValue();
    }
    public int getModMultiply()
    {
    	return ModMultiplySpinner.getValue();
    }

}


text:
<?php

require_once __DIR__ . '/../bootstrap.php';
require_once __DIR__ . '/TestResultMock.php';

use Tester\Assert;
use App\Helpers\Evaluation\UniversalScoreCalculator;
use App\Exceptions\SubmissionEvaluationFailedException;
/**
 * @testCase
 */
class TestUniversalScoreCalculator extends Tester\TestCase
{
    /**
     * Used for construction of universal score configs.
     * Name of the static function is transcribed to node type, arguments become children.
     * String arguments are converted into test-result nodes, numbers into literals.
     */
    public static function __callStatic($name, $arguments)
    {
        $children = [];
        foreach ($arguments as $arg) {
            if (is_string($arg)) {
                $children[] = [
                    'type' => 'test-result',
                    'test' => $arg,
                ];
            } else {
                $children[] = is_numeric($arg) ? (float)$arg : $arg;
            }
        }

        $res = [ 'type' => $name ];
        if ($children) {
            $res['children'] = $children;
        }
        return $res;
    }

    private static function randomStr($len)
    {
        return bin2hex(random_bytes($len));
    }

    /**
     * Generate random config parameters (with given prefix) and insert them into config structure (deeply).
     */
    private static function addDataExtensions(array &$config, $prefix = 'x-')
    {
        $count = rand(1, 3);
        for ($i = 0; $i < $count; ++$i) {
            $key = $prefix . self::randomStr(3);
            $value = self::randomStr(3);
            $config[$key] = $value;
        }

        if (array_key_exists('children', $config)) {
            foreach ($config['children'] as &$child) {
                if (is_array($child)) {
                    self::addDataExtensions($child, $prefix);
                }
            }
            unset($child);
        }
    }

    /**
     * Helper function that asserts two config structures for equality.
     * (i.e., it has the same semantics as Assert::equal)
     */
    private static function compareConfigs($expected, $actual)
    {
        Assert::equal(array_key_exists('children', $expected), array_key_exists('children', $actual));
        if (array_key_exists('children', $expected)) {
            $expectedChildren = $expected['children'];
            $actualChildren = $actual['children'];
            Assert::equal(count($expectedChildren), count($actualChildren));

            foreach ($expectedChildren as $key => $expectedChild) {
                $actualChild = $actualChildren[$key];
                if (is_array($actualChild) && is_array($expectedChild)) {
                    self::compareConfigs($expectedChild, $actualChild);
                } else {
                    Assert::equal($expectedChild, $actualChild);
                }
            }

            unset($expected['children']);
            unset($actual['children']);
        }

        Assert::equal($expected, $actual);
    }

    /**
     * Create sample configuration which uses most of function nodes.
     */
    private function getTestConfig()
    {
        return self::clamp(self::avg(
            self::max("a", "b", "c"),
            self::min("c", "d", "e"),
            self::div(
                self::sum(
                    self::sub(1, "a"),
                    self::mul(2, "b"),
                    self::mul(3, "d")
                ),
                self::neg(-6)
            )
        ));
    }

    /**
     * Convert associative array (test name => score) into test results mock.
     */
    private function prepareResults(array $data)
    {
        $results = [];
        foreach ($data as $name => $result) {
            $results[$name] = new TestResultMock($result);
        }
        return $results;
    }

    private function getCalc()
    {
        return new UniversalScoreCalculator();
    }

    /**
     * Instantiate the calculator and perform score computation (using sample config if not provided).
     */
    private function computeScore(array $results, array $config = null)
    {
        if ($config === null) {
            $config = $this->getTestConfig();
        }
        $results = $this->prepareResults($results);
        return $this->getCalc()->computeScore($config, $results);
    }

    public function testEvaluation1()
    {
        $res = $this->computeScore(["a" => 1.0, "b" => 1.0, "c" => 1.0, "d" => 1.0, "e" => 1.0]);
        Assert::equal(17.0 / 18.0, $res);
    }

    public function testEvaluation2()
    {
        $res = $this->computeScore(["a" => 0.0, "b" => 0.0, "c" => 0.0, "d" => 0.0, "e" => 0.0]);
        Assert::equal(1.0 / 18.0, $res);
    }

    public function testEvaluation3()
    {
        $res = $this->computeScore(["a" => 1.0, "b" => 0.0, "c" => 1.0, "d" => 0.0, "e" => 1.0]);
        Assert::equal(1.0 / 3.0, $res);
    }

    public function testEvaluation4()
    {
        $res = $this->computeScore(["a" => 0.0, "b" => 1.0, "c" => 0.0, "d" => 1.0, "e" => 0.0]);
        Assert::equal(2.0 / 3.0, $res);
    }

    public function testValidateConfig()
    {
        Assert::true($this->getCalc()->isScoreConfigValid($this->getTestConfig(), ["a", "b", "c", "d", "e"]));
    }

    public function _testBadConfig($config)
    {
        $calc = $this->getCalc();
        Assert::false($calc->isScoreConfigValid($config));
        Assert::exception(
            function () use ($calc, $config) {
                $calc->computeScore($config, ["a" => 1.0, "b" => 1.0, "c" => 1.0, "d" => 1.0, "e" => 1.0]);
            },
            SubmissionEvaluationFailedException::class
        );
    }

    public function testMalformedNodeMissingType()
    {
        $this->_testBadConfig(
            [ 'children' => [ $this->getTestConfig() ]]
        );
    }

    public function testMalformedNodeNullChild()
    {
        $this->_testBadConfig(self::clamp(null));
    }

    public function testInvalidFunctionName()
    {
        $this->_testBadConfig(self::foo(0.0));
    }

    public function testMissingChildren()
    {
        $this->_testBadConfig(self::sum());
    }

    public function testInvalidNumberOfChildrenUnary()
    {
        $this->_testBadConfig(self::neg(1.0, 0.0));
    }

    public function testInvalidNumberOfChildrenBinary()
    {
        $this->_testBadConfig(self::sub(1, 2, 3));
    }

    public function testInvalidNumberOfChildrenLeaf()
    {
        $this->_testBadConfig( [ 'type' => 'test-result', 'children' => [ self::sum(1, 2, 3) ]] );
    }

    public function testUnknownReference()
    {
        $calc = $this->getCalc();
        $config = $this->getTestConfig();
        Assert::false($calc->isScoreConfigValid($config, ["a", "b", "c", "d"]));
        Assert::exception(
            function () use ($calc, $config) {
                $results = $this->prepareResults(["a" => 1.0, "b" => 1.0, "c" => 1.0, "d" => 1.0]);
                $calc->computeScore($config, $results);
            },
            SubmissionEvaluationFailedException::class
        );
    }

    public function testNormalization()
    {
        $config = $this->getTestConfig();
        self::addDataExtensions($config);
        $normalized = $this->getCalc()->validateAndNormalizeScore($config);
        self::compareConfigs($config, $normalized);
    }

    public function testNormalizationWithUnkonwParams()
    {
        $config = $this->getTestConfig();
        self::addDataExtensions($config);

        $pollutedConfig = $config; // polluted config will contain some foo-xxx params, which will be removed
        self::addDataExtensions($pollutedConfig, 'foo-');

        $normalized = $this->getCalc()->validateAndNormalizeScore($pollutedConfig);
        self::compareConfigs($config, $normalized);
    }

    public function testDefaultConfig()
    {
        $testNames = ["A test", "B", "test C", "Test D"];
        $config = $this->getCalc()->getDefaultConfig($testNames);
        $correct = self::clamp(self::avg(...$testNames));
        Assert::equal($correct, $config);
    }

    public function testEmptyDefaultConfig()
    {
        $config = $this->getCalc()->getDefaultConfig([]);
        Assert::equal(['type' => 'value', 'value' => 1.0], $config);
    }
}

$testCase = new TestUniversalScoreCalculator();
$testCase->run();


text:
@interface IAMoviesViewController ()
@property NSMutableArray *allMovies;
@end

@implementation IAMoviesViewController
{
    IAMovieDbClient *_client;
    NSDictionary *_parameters;
    NSInteger _itemsPerPage;
    NSString *_imagesUrl;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.tableView registerNib:[UINib nibWithNibName:IAMainTableViewCellName bundle:nil]
         forCellReuseIdentifier:IAMainTableViewCellIdentifier];

    self.tableView.dataSource = self;

    _itemsPerPage = 4;
    [self loadMovies];

}

-(void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [super viewDidDisappear:animated];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.allMovies.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = IAMainTableViewCellIdentifier;
    IAMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    if(!cell) {
        cell = [[IAMainTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.delegate = self;

    IAMoviesCollection *moviesByType = self.allMovies[indexPath.row];
    moviesByType.mainTitle = [self setMainTitleWithRow:indexPath.row];

    cell.mainTitle.title = moviesByType.mainTitle;

    NSArray *movies = moviesByType.movies;

    NSArray *cellImages =[NSArray arrayWithObjects:cell.firstImage, cell.secondImage, cell.thirdImage, cell.fourthImage, cell.fifthImage,nil];

    [self attachGestureRecognizersToImages:cellImages];
    [self setImages:cellImages andIndexPathRow:indexPath.row];

    cell.firstLabel.text = [movies[0] title];
    cell.secondLabel.text = [movies[1] title];
    cell.thirdLabel.text = [movies[2] title];
    cell.fourthLabel.text = [movies[3] title];
    cell.fifthLabel.text = [movies[4] title];

    return cell;

}

-(void) loadMovies {
    self.allMovies = [[NSMutableArray alloc] init];
    _client = [[IAMovieDbClient alloc] init];
    _parameters = @{
                    IAApiKeyName : IAApiKeyValue
                    };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [self getWithUrl:IAUrlPopularMovies];
    [self getWithUrl:IAUrlNowPlayingMovies];
    [self getWithUrl:IAUrlTopRatedMovies];
    [self getWithUrl:IAUrlUpcomingMovies];
}

-(void)seeAllWasTapped:(IAMainTableViewCell *)cell {
    [self performSegueWithIdentifier:IAAllMoviesByTypeScene sender:cell];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier]  isEqual: IAAllMoviesByTypeScene]) {
        IAAllMoviesByTypeViewController *vc = [segue destinationViewController];
        NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
        vc.movies = [NSMutableArray arrayWithArray:[self.allMovies[indexPath.row] movies]];
        vc.title = [self.allMovies[indexPath.row] mainTitle];
        vc.moviesTypeUrl = [self.allMovies[indexPath.row] typeName];

    }
    else if([[segue identifier] isEqual:IAShowSingleMovieScene]) {
        IASingleMovieViewController *vc = [segue destinationViewController];
        vc.movieID = [sender tag];
    }
}

-(void)getWithUrl: (NSString *) url {

    __weak id weakSelf = self;
    [_client GET:url parameters:_parameters completion:^(OVCResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            IAMoviesCollection *_collection = response.result;
            _collection.typeName = url;
            [[weakSelf allMovies]  addObject:_collection];
        }
        if([self isDataLoaded] == YES || error != nil)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                IAAppDelegate *delegate = (IAAppDelegate *)[UIApplication sharedApplication].delegate;

                UIAlertController *alert = [delegate showErrorWithTitle:@"ERROR" andMessage:[error localizedDescription]];
                [MBProgressHUD hideHUDForView:[weakSelf view] animated:YES];
                if (error != nil) {
                    [weakSelf presentViewController:alert animated:YES completion:nil];
                }
                else {
                    [[weakSelf tableView] reloadData];
                }
            });
        }
    }];
}

-(void) handleImageTap:(UIGestureRecognizer *)gestureRecognizer {
    UIImageView *cell = (UIImageView*)gestureRecognizer.view;
    [self performSegueWithIdentifier:IAShowSingleMovieScene sender:cell];
}

-(void)attachGestureRecognizersToImages: (NSArray *) images {
    for (int i = 0; i < images.count; i++) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)];
        tap.cancelsTouchesInView = YES;
        tap.numberOfTapsRequired = 1;

        [images[i] addGestureRecognizer:tap];
    }
}

-(void) setImages: (NSArray *) images andIndexPathRow: (NSInteger)row{
    UIImage *defaultImage = [UIImage imageNamed:@"noImage"];
    IAMoviesCollection *moviesByType = self.allMovies[row];
    NSArray *movies = moviesByType.movies;
    NSArray *urls = [self getImageUrls:movies];

    for (int i = 0; i < images.count; i++) {
        UIImageView *currentImage = images[i];

        currentImage.tag = [[movies[i] movieId]integerValue];
        [currentImage sd_setImageWithURL:urls[i]
                        placeholderImage:defaultImage];
    }
}

-(BOOL) isDataLoaded {
    if (self.allMovies.count == _itemsPerPage) {
        return YES;
    }

    return false;
}

-(NSArray *) getImageUrls: (NSArray *) movies {
    NSMutableArray *urls = [[NSMutableArray alloc] init];
    for (int i = 0; i < 5; i++) {
        IAMovieCollection *movie = movies[i];
        if (movie.urlImage != nil) {
            [urls addObject:[NSURL URLWithString:[IAImageSmallBaseUrl stringByAppendingString:movie.urlImage]]];
        }
        else {
            [urls addObject:@"InvalidUrl"];
        }
    }

    return urls;
}

-(NSString *) setMainTitleWithRow: (NSInteger) row {
    if(row == 0) {
        return @"Popular movies";
    }
    else if(row == 1) {
        return @"Now playing movies";
    }
    else if(row == 2) {
        return @"Top rated movies";
    }
    else {
        return @"Upcoming movies";
    }
}
@end


text:
define(["dojo/_base/declare",
    "dojo/_base/lang",
    "dojo/_base/array",
    "dojo/_base/html",
    "dojo/on",
    "dojo/dom-class",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin",
    "dojo/text!./templates/SearchPane.html",
    "dojo/i18n!../nls/strings",
    "jimu/dijit/TabContainer3",
    "./AddFromUrlPane",
    // "./AddFromUrlDialog",
    "./SearchBox",
    "./BBoxOption",
    "./ScopeOptions",
    "./TypeOptions",
    "./SortOptions",
    "./ResultsPane",
    "./Paging",
    "./ResultCount"
  ],
  function(declare, lang, array, html, on, domClass,
    _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin,
    template, i18n, TabContainer3, AddFromUrlPane
    // , AddFromUrlDialog
  ) {

    return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {

      i18n: i18n,
      templateString: template,

      qDefaultFilter: null,
      qRequiredFilter: null,
      searchOnStart: true,

      searchContext: null,
      wabWidget: null,

      _dfd: null,

      postCreate: function() {
        this.inherited(arguments);
        array.forEach(this.getComponents(), function(component) {
          component.searchPane = this;
        }, this);
        this.initTabs();
      },

      startup: function() {
        if (this._started) {
          return;
        }
        this.inherited(arguments);
        this.bindEvents();
        this.initOptions();
        if (this.searchOnStart) {
          this.search();
        }
      },

      initTabs: function(){
        this.addFromUrlPane = new AddFromUrlPane({
          searchPane: this
        });
        html.place(this.addFromUrlPane.domNode, this.urlPane);
        this.tab = new TabContainer3({
          tabs: [{
            title: this.nls.search.searchBox.search,
            content: this.onlinePane
          }, {
            title: this.nls.search.url,
            content: this.urlPane
          }]
        }, this.tabNode);
        html.place(this.tab.domNode, this.domNode);
      },

      // addFromUrlClicked: function() {
      //   var d = new AddFromUrlDialog({
      //     wabWidget: this.wabWidget
      //   });
      //   d.show();
      // },

      _onFilterPlaceholderChanged: function() {
        if (domClass.contains(this.filterPlaceholder, "opened")) {
          domClass.remove(this.filterPlaceholder, "opened");
          domClass.remove(this.filterWrapper, "show");
        } else {
          this.filterWrapper.style.top = this.headerNode.clientHeight + "px";
          domClass.add(this.filterPlaceholder, "opened");
          domClass.add(this.filterWrapper, "show");
        }
      },

      _onSearchBoxPlaceholderChanged: function() {
        if (!this.searchBox) {
          return;
        }
        if (domClass.contains(this.searchBoxPlaceholder, "opened")) {
          domClass.remove(this.searchBoxPlaceholder, "opened");
          domClass.remove(this.searchBox.domNode, "show");
        } else {
          domClass.add(this.searchBoxPlaceholder, "opened");
          domClass.add(this.searchBox.domNode, "show");
          this.searchBox.searchTextBox.focus();
        }
      },

      bindEvents: function() {
        this.own(on(this.filterPlaceholder,
          'click',
          lang.hitch(this, this._onFilterPlaceholderChanged)));
        this.own(on(this.searchBoxPlaceholder,
          'click',
          lang.hitch(this, this._onSearchBoxPlaceholderChanged)));
      },

      buildQueryParams: function(task) {
        var qRequired = null;
        if (typeof this.qRequiredFilter === "string" && this.qRequiredFilter.length > 0) {
          qRequired = this.qRequiredFilter;
        }
        var params = {
          q: qRequired,
          canSortByRelevance: false
        };
        array.forEach(this.getComponents(), function(component) {
          component.appendQueryParams(params, task);
        });
        delete params.canSortByRelevance;
        if (params.q === null && typeof this.qDefaultFilter === "string" &&
          this.qDefaultFilter.length > 0) {
          params.q = this.qDefaultFilter;
        }
        return params;
      },

      getComponents: function() {
        return [this.searchBox,
          this.bboxOption,
          this.scopeOptions,
          this.typeOptions,
          this.sortOptions,
          this.resultsPane,
          this.paging,
          this.resultCount
        ];
      },

      initOptions: function() {
        // var options = this.wabWidget.config.scopeOptions || {};
        // var initOption = function(name, node) {
        //   var opt = options[name];
        //   if (opt) {
        //     if (typeof opt.allow === "boolean" && !opt.allow) {
        //       node.style.display = "none";
        //     }
        //     if (typeof opt.label === "string") {
        //       var s = lang.trim(opt.label);
        //       if (s.length > 0) {
        //         util.setNodeText(node, s);
        //       }
        //     }
        //   }
        // };
        // initOption("FromUrl", this.FromUrlNode);
      },

      resize: function() {
        this.contentNode.style.top = this.headerNode.clientHeight + 1 + "px";
        this.contentNode.style.bottom = this.footerNode.clientHeight + 1 + "px";
      },

      search: function() {
        var self = this,
          task = {};
        var params = this.buildQueryParams(task);
        if (params === null || params.q === null) {
          return;
        }
        if (params && params.sortField === null) {
          params.sortOrder = "desc"; // (wab queryItems issue - unable to use relevance)
          //console.warn("search-params",params);
        }
        var portal = this.searchContext.portal;
        if (task.scopeIsArcGISOnline && this.searchContext.arcgisOnlinePortal) {
          portal = this.searchContext.arcgisOnlinePortal;
        }
        //console.warn("portal",portal);

        if (this._dfd !== null) {
          this._dfd.cancel("Search aborted.", false);
        }
        var dfd = null;
        this._dfd = dfd = portal.queryItems(params).then(function(searchResponse) {
          //console.warn("searchResponse",searchResponse);
          if (!dfd.isCanceled()) {
            if (!searchResponse.queryParams) {
              searchResponse.queryParams = {
                start: searchResponse.start,
                num: searchResponse.num
              };
              if (!searchResponse.nextQueryParams) {
                if (typeof searchResponse.nextStart !== "undefined" &&
                  searchResponse.nextStart !== -1) {
                  searchResponse.nextQueryParams = {
                    start: searchResponse.nextStart
                  };
                }
              }
            }
            array.forEach(self.getComponents(), function(component) {
              component.processResults(searchResponse);
            });
          }
        }).otherwise(function(error) {
          // TODO handle the error
          console.warn("searchError", error);
        });
      }

    });

  });


text:
package eu.lunisolar.magma.func.predicate;

import eu.lunisolar.magma.func.*; // NOSONAR
import javax.annotation.Nonnull; // NOSONAR
import javax.annotation.Nullable; // NOSONAR
import java.util.Objects;// NOSONAR
import eu.lunisolar.magma.basics.meta.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR

import eu.lunisolar.magma.func.action.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR
import eu.lunisolar.magma.func.function.*; // NOSONAR
import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR
import eu.lunisolar.magma.func.function.from.*; // NOSONAR
import eu.lunisolar.magma.func.function.to.*; // NOSONAR
import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR
import eu.lunisolar.magma.func.predicate.*; // NOSONAR
import eu.lunisolar.magma.func.supplier.*; // NOSONAR

import org.testng.Assert;
import org.testng.annotations.*;      //NOSONAR
import java.util.regex.Pattern;          //NOSONAR
import java.text.ParseException;         //NOSONAR
import eu.lunisolar.magma.basics.*; //NOSONAR
import eu.lunisolar.magma.basics.exceptions.*; //NOSONAR
import java.util.concurrent.atomic.AtomicInteger; //NOSONAR
import eu.lunisolar.magma.func.tuple.*; // NOSONAR
import java.util.function.*; // NOSONAR

/** The test obviously concentrate on the interface methods the function it self is very simple.  */
public class LByteIntPredicateTest {
    private static final String ORIGINAL_MESSAGE = "Original message";
    private static final String EXCEPTION_WAS_WRAPPED = "Exception was wrapped.";
    private static final String NO_EXCEPTION_WERE_THROWN = "No exception were thrown.";

    private boolean testValue = true;

    private LByteIntPredicate sut = new LByteIntPredicate(){
        public  boolean testX(byte a1,int a2)  {
            return testValue;
        }
    };

    private LByteIntPredicate sutAlwaysThrowing = LByteIntPredicate.byteIntPred((a1,a2) -> {
            throw new ParseException(ORIGINAL_MESSAGE, 0);
    });

    private LByteIntPredicate sutAlwaysThrowingUnchecked = LByteIntPredicate.byteIntPred((a1,a2) -> {
            throw new IndexOutOfBoundsException(ORIGINAL_MESSAGE);
    });

    @Test
    public void testTheResult() throws Throwable {
         Assert.assertEquals(sut.test((byte)100,100), testValue);
    }

    @Test
    public void testTupleCall() throws Throwable {

        LByteIntPair domainObject = Tuple4U.byteIntPair((byte)100,100);

        Object result = sut.tupleTest(domainObject);

            Assert.assertEquals(result, testValue);
    }

    @Test
    public void testNonNullTest() throws Throwable {
            Assert.assertEquals(sut.nonNullTest((byte)100,100), testValue);
    }

    @Test
    public void testNestingTestUnchecked() throws Throwable {

        // then
        try {
            sutAlwaysThrowingUnchecked.nestingTest((byte)100,100);
            Assert.fail(NO_EXCEPTION_WERE_THROWN);
        } catch (Exception e) {
            Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class);
            Assert.assertNull(e.getCause());
            Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE);
        }
    }

    @Test
    public void testShovingTestUnchecked() throws Throwable {

        // then
        try {
            sutAlwaysThrowingUnchecked.shovingTest((byte)100,100);
            Assert.fail(NO_EXCEPTION_WERE_THROWN);
        } catch (Exception e) {
            Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class);
            Assert.assertNull(e.getCause());
            Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE);
        }
    }

    @Test
    public void testApplyAsBooleanShouldNotModifyValue() throws Throwable {
        Assert.assertEquals(sut.doApplyAsBoolean((byte)100,100), testValue);
    }

    @Test
    public void testFunctionalInterfaceDescription() throws Throwable {
        Assert.assertEquals(sut.functionalInterfaceDescription(), "LByteIntPredicate: boolean test(byte a1,int a2)");
    }

    @Test
    public void testByteIntPredMethod() throws Throwable {
        Assert.assertTrue(LByteIntPredicate.byteIntPred((a1,a2) -> testValue ) instanceof LByteIntPredicate);

    }

    @Test
    public void testnegate() throws Throwable {
        Assert.assertEquals(sut.negate().test((byte)100,100), !testValue);
    }

    @DataProvider(name="boolean permutations")
    public Object[][] permuations() {
       return new Object[][] {
            // b1 , b2   , AND  , OR   , XOR
            {false, false, false, false, false },
            {true , false, false, true , true },
            {false, true , false, true , true },
            {true , true , true , true , false },
       };
    }

    @Test(dataProvider="boolean permutations")
    public void testAndOrXor(final boolean f1Result, final boolean f2Result, final boolean andResult, final boolean orResult, final boolean xorResult) throws Throwable {

        //given
        LByteIntPredicate fun1 = LByteIntPredicate.byteIntPred((a1,a2) -> f1Result);
        LByteIntPredicate fun2 = LByteIntPredicate.byteIntPred((a1,a2) -> f2Result);

        //when
        LByteIntPredicate andFunction = fun1.and(fun2);
        LByteIntPredicate orFunction = fun1.or(fun2);
        LByteIntPredicate xorFunction = fun1.xor(fun2);

        //then
        Assert.assertEquals(andFunction.test((byte)100,100), andResult);

        Assert.assertEquals(orFunction.test((byte)100,100), orResult);

        Assert.assertEquals(xorFunction.test((byte)100,100), xorResult);
    }

    @Test
    public void testIsEqual() throws Throwable  {
        //when
        LByteIntPredicate equals = LByteIntPredicate.isEqual((byte)1,1);

        //then
        Assert.assertTrue(equals.test((byte)1,1));

        Assert.assertFalse(equals.test((byte)0,0));
    }

    // <editor-fold desc="compose (functional)">

    @Test
    public void testCompose() throws Throwable {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final AtomicInteger beforeCalls = new AtomicInteger(0);

        //given (+ some assertions)
        LByteIntPredicate sutO = (a1,a2) -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a1, (Object) (byte)90);
                Assert.assertEquals(a2, (Object) 91);
                return true;
        };

        LByteUnaryOperator before1 = p0 -> {
            Assert.assertEquals(p0, (Object) (byte)80);
            beforeCalls.incrementAndGet();
            return (byte)90;
        };
        LIntUnaryOperator before2 = p1 -> {
            Assert.assertEquals(p1, (Object) 81);
            beforeCalls.incrementAndGet();
            return 91;
        };

        //when
        LByteIntPredicate function = sutO.compose(before1,before2);
        function.test((byte)80,81);

        //then - finals
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertEquals(beforeCalls.get(), 2);
    }

    @Test
    public void testUnboxingCompose() throws Throwable {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final AtomicInteger beforeCalls = new AtomicInteger(0);

        //given (+ some assertions)
        LByteIntPredicate sutO = (a1,a2) -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a1, (Object) (byte)90);
                Assert.assertEquals(a2, (Object) 91);
                return true;
        };

        LToByteFunction<Integer> before1 = p0 -> {
            Assert.assertEquals(p0, (Object) 80);
            beforeCalls.incrementAndGet();
            return (byte)90;
        };
        LToIntFunction<Integer> before2 = p1 -> {
            Assert.assertEquals(p1, (Object) 81);
            beforeCalls.incrementAndGet();
            return 91;
        };

        //when
        LBiPredicate<Integer,Integer> function = sutO.unboxingCompose(before1,before2);
        function.test(80,81);

        //then - finals
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertEquals(beforeCalls.get(), 2);
    }

    // </editor-fold>

    // <editor-fold desc="then (functional)">

    @Test
    public void testBoolToByteIntPred0() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LByteIntPredicate sutO = (a1,a2) -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a1, (Object) (byte)80);
                Assert.assertEquals(a2, (Object) 81);
                return true;
        };

        LLogicalOperator thenFunction = p -> {
                thenFunctionCalled.set(true);
                // boolean
                Assert.assertEquals(p, (Object) true);
                // boolean
                return true;
        };

        //when
        LByteIntPredicate function = sutO.boolToByteIntPred(thenFunction);
        boolean finalValue = function.test((byte)80,81);

        //then - finals
        Assert.assertEquals(finalValue, (Object) true);
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    // </editor-fold>

    @Test(expectedExceptions = RuntimeException.class)
    public void testShove() {

        // given
        LByteIntPredicate sutThrowing = LByteIntPredicate.byteIntPred((a1,a2) -> {
            throw new UnsupportedOperationException();
        });

        // when
        sutThrowing.shovingTest((byte)100,100);
    }

    @Test
    public void testToString() throws Throwable {

        Assert.assertTrue(sut.toString().startsWith(this.getClass().getName()+"$"));

        Assert.assertTrue(String.format("%s", sut).contains("LByteIntPredicate: boolean test(byte a1,int a2)"));

    }

    @Test
    public void isThrowing() {

        Assert.assertFalse(sut.isThrowing());
    }

}


text:
<?php

namespace Drupal\Tests\search\Functional;

use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\Tests\BrowserTestBase;

/**
 * Tests that comment count display toggles properly on comment status of node.
 *
 * Issue 537278
 *
 * - Nodes with comment status set to Open should always how comment counts
 * - Nodes with comment status set to Closed should show comment counts
 *     only when there are comments
 * - Nodes with comment status set to Hidden should never show comment counts
 *
 * @group search
 */
class SearchCommentCountToggleTest extends BrowserTestBase {

  use CommentTestTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['node', 'comment', 'search', 'dblog'];

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * A user with permission to search and post comments.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $searchingUser;

  /**
   * Array of nodes available to search.
   *
   * @var \Drupal\node\NodeInterface[]
   */
  protected $searchableNodes;

  protected function setUp(): void {
    parent::setUp();

    $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);

    // Create searching user.
    $this->searchingUser = $this->drupalCreateUser([
      'search content',
      'access content',
      'access comments',
      'post comments',
      'skip comment approval',
    ]);

    // Log in with sufficient privileges.
    $this->drupalLogin($this->searchingUser);

    // Add a comment field.
    $this->addDefaultCommentField('node', 'article');
    // Create initial nodes.
    $node_params = ['type' => 'article', 'body' => [['value' => 'SearchCommentToggleTestCase']]];

    $this->searchableNodes['1 comment'] = $this->drupalCreateNode($node_params);
    $this->searchableNodes['0 comments'] = $this->drupalCreateNode($node_params);

    // Create a comment array
    $edit_comment = [];
    $edit_comment['subject[0][value]'] = $this->randomMachineName();
    $edit_comment['comment_body[0][value]'] = $this->randomMachineName();

    // Post comment to the test node with comment
    $this->drupalGet('comment/reply/node/' . $this->searchableNodes['1 comment']->id() . '/comment');
    $this->submitForm($edit_comment, 'Save');

    // First update the index. This does the initial processing.
    $this->container->get('plugin.manager.search')->createInstance('node_search')->updateIndex();
  }

  /**
   * Verify that comment count display toggles properly on comment status of node.
   */
  public function testSearchCommentCountToggle() {
    // Search for the nodes by string in the node body.
    $edit = [
      'keys' => "'SearchCommentToggleTestCase'",
    ];
    $this->drupalGet('search/node');

    // Test comment count display for nodes with comment status set to Open
    $this->submitForm($edit, 'Search');
    $this->assertSession()->pageTextContains('0 comments');
    $this->assertSession()->pageTextContains('1 comment');

    // Test comment count display for nodes with comment status set to Closed
    $this->searchableNodes['0 comments']->set('comment', CommentItemInterface::CLOSED);
    $this->searchableNodes['0 comments']->save();
    $this->searchableNodes['1 comment']->set('comment', CommentItemInterface::CLOSED);
    $this->searchableNodes['1 comment']->save();

    $this->submitForm($edit, 'Search');
    $this->assertSession()->pageTextNotContains('0 comments');
    $this->assertSession()->pageTextContains('1 comment');

    // Test comment count display for nodes with comment status set to Hidden
    $this->searchableNodes['0 comments']->set('comment', CommentItemInterface::HIDDEN);
    $this->searchableNodes['0 comments']->save();
    $this->searchableNodes['1 comment']->set('comment', CommentItemInterface::HIDDEN);
    $this->searchableNodes['1 comment']->save();

    $this->submitForm($edit, 'Search');
    $this->assertSession()->pageTextNotContains('0 comments');
    $this->assertSession()->pageTextNotContains('1 comment');
  }

}


text:
<!--

-->

<ironjacamar xmlns="http://www.ironjacamar.org/doc/schema"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.ironjacamar.org/doc/schema
             http://www.ironjacamar.org/doc/schema/ironjacamar_1_1.xsd">

  <transaction-support>NoTransaction</transaction-support>

  <connection-definitions>
    <connection-definition class-name="io.vertx.resourceadapter.impl.VertxManagedConnectionFactory" jndi-name="java:/eis/VertxConnectionFactory" pool-name="VertxConnectionFactory">
      <config-property name="clusterHost">localhost</config-property>
      <config-property name="clusterPort">0</config-property>
    </connection-definition>
  </connection-definitions>

</ironjacamar>


text:
using UnityEngine;
using UnityEditor;

//-------------------------------------------------------------------------------------
// ***** OculusBuild
//
// OculusBuild adds menu functionality for a user to build the currently selected scene,
// and to also build and run the standalone build. These menu items can be found under the
// Oculus/Build menu from the main Unity Editor menu bar.
//

class OculusBuild
{

#if UNITY_STANDALONE_WIN
	// Build the standalone Windows demo and place into main project folder
	[MenuItem ("Oculus/Build/StandaloneWindows")]
	static void PerformBuildStandaloneWindows ()
	{
		if(Application.isEditor)
		{
			string[] scenes = { EditorApplication.currentScene };
			BuildPipeline.BuildPlayer(scenes, "Win_OculusUnityDemoScene.exe", BuildTarget.StandaloneWindows, BuildOptions.None);
		}
	}

	// Build the standalone Windows demo and place into main project folder, and then run
	[MenuItem ("Oculus/Build/StandaloneWindows - Run")]
	static void PerformBuildStandaloneWindowsRun ()
	{
		if(Application.isEditor)
		{
			string[] scenes = { EditorApplication.currentScene };
			BuildPipeline.BuildPlayer(scenes, "Win_OculusUnityDemoScene.exe", BuildTarget.StandaloneWindows, BuildOptions.AutoRunPlayer);
		}
		else
		{
			string[] scenes = { "Assets/Tuscany/Scenes/VRDemo_Tuscany.unity" };
			BuildPipeline.BuildPlayer(scenes, "Win_OculusUnityDemoScene.exe", BuildTarget.StandaloneWindows, BuildOptions.AutoRunPlayer);
		}
    }
#endif

#if UNITY_STANDALONE_OSX
	// Build the standalone Mac demo and place into main project folder
	[MenuItem ("Oculus/Build/StandaloneMac")]
	static void PerformBuildStandaloneMac ()
	{
		if(Application.isEditor)
		{
			string[] scenes = { EditorApplication.currentScene };
			BuildPipeline.BuildPlayer(scenes, "Mac_OculusUnityDemoScene.app", BuildTarget.StandaloneOSXIntel, BuildOptions.None);
		}
	}

	// Build the standalone Mac demo and place into main project folder, and then run
	[MenuItem ("Oculus/Build/StandaloneMac - Run")]
	static void PerformBuildStandaloneMacRun ()
	{
		if(Application.isEditor)
		{
			string[] scenes = { EditorApplication.currentScene };
			BuildPipeline.BuildPlayer(scenes, "Mac_OculusUnityDemoScene.app", BuildTarget.StandaloneOSXIntel, BuildOptions.AutoRunPlayer);
		}
		else
		{
			string[] scenes = { "Assets/Tuscany/Scenes/VRDemo_Tuscany.unity" };
			BuildPipeline.BuildPlayer(scenes, "Mac_OculusUnityDemoScene.app", BuildTarget.StandaloneOSXIntel, BuildOptions.AutoRunPlayer);
		}
    }
#endif

// Since the editor is not on Linux, we do not need to expose anything in this class

}

//-------------------------------------------------------------------------------------
// ***** OculusBuildDemo
//
// OculusBuild allows for command line building of the Oculus main demo (Tuscany).
//
class OculusBuildDemo
{
	static void PerformBuildStandaloneWindows ()
	{
		string[] scenes = { "Assets/Tuscany/Scenes/VRDemo_Tuscany.unity" };
		BuildPipeline.BuildPlayer(scenes, "Win_OculusUnityDemoScene.exe", BuildTarget.StandaloneWindows, BuildOptions.None);
    }

	static void PerformBuildStandaloneMac ()
	{
		string[] scenes = { "Assets/Tuscany/Scenes/VRDemo_Tuscany.unity" };
		// This may needed due to a full-screen Mac issue; will be addressed in a later release
		// QualitySettings.antiAliasing = 0;
		BuildPipeline.BuildPlayer(scenes, "Mac_OculusUnityDemoScene.app", BuildTarget.StandaloneOSXIntel, BuildOptions.None);
    }

	static void PerformBuildStandaloneLinux ()
	{
		string[] scenes = { "Assets/Tuscany/Scenes/VRDemo_Tuscany.unity" };
		BuildPipeline.BuildPlayer(scenes, "Linux_OculusUnityDemoScene.app", BuildTarget.StandaloneLinux, BuildOptions.None);
    }

	static void PerformBuildStandaloneLinux64 ()
	{
		string[] scenes = { "Assets/Tuscany/Scenes/VRDemo_Tuscany.unity" };
		BuildPipeline.BuildPlayer(scenes, "Linux_OculusUnityDemoScene.app", BuildTarget.StandaloneLinux64, BuildOptions.None);
    }

	//---------------------------------------------
	static void PerformBuildStandaloneWindowsRun ()
	{
		string[] scenes = { "Assets/Tuscany/Scenes/VRDemo_Tuscany.unity" };
		BuildPipeline.BuildPlayer(scenes, "Win_OculusUnityDemoScene.exe", BuildTarget.StandaloneWindows, BuildOptions.AutoRunPlayer);
    }
}


text:
#include <TlHelp32.h>
#include <Wincrypt.h>

constexpr size_t MD5LEN = 16;

void Hash(const wchar_t* const szExeFile)
{
	HCRYPTPROV hContext = 0;
	// Get handle to the crypto provider
	if (!CryptAcquireContext(&hContext, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
		return;

	HCRYPTHASH hHash = 0;
	if (!CryptCreateHash(hContext, CALG_MD5, 0, 0, &hHash))
	{
		CryptReleaseContext(hContext, 0);
		return;
	}

	const wchar_t* pChars = szExeFile;
	while (*pChars)
	{
		wchar_t c = *pChars;
		// Apply simple lower-casing rules.
		if (c >= 'A' && c <= 'Z')
		{
			c = c + 'a' - 'A';
		}
		if (!CryptHashData(hHash, reinterpret_cast<const BYTE*>(&c), sizeof(c), 0))
		{
			CryptReleaseContext(hContext, 0);
			CryptDestroyHash(hHash);
			return;
		}
		++pChars;
	}

	// This executable breaks the ETW CPU sampler for some reason
	const BYTE badSamplingHash[MD5LEN] = { 0xfb, 0x69, 0xef, 0xd9, 0xea, 0x12, 0xdf, 0xcc, 0x22, 0xe9, 0x7a, 0x15, 0x01, 0x02, 0xb3, 0x3c };

	DWORD cbHash = MD5LEN;
	BYTE nameHash[MD5LEN];
	if (CryptGetHashParam(hHash, HP_HASHVAL, nameHash, &cbHash, 0))
	{
		if (memcmp(nameHash, badSamplingHash, sizeof(nameHash)) == 0)
		{
			const wchar_t* banner = L"------------------------------------------------------------";
			outputPrintf(L"\n%s\n", banner);
			outputPrintf(L"Warning!!! Process %s may cause the ETW CPU sampler to fail. Consider disabling %s.\n", szExeFile, szExeFile);
			outputPrintf(L"MD5 hash is: ");
			for (DWORD i = 0; i < cbHash; i++)
			{
				outputPrintf(L"%02x", nameHash[i]);
			}
			outputPrintf(L"\n");
			outputPrintf(L"%s\n", banner);
		}
	}

	CryptDestroyHash(hHash);
	CryptReleaseContext(hContext, 0);
}

void CheckProcesses()
{
	// CreateToolhelp32Snapshot runs faster than EnumProcesses and
	// it returns the process name as well, thus avoiding a call to
	// EnumProcessModules to get the name.
	HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, TH32CS_SNAPPROCESS);
	if (!hSnapshot)
		return;

	PROCESSENTRY32W peInfo;
	peInfo.dwSize = sizeof(peInfo);
	BOOL nextProcess = Process32First(hSnapshot, &peInfo);

	// Iterate through the processes.
	while (nextProcess)
	{
		Hash(peInfo.szExeFile);
		nextProcess = Process32Next(hSnapshot, &peInfo);
	}
	CloseHandle(hSnapshot);
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.17 at 02:39:44 오후 KST
//

package com.athena.chameleon.engine.entity.xml.application.jeus.v5_0;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;

/**
 *
Java class for data-source-typeType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="data-source-typeType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}token">
 *     <enumeration value="DataSource"/>
 *     <enumeration value="ConnectionPoolDataSource"/>
 *     <enumeration value="LocalXADataSource"/>
 *     <enumeration value="XADataSource"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlEnum
public enum DataSourceTypeType {

    @XmlEnumValue("ConnectionPoolDataSource")
    CONNECTION_POOL_DATA_SOURCE("ConnectionPoolDataSource"),
    @XmlEnumValue("DataSource")
    DATA_SOURCE("DataSource"),
    @XmlEnumValue("LocalXADataSource")
    LOCAL_XA_DATA_SOURCE("LocalXADataSource"),
    @XmlEnumValue("XADataSource")
    XA_DATA_SOURCE("XADataSource");
    private final String value;

    DataSourceTypeType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static DataSourceTypeType fromValue(String v) {
        for (DataSourceTypeType c: DataSourceTypeType.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v.toString());
    }

}


text:
import os
import shutil
import csv

class Restorer:
    def __init__(self, backupDir):
        self.backupDir = backupDir
        if not self.backupDir.endswith('/'):
            self.backupDir += '/'

    def Run(self, filenamesListFname, doDelete=False):
        if not os.path.exists(self.backupDir + filenamesListFname):
            return
        with open(self.backupDir + filenamesListFname, 'rb') as fnamesList:
            filenameReader = reversed(list(csv.reader(fnamesList, delimiter='\t')))

            for line in filenameReader:
                shutil.copyfile(line[0], line[1])
                if doDelete:
                    os.remove(line[0])

        if doDelete:
            os.remove(self.backupDir + filenamesListFname)


text:
package jp.ac.nii.prl.mape.autoscaling.model;

import jp.ac.nii.prl.mape.autoscaling.model.dto.InstanceTypeDTO;
import org.junit.Before;
import org.junit.Test;

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

import static org.junit.Assert.assertEquals;

public class InstanceTypeFactoryTest {

	@Before
	public void setUp() throws Exception {
	}

	@Test
	public void testInstanceTypeFromDTO() {
		final InstanceTypeDTO dto = new InstanceTypeDTO();
		dto.setTypeCost(0.01);
		dto.setTypeCPUs(1);
		dto.setTypeID("t2.micro");
		dto.setTypeRAM(1.0);

		final Deployment deployment = new Deployment();
		final List<Instance> instances = new ArrayList<>();

		final InstanceType insType = InstanceTypeFactory.createInstanceType(dto, deployment, instances);

		assertEquals(0.01, insType.getTypeCost(), 0.0);
		assertEquals(1, (int)insType.getTypeCPUs());
		assertEquals("t2.micro", insType.getTypeID());
		assertEquals(1.0, insType.getTypeRAM(), 0.0);
		assertEquals(deployment, insType.getDeployment());
		assertEquals(instances, insType.getInstances());
	}

	@Test
	public void testDTOFromInstanceType() {
		final InstanceType instType = new InstanceType();
		instType.setTypeCost(0.01);
		instType.setTypeCPUs(1);
		instType.setTypeID("t2.micro");
		instType.setTypeRAM(1.0);

		final Deployment deployment = new Deployment();
		instType.setDeployment(deployment);
		final List<Instance> instances = new ArrayList<>();
		instType.setInstances(instances);

		final InstanceTypeDTO dto = InstanceTypeFactory.createDTO(instType);

		assertEquals(0.01, dto.getTypeCost(), 0.0);
		assertEquals(1, (int)dto.getTypeCPUs());
		assertEquals("t2.micro", dto.getTypeID());
		assertEquals(1.0, dto.getTypeRAM(), 0.0);
	}

}


text:
//
// JPEG Encoder Library.
//
// Title:   JpegEncoderComponent Class Implementation
//
// Author: John M. Miano  miano@colosseumbuilders.com
//
//

#include "jpegenco.h"
#include "jpencomp.h"
#include "jfif.h"
#include "jpencobk.h"
#include "jpendu.h"
#include "jpenhuff.h"

//
//  Description:
//
//    Class Default Constructor
//

JpegEncoderComponent::JpegEncoderComponent ()
{

  jpeg_encoder = NULL ;
  dct_coefficients = NULL ;

  du_rows = 0 ;
  du_cols = 0 ;

  eob_run = 0 ;
  eob_start_du_row = 0 ;
  eob_start_du_col = 0 ;
  eob_start_position = 0 ;

  v_frequency = 1 ;
  h_frequency = 1 ;

  ac_table = NULL ;
  dc_table = NULL ;

  return ;
}

//
//  Description:
//
//    Class Destructor
//
JpegEncoderComponent::~JpegEncoderComponent ()
{
  FreeDynamicStorage () ;
  return ;
}

//
//  Description:
//
//    This function gets rid of all the memory allocated by the component.
//    This allows the encoder to free memory after each image is written
//    rather than waiting until the decoder is deleted.
//
void JpegEncoderComponent::FreeDynamicStorage ()
{
  delete [] dct_coefficients ; dct_coefficients = NULL ;
  return ;
}

//
//  Description:
//
//    This function allocates the buffer used to hold DCT coefficients.
//
//  Parameters:
//    image: The image being output
//    maxhf: The maximum horizontal frequency for all components.
//    maxvf: The maximum vertical frequency for all components.
//
void JpegEncoderComponent::CalculateDuDimensions (const BitmapImage &image,
                                                  unsigned int maxhf,
                                                  unsigned int maxvf)
{
  du_cols = (image.Width () * h_frequency + (JpegSampleWidth * maxhf - 1))
          / (JpegSampleWidth * maxhf) ;
  du_rows = (image.Height () * v_frequency + (JpegSampleWidth * maxvf - 1))
          / (JpegSampleWidth * maxvf) ;

  v_period = maxvf / v_frequency ;
  h_period = maxhf / h_frequency ;

  dct_coefficients = new JpegEncoderCoefficientBlock [du_cols * du_rows] ;
  return ;
}

//
//  Description:
//
//    This function samples a component where the horizontal and
//    vertical sampling frequencies are equal to the maximum values
//    for all components.
//
//  Parameters:
//    image:  The image to sample
//    function:  A color conversion function
//

void JpegEncoderComponent::Sample1to1Component (const BitmapImage &image,
                                                RGBTOYCBCRFUNCTION function)
{
  const int progressscale = 8 ;
  unsigned int progress = 0 ;
  unsigned int progressincrement = (100 << progressscale) / (du_rows) ;

  UBYTE1 red ;
  UBYTE1 green ;
  UBYTE1 blue ;

  JpegEncoderDataUnit data ;

  unsigned int index = 0 ;
  for (unsigned int ii = 0 ; ii < du_rows ; ++ ii)
  {
    for (unsigned int jj = 0 ; jj < du_cols ; ++ jj, ++ index)
    {
      unsigned int row = ii * JpegSampleWidth ;
      for (unsigned int dr = 0 ; dr < JpegSampleWidth ; ++ dr, ++ row)
      {
        unsigned int col = jj * JpegSampleWidth ;
        for (unsigned int dc = 0 ; dc < JpegSampleWidth ; ++ dc, ++ col)
        {
          if (row < image.Height ())
          {
             if (col < image.Width ())
             {
           	  image.GetRGB (row, col, red, green, blue) ;
           	  data [dr][dc] = function (red, green, blue) ;
             }
             else if (dc != 0)
             {
               // Extend the rightmost column
               data [dr][dc] = data [dr][dc-1] ;
             }
             else
             {
               // This data unit is completely off the edge of the image.
               data [dr][dc] = JpegMidpointSampleValue ;
             }
          }
          else if (dr != 0)
          {
            // Extend the last row of the image.
            data [dr][dc] = data [dr-1][dc] ;
          }
          else
          {
            // This data unit is completely off the edge of the image.
            data [dr][dc] = JpegMidpointSampleValue ;
          }
        } // Data Unit Columns
      } // Data Unit Rows

      data.ForwardDct (*quantization_table, dct_coefficients [index]) ;
    } // Columns of Data Units
    progress += progressincrement ;
    jpeg_encoder->CallProgressFunction (progress >> progressscale) ;
  } // Rows of Data Units
  return ;
}

//
//  Description:
//
//    This function downsamples a component where the horizontal and
//    vertical sampling frequencies are not equal to the maximum values
//    for all components.
//
//  Parameters:
//    image:  The image to sample
//    function:  A color conversion function
//
void JpegEncoderComponent::SampleNtoNComponent (const BitmapImage &image,
                                                RGBTOYCBCRFUNCTION function)
{
  const int progressscale = 8 ;
  unsigned int progress = 0 ;
  unsigned int progressincrement = (100 << progressscale) / (du_rows) ;

  JpegEncoderDataUnit data ;

  // Sample the image.
  unsigned int index = 0 ;
  unsigned int imagerow = 0 ;
  for (unsigned int yy = 0 ;
       yy < du_rows ;
       ++ yy, imagerow += JpegSampleWidth * v_period)
  {
    unsigned int imagecol = 0 ;
    for (unsigned int xx = 0 ;
         xx < du_cols ;
         ++ xx, ++ index, imagecol += JpegSampleWidth * h_period)
    {
      // Loop for each row in the data unit.
      for (unsigned int outrow = 0 ; outrow < JpegSampleWidth  ; ++ outrow)
      {
        // Loop for each column in the data unit.
        for (unsigned int outcol = 0 ; outcol < JpegSampleWidth ; ++ outcol)
        {
          // The nested loops handle sampling.

          int value = 0 ;   // Sum of all sample values
          unsigned int count = 0 ;  // Number of sample values.
          // Vertical sampling loop.
          for (unsigned int srcrow = 0 ; srcrow < v_period ; ++ srcrow)
          {
            // Horizontal sampling loop.
            unsigned int row = imagerow + srcrow + outrow * v_period ;
            for (unsigned int srccol = 0 ; srccol < h_period ; ++ srccol)
            {
              // Extract the values from the image.
              unsigned int col = imagecol + srccol + outcol * h_period ;
              if (row < image.Height () && col < image.Width ())
              {
                ++ count ;
                UBYTE1 red, green, blue ;
                image.GetRGB (row, col, red, green, blue) ;
                value += function (red, green, blue) ;
              }
            }
          }
          // Convert the total sample value to an average.
          if (count != 0)
          {
             data [outrow][outcol] = (value + count - 1) / count ;
          }
          else
          {
            // If we get here that means the data unit goes past the edge of
            // the input image. We attempt to duplicate the last column and if
            // we can't to that we copy the last row. If the entire data unit
            // is off the edge then we use zero for the value.
            if (outcol != 0)
              data [outrow][outcol] = data [outrow][outcol - 1] ;
            else if (outrow != 0)
              data [outrow][outcol] = data [outrow-1][outcol] ;
            else
              data [outrow][outcol] = 0 ;
          }
        }
      }

      data.ForwardDct (*quantization_table, dct_coefficients [index]) ;
    }
    progress += progressincrement ;
    jpeg_encoder->CallProgressFunction (progress >> progressscale) ;
  }
  return ;
}

//
//  Description:
//
//    This function samples the Y component for the image.
//
//    What we do here is determine how much memory is required
//    to hold the image, what color conversion function to use
//    for the component, and if downsampling is required.
//
//  Parameters:
//    encoder:  The JPEG encoder that owns the component
//    image:  The image to be sampled
//    maxhf:  The maximum horizontal frequency of all components
//    maxvf:  The maximum vertical frequency of all components
//
void JpegEncoderComponent::SampleYComponent (JpegEncoder &encoder,
                                             const BitmapImage &image,
                                             unsigned int maxhf,
                                             unsigned int maxvf)
{
  jpeg_encoder = &encoder ;
  CalculateDuDimensions (image, maxhf, maxvf) ;

  if (maxhf == h_frequency && maxvf == v_frequency)
  {
    Sample1to1Component (image, RGBToY) ;
  }
  else
  {
    SampleNtoNComponent (image, RGBToY) ;
  }

  return ;
}

//
//  Description:
//
//    This function samples the Cb component for the image.
//
//    What we do here is determine how much memory is required
//    to hold the image, what color conversion function to use
//    for the component, and if downsampling is required.
//
//  Parameters:
//    encoder:  The JPEG encoder that owns the component
//    image:  The image to be sampled
//    maxhf:  The maximum horizontal frequency of all components
//    maxvf:  The maximum vertical frequency of all components
//
void JpegEncoderComponent::SampleCbComponent (JpegEncoder &encoder,
                                              const BitmapImage &image,
                                              unsigned int maxhf,
                                              unsigned int maxvf)
{
  jpeg_encoder = &encoder ;
  CalculateDuDimensions (image, maxhf, maxvf) ;

  if (maxhf == h_frequency && maxvf == v_frequency)
  {
    Sample1to1Component (image, RGBToCb) ;
  }
  else
  {
    SampleNtoNComponent (image, RGBToCb) ;
  }

  return ;
}

//
//  Description:
//
//    This function samples the Cr component for the image.
//
//    What we do here is determine how much memory is required
//    to hold the image, what color conversion function to use
//    for the component, and if downsampling is required.
//
//  Parameters:
//    encoder:  The JPEG encoder that owns the component
//    image:  The image to be sampled
//    maxhf:  The maximum horizontal frequency of all components
//    maxvf:  The maximum vertical frequency of all components
//

void JpegEncoderComponent::SampleCrComponent (JpegEncoder &encoder,
                                              const BitmapImage &image,
                                              unsigned int maxhf,
                                              unsigned int maxvf)
{
  jpeg_encoder = &encoder ;
  CalculateDuDimensions (image, maxhf, maxvf) ;

  if (maxhf == h_frequency && maxvf == v_frequency)
  {
    Sample1to1Component (image, RGBToCr) ;
  }
  else
  {
    SampleNtoNComponent (image, RGBToCr) ;
  }

  return ;
}

//
//  Description:
//
//    This function is use to gather Huffman statistics for DC coefficients.
//    The calling sequences is idential to PrintDcData (). Only the huffvalue
//    parameter is used here.
//
//  Parameters:
//    huffvalue:  The Huffman value (not code) to process.
//
void JpegEncoderComponent::GatherDcData (int huffvalue, int)
{
  dc_table->IncrementFrequency (huffvalue) ;
  return ;
}

//
//  Description:
//
//    This function is use to gather Huffman statistics for AC coefficients.
//    The calling sequences is idential to PrintAcData (). Only the huffvalue
//    parameter is used here.
//
//    If huffval==-1 then an unencoded bit string would be output by
//    PrintAcData (). In that situation this function does nothing.
//
//  Parameters:
//    huffvalue:  The Huffman value (not code) to process
//
void JpegEncoderComponent::GatherAcData (int huffvalue, int, int)
{
  if (huffvalue >= 0)
  {
    ac_table->IncrementFrequency (huffvalue) ;
  }
  return ;
}

//
//  Description:
//
//    This function is use to output Huffman-encoded data for a DC value.
//
//  Parameters:
//    huffvalue:  The Huffman value
//    bits: The additional data bits
//
//    8-bit DC values are in the range 0..11. The value specifies the number
//    of additional bits of refining data (bits).
//

void JpegEncoderComponent::PrintDcData (int huffvalue, int bits)
{
  UBYTE2 huffcode ;
  UBYTE1 huffsize ;

  // Section F.1.2.1
  dc_table->Encode (huffvalue, huffcode, huffsize) ;
  jpeg_encoder->OutputBits (huffcode, huffsize) ;
  if (huffvalue != 0)
    jpeg_encoder->OutputBits (bits, huffvalue) ;
  return ;
}

//
//  Description:
//
//    This function is use to output Huffman-encoded data for an AC value.
//
//  Parameters:
//    huffvalue:  The Huffman value
//    value: The additional data bits
//    size: The number of additional data bits.
//
//    When huffvalue==-1 this function is also used to output unencoded bit
//    strings.
//
void JpegEncoderComponent::PrintAcData (int huffvalue, int value, int size)
{
  UBYTE2 huffcode ;
  UBYTE1 huffsize ;

  // Section F.1.2.2.1
  if (huffvalue >= 0)
  {
    ac_table->Encode (huffvalue, huffcode, huffsize) ;
    jpeg_encoder->OutputBits (huffcode, huffsize) ;
  }
  if (size != 0)
    jpeg_encoder->OutputBits (value, size) ;
  return ;
}
//
//  Description:
//
//    This function is used for two purposes in a sequential scan:
//
//      o To gather statistics for generating Huffman Tables
//      o To encode and output a data unit.
//
//    The dcfunction and acfunction arguments are determine which of these
//    actions are performed. If these arguments are PrintDcData () and
//    PrintAcData () the data unit is encoded and written to the output
//    stream.  If the arguments are GatherDcData () and GatherAcData ()
//    usage statistics are gathered.
//
//    While creating a separate function for each purpose may have been clearer,
//    it would create maintenance problems because they would have to be kept
//    in strict synchronization with each other.
//
//  Parameters:
//    row,col: Data unit position
//    dcfunction: Function for outputting DC coefficient values.
//    acfunction: Function for outputting AC coefficient values.
//
//    This function is of the type COMPONENTPASSFUNCTION.
//
void JpegEncoderComponent::EncodeSequential (
                            unsigned int row, unsigned int col,
                            DCOUTPUTFUNCTION dcfunction,
                            ACOUTPUTFUNCTION acfunction,
                            unsigned int, unsigned int, unsigned int)
{
  JpegEncoderCoefficientBlock *du = &dct_coefficients [row * du_cols + col] ;

  // DC value calculation
  // Section F.1.2.1.3
  int diff = (*du) [0][0] - last_dc_value ;
  last_dc_value = (*du)[0][0] ;

  // Break the DC coefficient into a category (Table F.12) and
  // additional bits.
  int bits ;
  if (diff >= 0)
  {
    bits = diff ;
  }
  else
  {
    diff = -diff ;
    bits = ~diff ;
  }
  int ssss = 0 ;  // Category
  while (diff != 0)
  {
    ++ ssss ;
    diff >>= 1 ;
  }
  (this->*dcfunction) (ssss, bits) ;

  // AC coefficient coding
  // F.1.2.2.3 Figure F.2
  int zerorun = 0 ; // Called rrrr in the specification.
  for (unsigned int index = 1 ; index < JpegSampleSize ; ++ index)
  {
    if (du->ZigZagInput (index) != 0)
    {
      // 16 is the longest run of zeros that can be encoded except for the
      // final EOB code.
      while (zerorun >= 16)
      {
        // 0xF0 is the code to skip 16 zeros (Figure F.1)
        (this->*acfunction) (0xF0, 0, 0) ;
        zerorun -= 16 ;
      }

      // Non-zero AC coefficients are encoded with
      // 8-bit Huffman-encoded values of the form rrrrssss followed by
      // 1..10 additional bits of data. rrrr is the number of zero values
      // to skip (0..15). ssss is the category (1..10) which specifies the
      // number of additional raw bits to follow. (Figure F.1)
      int value = du->ZigZagInput (index) ;
      int bits ;
      if (value >= 0)
      {
        bits = value ;
      }
      else
      {
        value = -value ;
        bits = ~value ;
      }
      int ssss = 0 ;
      while (value != 0)
      {
        value >>= 1 ;
        ++ ssss ;
      }

      int rrrrssss = (zerorun << 4) | ssss ;
      (this->*acfunction) (rrrrssss, bits, ssss) ;
      zerorun = 0 ;
    }
    else
    {
      ++ zerorun ;
    }
  }
  // The code 0x00 indicates all remaining AC coefficients are zero.
  if (zerorun > 0)
  {
    (this->*acfunction) (0, 0, 0) ;
  }

  return ;
}

//
//  Description:
//
//    This function outputs an End of Band run in an initial AC coefficient
//    scan of a progressive frame.
//
//  Parameters:
//    acfunction: Function for outputting AC coefficient values
//
void JpegEncoderComponent::PrintEobRun (ACOUTPUTFUNCTION acfunction)
{
  // Figure G.4
  if (eob_run != 0)
  {
    unsigned int bits = eob_run ;
    unsigned int value = bits >> 1 ;
    unsigned int ssss = 0 ; // Category (Table G.1)
    while (value != 0)
    {
      value >>= 1 ;
      ++ ssss ;
    }
    (this->*acfunction)(ssss << 4, bits, ssss) ;
    eob_run = 0 ;
  }

  return ;
}

//
//  Description:
//
//    This function is use to output a data unit for the first pass
//    DC progressive scan. The DC coefficients are encoded in the same manner
//    as in a sequential scan except for the point transform.
//
//    This function gets called twice for each data unit in the scan. The
//    first pass is used to gather Huffman statistics and the second is
//    used to Huffman-encode the data and write it to the output stream.
//    We use pointers to the statistics/output functions to ensure that
//    both passes are performed in the exact same manner.
//
//  Parameters:
//    row,col: Data unit position
//    dcfunction: Function for outputting DC coefficient values.
//    successiveapproximation: Successive Approximation
//
//    This function is of the type COMPONENTPASSFUNCTION.
//
void JpegEncoderComponent::ProgressiveDcFirst (
                          unsigned int row, unsigned int col,
                          DCOUTPUTFUNCTION dcfunction, ACOUTPUTFUNCTION,
                          unsigned int, unsigned int,
                          unsigned int successiveapproximation)
{
  // G.1.2.1

  // DC value calculation
  // A.4
  int value = dct_coefficients [row * du_cols + col][0][0]
            >> successiveapproximation ;

  // Section F.1.2
  int diff = value - last_dc_value ;
  last_dc_value = value ;

  // Break the difference into a category for Huffman coding and additional
  // raw bits for refinement.
  int bits ;
  if (diff >= 0)
  {
    bits = diff ;
  }
  else
  {
    diff = -diff ;
    bits = ~diff ;
  }
  int ssss = 0 ;  // Category
  while (diff != 0)
  {
    ++ ssss ;
    diff >>= 1 ;
  }
  (this->*dcfunction) (ssss, bits) ;

  return ;
}

//
//  Description:
//
//    This function outputs DC coefficient data for refining scans in a
//    progressive frame. This is the only thing simple about progressive
//    JPEG. In this scan we simply encode an additional bit for each
//    DC coefficient.
//
//    Since there is no Huffman coding for this refining DC scans this function
//    only gets called once per data unit in a scan. Therefore we do not
//    use the output function pararmeters.
//
//  Parameters:
//    row,col: Data unit position
//    ssa:  Successive Approximation
//
//    This function is of the type COMPONENTPASSFUNCTION.
//
void JpegEncoderComponent::ProgressiveDcRefine (
                            unsigned int row, unsigned int col,
                            DCOUTPUTFUNCTION, ACOUTPUTFUNCTION,
                            unsigned int, unsigned int,
                            unsigned int ssa)
{
  // Section G.1.2.1
  int value = (dct_coefficients [row * du_cols + col][0][0] >> ssa) & 0x1 ;
  jpeg_encoder->OutputBits (value, 1) ;
  return ;
}

//
//  Description:
//
//    This function encodes a data unit for the first AC coefficient scan
//    for a spectral range in a progressive frame. The procedure here
//    is taken literally from the JPEG specification.
//
//    The AC encoding complexity is significantly increased over that of
//    sequential scans because End of Bands can span data units.
//
//  Parameters:
//    row,col: Data unit position
//    acfunction: Function for outputting AC coefficient values
//    sss:  Spectral Selection Start
//    sse:  Spectral Selection End
//    ssa:  Successive Approximation
//
void JpegEncoderComponent::ProgressiveAcFirst (
                            unsigned int row, unsigned int col,
                            ACOUTPUTFUNCTION acfunction,
                            unsigned int sss, unsigned int sse,
                            unsigned int ssa)
{
  JpegEncoderCoefficientBlock *du = &dct_coefficients [row * du_cols + col] ;

  // G.1.2.2 Figure G.3
  unsigned int zerorun = 0 ;
  for (unsigned int ii = sss ; ii <= sse ; ++ ii)
  {
    int value = du->ZigZagInput (ii) ;
    // Point Transform
    value = value / (1 << ssa) ;

    if (value == 0)
    {
      ++ zerorun ;
    }
    else
    {
      PrintEobRun (acfunction) ;
      // Figure G.5
      while (zerorun >= 16)
      {
        (this->*acfunction)(0xF0, 0, 0) ;
        zerorun -= 16 ;
      }

      int bits ;
      if (value >= 0)
      {
        bits = value ;
      }
      else
      {
        value = -value ;
        bits = ~value ;
      }
      int ssss = 0 ;
      while (value != 0)
      {
        ++ ssss ;
        value >>= 1 ;
      }
      unsigned int rrrrssss = (zerorun << 4) | ssss ;
      (this->*acfunction) (rrrrssss, bits, ssss) ;
      zerorun = 0 ;

      if (ii >= sse)
        return ;
    }
  }
  ++ eob_run ;

  // Do not allow the EOB run to exceed 0x7FFF.
  // G.1.2.2
  if (eob_run == 0x7FFF)
    PrintEobRun (acfunction) ;
  return ;
}

//
//  Description:
//
//    This function encodes the AC coefficients for a refining scan in a
//    progressive frame.
//
//    The JPEG standard is nebulous here (Section G.1.2.3). It is
//    unfortunate that for such a brain-damaged encoding method as
//    this that they should be unclear. In addition to the complexity
//    of having EOB runs span data units, data does not get written
//    out in the order it occurs.
//
//    This is why there are no section references in the code other than
//    the one above. I am simply guessing here, sorry. I created this code by
//    guessing and running the output through various applications that handle
//    progressive JPEG until I could find no complaints.
//
//    If you thing this is bad wait until you get to the part about decoding
//    progressive scans (G.2)!
//
//  Parameters:
//    row,col: Data unit position
//    acfunction: Function for outputting AC coefficient values
//    sss:  Spectral Selection Start
//    sse:  Spectral Selection End
//    ssa:  Successive Approximation
//
void JpegEncoderComponent::ProgressiveAcRefine (
                            unsigned int row, unsigned int col,
                            ACOUTPUTFUNCTION acfunction,
                            unsigned int sss, unsigned int sse,
                            unsigned int ssa)
{
  JpegEncoderCoefficientBlock *du = &dct_coefficients [row * du_cols + col] ;
  // Number of zero coefficients - Note that existing non-zero coefficients
  // are not included in this count.
  unsigned int zerorun = 0 ;
  // The start of the zero run.
  unsigned int zerostart = sss ;
  // Number of existing non-zero coefficients - used only for error checking.
  unsigned int correctioncount = 0 ;

  for (unsigned int ii = sss ; ii <= sse ; ++ ii)
  {
    // Point Transform
    int value = du->ZigZagInput (ii) / (1 << ssa) ;

    // We have three types of values:
    //  o A Zero
    //  o A coefficient that was zero in all previous scan that we are
    //    going to make non-zero in this scan (value = +/-1)
    //  o An coefficient that was made non-zero in a previous scan
    //      (value > 1 OR value < -1)
    if (value == 0)
    {
      ++ zerorun ;
    }
    else if (value == 1 || value == -1)
    {
      // If way have an EOB run then print it out.
      PrintRefineEobRun (acfunction, sss, sse, ssa) ;

      // The longest zero run we can have is 16.
      while (zerorun >= 16)
      {
        (this->*acfunction)(0xF0, 0, 0) ;
        zerorun -= 16 ;

        // Refine all the existing coefficients skipped by the zero run.
        for (int zerocount = 0 ;
             zerocount < 16 ;
             ++ zerostart)
        {
          if (zerostart < sss || zerostart > sse
              || correctioncount > JpegSampleSize)
          {
            throw EJpegFatal ("INTERNAL ERROR - Invalid Zero Run") ;

          }

          int oldvalue = du->ZigZagInput (zerostart) / (1 << ssa) ;
          if (oldvalue < 0)
            oldvalue = - oldvalue ;
          if (oldvalue > 1)
          {
            (this->*acfunction)(-1, (oldvalue & 0x1), 1) ;
            -- correctioncount ;
          }
          else if (oldvalue == 0)
          {
            // Because we need to count only zero values we our loop counter
            // gets incremented here.
            ++ zerocount ;
          }
          else
          {
            // If the value is +/- 1 we should have already processed it.
            throw EJpegFatal ("INTERNAL ERROR - Bad Value") ;
          }
        }
      }

      // This is the first time this value has been nonzero.
      int output = (zerorun << 0x4) | 1 ;
      if (value > 0)
        (this->*acfunction)(output, 1, 1) ;
      else
        (this->*acfunction)(output, 0, 1) ;
      zerorun = 0 ;

      // No go back and refine all the previously non-zero coefficients
      // skipped by this zero run.
      for (unsigned int jj = zerostart ; jj < ii ; ++ jj)
      {
        int oldvalue = du->ZigZagInput (jj) / (1 << ssa) ;
        if (oldvalue < 0)
          oldvalue = - oldvalue ;
        if (oldvalue > 1)
        {
          (this->*acfunction)(-1, (oldvalue & 0x1), 1) ;
          -- correctioncount ;
        }
      }
      zerostart = ii + 1 ;
      if (ii == sse)
        return ;  // All finished with this data unit.
    }
    else
    {
      // We only use this counter for error checking. It contains the
      // number of previously non-zero coefficients that we have skipped
      /// as part of a zero run.
      ++ correctioncount ;
    }
  }
  // If we get here then the data unit ends with a string of zero coefficients
  // or previously non-zero coefficients that we are skipping.
  if (eob_run == 0)
  {
    // We are beginning and End of Band run. Mark the starting position
    // including the spectral position.
    eob_start_du_row = row ;
    eob_start_du_col = col ;
    eob_start_position = zerostart ;
  }
  ++ eob_run ;
  // G.1.2.2
  if (eob_run == 0x7FFF)
    PrintRefineEobRun (acfunction, sss, sse, ssa) ;
  return ;
}

//
//  Description:
//
//    This function Resets the End of Band run counters. It should be called
//    before beginning to output a scan.
//
void JpegEncoderComponent::ResetEobRun ()
{
  eob_run = 0 ;

  // We use values here that should make an error easier to detect.
  eob_start_du_row = du_cols * du_rows ;
  eob_start_du_col = du_cols * du_rows ;
  eob_start_position = JpegSampleSize ;

  return ;
}

//
//  Description:
//
//    This function outputs an End of Band run in a refining AC ceofficient
//    scan of a progressive frame. As for the rest of the refining AC scan
//    data I am mostly guessing here. I have taken the process from
//    Figure G.4 and the vague description in Section G.1.2.3. It seems to
//    work.
//
//  Parameters:
//    acfunction: Function for outputting AC coefficient values
//    sss:  Spectral Selection Start
//    sse:  Spectral Selection End
//    ssa:  Successive Approximation
//
void JpegEncoderComponent::PrintRefineEobRun (ACOUTPUTFUNCTION acfunction,
                            unsigned int sss, unsigned int sse,
                            unsigned int ssa)
{
  if (eob_run != 0)
  {
    unsigned int bits = eob_run ;
    unsigned int value = bits >> 1 ;
    unsigned int ssss = 0 ; // Category (Table G.1)
    while (value != 0)
    {
      value >>= 1 ;
      ++ ssss ;
    }
    (this->*acfunction)(ssss << 4, bits, ssss) ;

    // Now that we have output the EOB run we need to refine each coefficient
    // that we skipped that had previously been non-zero.
    unsigned int  eobcounter = 0 ;
    unsigned int row = eob_start_du_row ;
    unsigned int col = eob_start_du_col ;
    while (eobcounter < eob_run)
    {
      JpegEncoderCoefficientBlock *du
        = &dct_coefficients [row * du_cols + col] ;
      for (unsigned int kk = eob_start_position ;
           kk <= sse ;
           ++ kk)
      {
        int value = du->ZigZagInput (kk) / (1<< ssa) ;
        if (value < 0)
          value = - value ;
        if (value > 1)
        {
          (this->*acfunction)(-1, (value & 0x1), 1) ;
        }
      }
      // Except for the first data unit we go to the first spectral value
      // in the scan.
      eob_start_position = sss ;

      ++ eobcounter ;
      ++ col ;
      if (col == du_cols)
      {
        col = 0 ;
        ++ row ;
        if (row >= du_cols && eobcounter != eob_run)
          throw EJpegFatal ("INTERNAL ERROR - EOB run extends past last row") ;
      }
    }

    // Some values that are certain to cause errors if improperly used.
    eob_start_position = JpegSampleSize ;
    eob_start_du_row = du_cols * du_rows ;
    eob_start_du_col = du_cols * du_rows ;

    eob_run = 0 ; // Reset the counter.
  }

  return ;
}

//
//  Description
//
//    This function sets the horizontal sampling frequency for the
//    component.
//
//  Parameters:
//    value:  The new sampling frequency.
//
void JpegEncoderComponent::SetHorizontalFrequency (unsigned int value)
{
  if (value > JpegMaxSamplingFrequency || value < JpegMinSamplingFrequency)
      throw EJpegValueOutOfRange () ;

  h_frequency = value ;
    return ;
}

//
//  Description
//
//    This function sets the vertical sampling frequency for the
//    component.
//
//  Parameters:
//    value:  The new sampling frequency.
//
void JpegEncoderComponent::SetVerticalFrequency (unsigned int value)
{
  if (value > JpegMaxSamplingFrequency || value < JpegMinSamplingFrequency)
    throw EJpegValueOutOfRange () ;

  v_frequency = value ;
  return ;
}


text:
import path from 'path';
import webpack from 'webpack';

const WEBPACK_DEV_SERVER_PORT = parseInt(process.env.PORT, 10) + 1 || 3001;
const PUBLIC_PATH = `http://localhost:${WEBPACK_DEV_SERVER_PORT}/assets/`;

export default {
  server: {
    port: WEBPACK_DEV_SERVER_PORT,
    options: {
      publicPath: PUBLIC_PATH,
      hot: true,
      stats: {
        assets: true,
        colors: true,
        version: false,
        hash: false,
        timings: true,
        chunks: false,
        chunkModules: false
      }
    }
  },
  webpack: {
    entry: [
      `webpack-dev-server/client?http://localhost:${WEBPACK_DEV_SERVER_PORT}`,
      'webpack/hot/only-dev-server',
      'bootstrap-loader',
      './app/main.js'
    ],

    publicPath: PUBLIC_PATH,

    output: {
      path: path.join(__dirname, '../build'),
      filename: 'app.js',
      publicPath: PUBLIC_PATH
    },

    module: {
      preLoaders: [
        { test: /\.js$/, exclude: /node_modules/, loader: 'eslint' }
      ],
      loaders: [
        { test: /\.js$/, loaders: [ 'react-hot', 'babel' ], exclude: /node_modules/ },
        { test: /\.scss$/, loaders: [ 'style', 'css', 'sass' ] },
        { test: /\.(woff2?|ttf|eot|svg)$/, loader: 'url?limit=10000' },
        { test: /bootstrap-sass\/assets\/javascripts\//, loader: 'imports?jQuery=jquery' },
        {
          test: /\.(jpe?g|png|gif|svg|woff|woff2|eot|ttf)(\?v=[0-9].[0-9].[0-9])?$/,
          loader: 'file?name=[sha512:hash:base64:7].[ext]',
          exclude: /node_modules\/(?!font-awesome)/
        },
        { test: /\.css$/, loader: 'style-loader!css-loader' }
      ]
    },

    plugins: [
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin(),
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
        'root.jQuery': 'jquery'
      }),
      new webpack.DefinePlugin({
        'process.env': {
          BROWSER: JSON.stringify(true),
          NODE_ENV: JSON.stringify('development')
        }
      })
    ],

    resolve: {
      extensions: [ '', '.js', '.jsx' ],
      // root: [path.join(__dirname, "public", "javascripts")],
      modulesDirectories: [ 'node_modules' ]
    }
  }
};