text:
import type { DropTarget } from 'dnd-core';
import type { DropTargetMonitor } from '../../types/index.js';
import type { DropTargetHookSpec } from '../types.js';
export declare class DropTargetImpl<O, R, P> implements DropTarget {
    spec: DropTargetHookSpec<O, R, P>;
    private monitor;
    constructor(spec: DropTargetHookSpec<O, R, P>, monitor: DropTargetMonitor<O, R>);
    canDrop(): boolean;
    hover(): void;
    drop(): R | undefined;
}


text:
require 'spec_helper'

RSpec.describe IssueSerializer do
  let_it_be(:resource) { create(:issue) }
  let_it_be(:user) { create(:user) }

  let(:json_entity) do
    described_class.new(current_user: user)
      .represent(resource, serializer: serializer)
      .with_indifferent_access
  end

  context 'non-sidebar issue serialization' do
    let(:serializer) { nil }

    it 'matches issue json schema' do
      expect(json_entity).to match_schema('entities/issue')
    end
  end

  context 'sidebar issue serialization' do
    let(:serializer) { 'sidebar' }

    it 'matches issue_sidebar json schema' do
      expect(json_entity).to match_schema('entities/issue_sidebar')
    end
  end

  context 'sidebar extras issue serialization' do
    let(:serializer) { 'sidebar_extras' }

    it 'matches issue_sidebar_extras json schema' do
      expect(json_entity).to match_schema('entities/issue_sidebar_extras')
    end
  end

  context 'board issue serialization' do
    let(:serializer) { 'board' }

    it 'matches board issue json schema' do
      expect(json_entity).to match_schema('entities/issue_board')
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.alibaba.otter.canal.client.running;

import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang.math.RandomUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.alibaba.otter.canal.client.impl.running.ClientRunningData;
import com.alibaba.otter.canal.client.impl.running.ClientRunningListener;
import com.alibaba.otter.canal.client.impl.running.ClientRunningMonitor;
import com.alibaba.otter.canal.common.utils.AddressUtils;
import com.alibaba.otter.canal.common.zookeeper.ZkClientx;
import com.alibaba.otter.canal.common.zookeeper.ZookeeperPathUtils;

public class ClientRunningTest extends AbstractZkTest {

    private ZkClientx zkclientx = new ZkClientx(cluster1 + ";" + cluster2);
    private short     clientId  = 1001;

    @Before
    public void setUp() {
        String path = ZookeeperPathUtils.getDestinationPath(destination);
        zkclientx.deleteRecursive(path);

        zkclientx.createPersistent(ZookeeperPathUtils.getClientIdNodePath(this.destination, clientId), true);
    }

    @After
    public void tearDown() {
        String path = ZookeeperPathUtils.getDestinationPath(destination);
        zkclientx.deleteRecursive(path);
    }

    @Test
    public void testOneServer() {
        final CountDownLatch countLatch = new CountDownLatch(2);
        ClientRunningMonitor runningMonitor = buildClientRunning(countLatch, clientId, 2088);
        runningMonitor.start();
        sleep(2000L);
        runningMonitor.stop();
        sleep(2000L);

        if (countLatch.getCount() != 0) {
            Assert.fail();
        }
    }

    @Test
    public void testMultiServer() {
        final CountDownLatch countLatch = new CountDownLatch(30);
        final ClientRunningMonitor runningMonitor1 = buildClientRunning(countLatch, clientId, 2088);
        final ClientRunningMonitor runningMonitor2 = buildClientRunning(countLatch, clientId, 2089);
        final ClientRunningMonitor runningMonitor3 = buildClientRunning(countLatch, clientId, 2090);
        final ExecutorService executor = Executors.newFixedThreadPool(3);
        executor.submit(new Runnable() {

            public void run() {
                for (int i = 0; i < 10; i++) {
                    if (!runningMonitor1.isStart()) {
                        runningMonitor1.start();
                    }
                    sleep(2000L + RandomUtils.nextInt(500));
                    if (runningMonitor1.check()) {
                        runningMonitor1.stop();
                    }
                    sleep(2000L + RandomUtils.nextInt(500));
                }
            }

        });

        executor.submit(new Runnable() {

            public void run() {
                for (int i = 0; i < 10; i++) {
                    if (!runningMonitor2.isStart()) {
                        runningMonitor2.start();
                    }
                    sleep(2000L + RandomUtils.nextInt(500));
                    if (runningMonitor2.check()) {
                        runningMonitor2.stop();
                    }
                    sleep(2000L + RandomUtils.nextInt(500));
                }
            }

        });

        executor.submit(new Runnable() {

            public void run() {
                for (int i = 0; i < 10; i++) {
                    if (!runningMonitor3.isStart()) {
                        runningMonitor3.start();
                    }
                    sleep(2000L + RandomUtils.nextInt(500));
                    if (runningMonitor3.check()) {
                        runningMonitor3.stop();
                    }
                    sleep(2000L + RandomUtils.nextInt(500));
                }
            }

        });

        sleep(30000L);
    }

    private ClientRunningMonitor buildClientRunning(final CountDownLatch countLatch, final short clientId,
                                                    final int port) {
        ClientRunningData clientData = new ClientRunningData();
        clientData.setClientId(clientId);
        clientData.setAddress(AddressUtils.getHostIp());

        ClientRunningMonitor runningMonitor = new ClientRunningMonitor();
        runningMonitor.setDestination(destination);
        runningMonitor.setZkClient(zkclientx);
        runningMonitor.setClientData(clientData);
        runningMonitor.setListener(new ClientRunningListener() {

            public InetSocketAddress processActiveEnter() {
                System.out.println(String.format("clientId:%s port:%s has start", clientId, port));
                countLatch.countDown();
                return new InetSocketAddress(AddressUtils.getHostIp(), port);
            }

            public void processActiveExit() {
                countLatch.countDown();
                System.out.println(String.format("clientId:%s port:%s has stop", clientId, port));
            }

        });
        runningMonitor.setDelayTime(1);
        return runningMonitor;
    }
}


text:
package kien.lmbseditor.window;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;

import kien.lmbseditor.core.EditorProperty;
import kien.util.KienLogger;
import net.miginfocom.swing.MigLayout;
import javax.swing.JCheckBox;

public class EditorPreferencesWindow extends JDialog {

	/**
	 *
	 */
	private static final long serialVersionUID = 1765234494439106077L;
	private final JPanel contentPanel = new JPanel();
	private JTextField textField;
	private JCheckBox useMinifiedJsonCheckBox;

	/**
	 * Create the dialog.
	 */
	public EditorPreferencesWindow() {
		setModal(true);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		setTitle("Preferences");
		setBounds(new Rectangle(0, 0, 450, 200));
		setResizable(false);
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel
				.setLayout(new MigLayout("", "[70px][70px][30px][70px][30px][70px][75px]", "[1px][21px][1px][21px]"));
		{
			JLabel lblNewLabel = new JLabel("Project Directory");
			contentPanel.add(lblNewLabel, "cell 0 0,alignx left,aligny bottom");
		}
		{
			textField = new JTextField();
			textField.setText(EditorProperty.projectDirectory);
			textField.setEditable(false);
			contentPanel.add(textField, "cell 0 1 6 1,growx,aligny center");
			textField.setColumns(10);
		}
		{
			JButton btnNewButton = new JButton("...");
			btnNewButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					EditorPreferencesWindow.this.onDirectorySetting();
				}
			});
			contentPanel.add(btnNewButton, "cell 6 1,growx,aligny top");
		}
		{
			useMinifiedJsonCheckBox = new JCheckBox("Use Minified Json");
			useMinifiedJsonCheckBox.setToolTipText("When checked, saved json files will be minified.");
			useMinifiedJsonCheckBox.setSelected(EditorProperty.useMinifiedJson);
			contentPanel.add(useMinifiedJsonCheckBox, "cell 0 3");
		}
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("OK");

				okButton.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						EditorPreferencesWindow.this.onOk();
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						EditorPreferencesWindow.this.onCancel();
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
	}

	private void onDirectorySetting() {
		JFileChooser jfc = new JFileChooser();
		jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int ret = jfc.showOpenDialog(this);
		if (ret == -1) {
			KienLogger.logger.severe("Error had occured while choosing directory");
			System.exit(0);
		} else if (ret == 1) {
			return;
		} else {
			File f = jfc.getSelectedFile();
			if (f.exists() && f.isDirectory()) {
				File project = new File(f.getAbsolutePath() + "\\Game.rpgproject");
				if (project.exists()) {
					textField.setText(f.getAbsolutePath());
					return;
				}
			}
			JOptionPane.showConfirmDialog(this, "Not a valid RPG Maker MV project directory.", "Error",
					JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
		}
	}

	private void onOk() {
		if (!EditorPreferencesWindow.this.textField.getText().equals(EditorProperty.projectDirectory)) {
			EditorProperty.setProjectDirectory(this.textField.getText());
		}
		EditorProperty.useMinifiedJson = this.useMinifiedJsonCheckBox.isSelected();
		this.onCancel();
	}

	private void onCancel() {
		this.setVisible(false);
		this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
	}

}


text:
using System.Collections.Generic;

namespace Warmer.Localization
{
    /// <summary>
    /// Represents the english locale
    /// </summary>
    internal class EnglishLocale : LocaleBase
    {
        /// <inheritdoc />
        protected override void Load(IDictionary<string, string> strings)
        {
            strings["About.Contact"] = "Contact: abricot.soinou@gmail.com";
            strings["About.Bugs"] = "Report bugs on https://github.com/Soinou/Warmer/issues";
            strings["Tray.Show"] = "Show";
            strings["Tray.Exit"] = "Exit";
            strings["Tray.About"] = "About";
            strings["Main.On"] = "On";
            strings["Main.Off"] = "Off";
            strings["Main.Temperature"] = "Temperature ({0}K)";
            strings["Main.Interval"] = "Interval ({0}ms)";
            strings["Main.StateTooltip"] = "Enables/Disables the screen warming";
            strings["Main.TemperatureTooltip"] = "Screen 'temperature' (Lower means more red, higher means less red)";
            strings["Main.IntervalTooltip"] = "Interval between two screen gamma updates (Change if you have problems with other applications changing your screen gamma)";
            strings["Restart.Title"] = "Warmer - Info";
            strings["Restart.Message"] = "You should now be able to use screen temperatures lower than 3300K after restarting your computer.";
            strings["Extend.Message"] = "extend the temperature range";
        }
    }
}


text:
package com.siirush.detect.annotation;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target({ METHOD }) @Retention(RUNTIME)
public @interface Support {
	String version();
	String feature() default "";
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class edu.ucsd.sbrg.escher.model.EscherMap (EscherConverter 1.2.0 API)</title>
<meta name="date" content="2019-06-12">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
edu.ucsd.sbrg.escher.model.EscherMap

Packages that use EscherMap

Package
Description

edu.ucsd.sbrg.escher

edu.ucsd.sbrg.escher.converter

Provides converters for Escher JSON to community standards (SBGN, SBML) and vice-versa.

edu.ucsd.sbrg.escher.gui

Classes for the graphical user interface.

edu.ucsd.sbrg.escher.model

Represents model classes for representation of Escher's components.

edu.ucsd.sbrg.escher.util

Provides utility methods, e.g. validation, Jackson mappers, command line options, etc.

Uses of EscherMap in edu.ucsd.sbrg.escher

Methods in edu.ucsd.sbrg.escher that return EscherMap

Modifier and Type
Method and Description

static EscherMap
EscherConverter.convert(org.sbgn.bindings.Sbgn document,
       de.zbit.util.prefs.SBProperties properties)

Calls SBGN-ML to Escher converter.

static EscherMap
EscherConverter.parseEscherJson(File input)

Parses given JSON file into an EscherMap instance using Jackson.

static EscherMap
EscherConverter.parseEscherJson(InputStream stream)

Parses an InputStream that represents an Escher JSON file into an
 EscherMap instance using Jackson.

static EscherMap
EscherConverter.parseSBGNML(File input,
           de.zbit.util.prefs.SBProperties properties)

static EscherMap
EscherConverter.parseSBGNML(InputStream is,
           de.zbit.util.prefs.SBProperties properties)

Parses an SBGNML input and calls a convert method to EscherMap.

Methods in edu.ucsd.sbrg.escher that return types with arguments of type EscherMap

Modifier and Type
Method and Description

static List<EscherMap>
EscherConverter.convert(org.sbml.jsbml.SBMLDocument document,
       de.zbit.util.prefs.SBProperties properties)

Calls SBML Layout Extension to Escher converter.

Methods in edu.ucsd.sbrg.escher with parameters of type EscherMap

Modifier and Type
Method and Description

static <T> T
EscherConverter.convert(EscherMap map,
       Class<? extends T> format,
       de.zbit.util.prefs.SBProperties properties)

Generic method which converts the given EscherMap instance to the specified
 generic parameter format, by calling the corresponding converter.

static void
EscherConverter.writeEscherJson(EscherMap map,
               File output)

Serializes an EscherMap instance to JSON and writes to output file.

Method parameters in edu.ucsd.sbrg.escher with type arguments of type EscherMap

Modifier and Type
Method and Description

static void
EscherConverter.writeEscherJson(List<EscherMap> mapList,
               File output)

Serializes a List<EscherMap> to JSON and writes to output directory.

Uses of EscherMap in edu.ucsd.sbrg.escher.converter

Fields in edu.ucsd.sbrg.escher.converter declared as EscherMap

Modifier and Type
Field and Description

protected EscherMap
SBGN2Escher.escherMap

Output Escher map.

Fields in edu.ucsd.sbrg.escher.converter with type parameters of type EscherMap

Modifier and Type
Field and Description

protected List<EscherMap>
SBML2Escher.escherMaps

List of escher maps converted from the layouts exported from the SBML document.

Methods in edu.ucsd.sbrg.escher.converter that return EscherMap

Modifier and Type
Method and Description

EscherMap
SBGN2Escher.convert(org.sbgn.bindings.Sbgn document)

Converts Sbgn document to EscherMap by iteratively creating nodes,
 reactions, etc.

Methods in edu.ucsd.sbrg.escher.converter that return types with arguments of type EscherMap

Modifier and Type
Method and Description

List<EscherMap>
SBML2Escher.convert(org.sbml.jsbml.SBMLDocument doc)

Converts an SBMLDocument to a list of EscherMaps by iteratively creating nodes,
 reactions, etc.

Methods in edu.ucsd.sbrg.escher.converter with parameters of type EscherMap

Modifier and Type
Method and Description

abstract T
Escher2Standard.convert(EscherMap map)

org.sbml.jsbml.SBMLDocument
Escher2SBML.convert(EscherMap map)

org.sbgn.bindings.Sbgn
Escher2SBGN.convert(EscherMap escherMap)

void
Escher2Standard.preprocessDataStructure(EscherMap escherMap)

Pre-processes every reaction in a data structure

Uses of EscherMap in edu.ucsd.sbrg.escher.gui

Methods in edu.ucsd.sbrg.escher.gui that return types with arguments of type EscherMap

Modifier and Type
Method and Description

protected List<de.zbit.io.OpenedFile<EscherMap>>
EscherParserWorker.doInBackground()

de.zbit.io.OpenedFile<EscherMap>
EscherMapDisplay.getOpenedFile()

Method parameters in edu.ucsd.sbrg.escher.gui with type arguments of type EscherMap

Modifier and Type
Method and Description

protected void
EscherParserWorker.process(List<de.zbit.io.OpenedFile<EscherMap>> chunks)

Constructors in edu.ucsd.sbrg.escher.gui with parameters of type EscherMap

Constructor and Description

EscherConverterWorker(EscherMap map,
                     Class<? extends T> format,
                     de.zbit.util.prefs.SBProperties properties)

Constructor parameters in edu.ucsd.sbrg.escher.gui with type arguments of type EscherMap

Constructor and Description

EscherMapDisplay(de.zbit.io.OpenedFile<EscherMap> openedFile,
                de.zbit.util.prefs.SBProperties properties)

Uses of EscherMap in edu.ucsd.sbrg.escher.model

Methods in edu.ucsd.sbrg.escher.model that return EscherMap

Modifier and Type
Method and Description

EscherMap
EscherMap.clone()

Methods in edu.ucsd.sbrg.escher.model with parameters of type EscherMap

Modifier and Type
Method and Description

Node
EscherReaction.findMidmarker(EscherMap map)

Constructors in edu.ucsd.sbrg.escher.model with parameters of type EscherMap

Constructor and Description

EscherMap(EscherMap escherMap)

Copy constructor.

Uses of EscherMap in edu.ucsd.sbrg.escher.util

Methods in edu.ucsd.sbrg.escher.util that return EscherMap

Modifier and Type
Method and Description

EscherMap
EscherParser.parse(File jsonFile)

Deprecated.

EscherMap
EscherParser.parse(InputStream inputStream,
     String defaultMapId)

Deprecated.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015–2019 University of Tübingen. All rights reserved.


text:
namespace boost {
namespace safe_numerics {

template <
    class T,
    class P = native,
    class E = default_exception_policy
>
using safe = safe_base<
    T,
    ::std::numeric_limits<T>::min(),
    ::std::numeric_limits<T>::max(),
    P,
    E
>;

} // safe_numerics
} // boost

#endif // BOOST_NUMERIC_SAFE_INTEGER_HPP


text:
/**
 *
 */
package model;

import java.util.ArrayList;

/**
 * @author Arkadi Yoskovitz
 */
public class GuessingGame {

	// Attribute
	private final Target gameTarget;
	private ArrayList<Score> 	gameResults;
	private boolean 			active;
	private boolean 			winner;
	private int					limit;

	// Contractor
	public GuessingGame() {
		this.gameTarget = new Target();
		this.gameResults = new ArrayList<Score>();
		this.active = true;
		this.winner = false;
		this.limit = 10;
	}

	// Access Methods
	public Target getGameTarget() {
		return gameTarget;
	}

	public ArrayList<Score> getGameResults() {
		return gameResults;
	}

	public void setGameResults(ArrayList<Score> guessResults) {
		this.gameResults = guessResults;
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}

	public boolean isWinner() {
		return winner;
	}

	public void setWinner(boolean winner) {
		this.winner = winner;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	@Override
	public String toString() {
		StringBuilder result = new StringBuilder();
		String NEW_LINE = System.getProperty("line.separator");
		result.append(this.getClass().getName() + " Object {" + NEW_LINE);
		result.append(gameTarget.toString() + NEW_LINE);
		result.append("Active state: " + isActive() + NEW_LINE);
		result.append("Limit: " + getLimit() + NEW_LINE);
		result.append("Current size: " + getGameResults().size() + NEW_LINE);
		result.append("Guess results: " + NEW_LINE);
		for (Score score : gameResults) {
			result.append(score.toString() + NEW_LINE);
		}
		result.append("}");
		return result.toString();
	}

	// Handling Guess Event
	public void calculateGuessState(String guess) {

		Score newScore = new Score(getGameTarget(),guess);

		getGameResults().add(0,newScore);

		if (newScore.getCountBullsEye() == 4) {
			setActive(false);
		} else if (getGameResults().size() == limit) {
			setActive(false);
		}
	}
}


text:
function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [parameter(Mandatory = $true)]  [System.String]   $ServiceAppName,
        [parameter(Mandatory = $true)]  [System.String[]] $Admin,
        [parameter(Mandatory = $true)]  [System.String[]] $Crawler,
        [parameter(Mandatory = $true)]  [System.String[]] $ContentProcessing,
        [parameter(Mandatory = $true)]  [System.String[]] $AnalyticsProcessing,
        [parameter(Mandatory = $true)]  [System.String[]] $QueryProcessing,
        [parameter(Mandatory = $true)]  [System.String[]] $IndexPartition,
        [parameter(Mandatory = $true)]  [System.String]   $FirstPartitionDirectory,
        [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount
    )

    $result = Invoke-xSharePointCommand -Credential $InstallAccount -Arguments $PSBoundParameters -ScriptBlock {
        $params = $args[0]
        $ConfirmPreference = 'None'

        $ssa = Get-SPEnterpriseSearchServiceApplication -Identity $params.ServiceAppName

        IF ($null -eq $ssa) {
            return $null
        }
        $currentTopology = $ssa.ActiveTopology

        $AdminComponents = (Get-SPEnterpriseSearchComponent -SearchTopology $currentTopology | Where-Object { ($_.GetType().Name -eq "AdminComponent") }).ServerName
        $CrawlComponents = (Get-SPEnterpriseSearchComponent -SearchTopology $currentTopology | Where-Object { ($_.GetType().Name -eq "CrawlComponent") }).ServerName
        $ContentProcessingComponents = (Get-SPEnterpriseSearchComponent -SearchTopology $currentTopology | Where-Object { ($_.GetType().Name -eq "ContentProcessingComponent") }).ServerName
        $AnalyticsProcessingComponents = (Get-SPEnterpriseSearchComponent -SearchTopology $currentTopology | Where-Object { ($_.GetType().Name -eq "AnalyticsProcessingComponent") }).ServerName
        $QueryProcessingComponents = (Get-SPEnterpriseSearchComponent -SearchTopology $currentTopology | Where-Object { ($_.GetType().Name -eq "QueryProcessingComponent") }).ServerName
        $IndexComponents = (Get-SPEnterpriseSearchComponent -SearchTopology $currentTopology | Where-Object { ($_.GetType().Name -eq "IndexComponent") -and ($_.IndexPartitionOrdinal -eq 0) }).ServerName

        return @{
            ServiceAppName = $params.ServiceAppName
            Admin = $AdminComponents
            Crawler = $CrawlComponents
            ContentProcessing = $ContentProcessingComponents
            AnalyticsProcessing = $AnalyticsProcessingComponents
            QueryProcessing = $QueryProcessingComponents
            InstallAccount = $params.InstallAccount
            FirstPartitionDirectory = $params.FirstPartitionDirectory
            IndexPartition = $IndexComponents
        }
    }
    return $result
}

function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]  [System.String]   $ServiceAppName,
        [parameter(Mandatory = $true)]  [System.String[]] $Admin,
        [parameter(Mandatory = $true)]  [System.String[]] $Crawler,
        [parameter(Mandatory = $true)]  [System.String[]] $ContentProcessing,
        [parameter(Mandatory = $true)]  [System.String[]] $AnalyticsProcessing,
        [parameter(Mandatory = $true)]  [System.String[]] $QueryProcessing,
        [parameter(Mandatory = $true)]  [System.String[]] $IndexPartition,
        [parameter(Mandatory = $true)]  [System.String]   $FirstPartitionDirectory,
        [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount
    )

    $CurrentValues = Get-TargetResource @PSBoundParameters

    Invoke-xSharePointCommand -Credential $InstallAccount -Arguments @($PSBoundParameters, $CurrentValues, $PSScriptRoot) -ScriptBlock {
        $params = $args[0]
        $CurrentValues = $args[1]
        $ScriptRoot = $args[2]
        $ConfirmPreference = 'None'

        $AllSearchServers = @()
        $AllSearchServers += ($params.Admin               | Where-Object { $AllSearchServers.Contains($_) -eq $false })
        $AllSearchServers += ($params.Crawler             | Where-Object { $AllSearchServers.Contains($_) -eq $false })
        $AllSearchServers += ($params.ContentProcessing   | Where-Object { $AllSearchServers.Contains($_) -eq $false })
        $AllSearchServers += ($params.AnalyticsProcessing | Where-Object { $AllSearchServers.Contains($_) -eq $false })
        $AllSearchServers += ($params.QueryProcessing     | Where-Object { $AllSearchServers.Contains($_) -eq $false })
        $AllSearchServers += ($params.IndexPartition      | Where-Object { $AllSearchServers.Contains($_) -eq $false })

        # Ensure the search service instance is running on all servers
        foreach($searchServer in $AllSearchServers) {
            $searchService = Get-SPEnterpriseSearchServiceInstance -Identity $searchServer
            if($searchService.Status -eq "Offline") {
                Write-Verbose "Start Search Service Instance"
                Start-SPEnterpriseSearchServiceInstance -Identity $searchServer
            }

            #Wait for Search Service Instance to come online
            $loopCount = 0
            $online = Get-SPEnterpriseSearchServiceInstance -Identity $searchServer
            do {
                $online = Get-SPEnterpriseSearchServiceInstance -Identity $searchServer
                Write-Verbose "Waiting for service: $($online.TypeName)"
                $loopCount++
                Start-Sleep -Seconds 30
            }
            until ($online.Status -eq "Online" -or $loopCount -eq 20)
        }

        # Create the index partition directory on each remote server
        foreach($IndexPartitionServer in $params.IndexPartition) {
            $networkPath = "\\$IndexPartitionServer\" + $params.FirstPartitionDirectory.Replace(":\", "$\")
            New-Item $networkPath -ItemType Directory -Force
        }

        # Create the directory on the local server as it will not apply the topology without it
        if ((Test-Path -Path $params.FirstPartitionDirectory) -eq $false) {
            New-Item $params.FirstPartitionDirectory -ItemType Directory -Force
        }

        # Get all service service instances to assign topology components to
        $AllSearchServiceInstances = @{}
        foreach ($server in $AllSearchServers) {
            $AllSearchServiceInstances.Add($server, (Get-SPEnterpriseSearchServiceInstance -Identity $server))
        }

        # Get current topology and prepare a new one
        $ssa = Get-SPEnterpriseSearchServiceApplication -Identity $params.ServiceAppName
        if ($null -eq $ssa) {
            throw "Search service applications '$($params.ServiceAppName)' was not found"
            return
        }
        $currentTopology = $ssa.ActiveTopology
        $newTopology = New-SPEnterpriseSearchTopology -SearchApplication $ssa -Clone -SearchTopology $currentTopology

        $componentTypes = @{
            Admin = "AdminComponent"
            Crawler = "CrawlComponent"
            ContentProcessing = "ContentProcessingComponent"
            AnalyticsProcessing = "AnalyticsProcessingComponent"
            QueryProcessing = "QueryProcessingComponent"
            IndexPartition = "IndexComponent"
        }

        # Build up the topology changes for each object type
        @("Admin", "Crawler", "ContentProcessing", "AnalyticsProcessing", "QueryProcessing", "IndexPartition")  | ForEach-Object {
            $CurrentSearchProperty = $_
            Write-Verbose "Setting components for '$CurrentSearchProperty' property"

            if ($null -eq $CurrentValues.$CurrentSearchProperty) {
                $ComponentsToAdd = $params.$CurrentSearchProperty
            } else {
                $ComponentsToAdd = @()
                $ComponentsToRemove = @()
                foreach($Component in ($params.$CurrentSearchProperty | Where-Object { $CurrentValues.$CurrentSearchProperty -contains $_ -eq $false })) {
                    $ComponentsToAdd += $Component
                }
                foreach($Component in ($CurrentValues.$CurrentSearchProperty | Where-Object { $params.$CurrentSearchProperty -contains $_ -eq $false })) {
                    $ComponentsToRemove += $Component
                }
            }
            foreach($ComponentToAdd in $ComponentsToAdd) {
                $NewComponentParams = @{
                    SearchTopology = $newTopology
                    SearchServiceInstance = $AllSearchServiceInstances.$ComponentToAdd
                }
                switch($componentTypes.$CurrentSearchProperty) {
                    "AdminComponent" {
                        New-SPEnterpriseSearchAdminComponent @NewComponentParams
                    }
                    "CrawlComponent" {
                        New-SPEnterpriseSearchCrawlComponent @NewComponentParams
                    }
                    "ContentProcessingComponent" {
                        New-SPEnterpriseSearchContentProcessingComponent @NewComponentParams
                    }
                    "AnalyticsProcessingComponent" {
                        New-SPEnterpriseSearchAnalyticsProcessingComponent @NewComponentParams
                    }
                    "QueryProcessingComponent" {
                        New-SPEnterpriseSearchQueryProcessingComponent @NewComponentParams
                    }
                    "IndexComponent" {
                        $NewComponentParams.Add("IndexPartition", 0)
                        if ($params.ContainsKey("FirstPartitionDirectory") -eq $true) {
                            if ([string]::IsNullOrEmpty($params.FirstPartitionDirectory) -eq $false) {
                                $NewComponentParams.Add("RootDirectory", $params.FirstPartitionDirectory)
                            }
                        }
                        New-SPEnterpriseSearchIndexComponent @NewComponentParams
                    }
                }
            }
            foreach($ComponentToRemove in $ComponentsToRemove) {
                if ($componentTypes.$CurrentSearchProperty -eq "IndexComponent") {
                    $component = Get-SPEnterpriseSearchComponent -SearchTopology $newTopology | Where-Object {($_.GetType().Name -eq $componentTypes.$CurrentSearchProperty) -and ($_.ServerName -eq $ComponentToRemove) -and ($_.IndexPartitionOrdinal -eq 0)}
                } else {
                    $component = Get-SPEnterpriseSearchComponent -SearchTopology $newTopology | Where-Object {($_.GetType().Name -eq $componentTypes.$CurrentSearchProperty) -and ($_.ServerName -eq $ComponentToRemove)}
                }
                if ($null -ne $component) {
                    $component | Remove-SPEnterpriseSearchComponent -SearchTopology $newTopology -confirm:$false
                }

            }
        }

        # Apply the new topology to the farm
        Set-SPEnterpriseSearchTopology -Identity $newTopology
    }
}

function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [parameter(Mandatory = $true)]  [System.String]   $ServiceAppName,
        [parameter(Mandatory = $true)]  [System.String[]] $Admin,
        [parameter(Mandatory = $true)]  [System.String[]] $Crawler,
        [parameter(Mandatory = $true)]  [System.String[]] $ContentProcessing,
        [parameter(Mandatory = $true)]  [System.String[]] $AnalyticsProcessing,
        [parameter(Mandatory = $true)]  [System.String[]] $QueryProcessing,
        [parameter(Mandatory = $true)]  [System.String[]] $IndexPartition,
        [parameter(Mandatory = $true)]  [System.String]   $FirstPartitionDirectory,
        [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount
    )

    $CurrentValues = Get-TargetResource @PSBoundParameters
    if ($CurrentValues -eq $null) { return $false }
    return Test-xSharePointSpecificParameters -CurrentValues $CurrentValues `
                                              -DesiredValues $PSBoundParameters `
                                              -ValuesToCheck @(
                                                  "Admin",
                                                  "Crawler",
                                                  "ContentProcessing",
                                                  "AnalyticsProcessing",
                                                  "QueryProcessing",
                                                  "IndexPartition"
                                              )
}

Export-ModuleMember -Function *-TargetResource


text:
using System;
using System.Linq;
using FoodProject.Abstract;
using FoodProject.Models;
using FoodProject.Controllers;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Web;

namespace UnitTest1
{
    [TestClass]
    public class RecipeControllerTest
    {
        // used to set the controller we are testing context's
        public static HttpContextBase FakeHttpContext()
        {
            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var session = new MockHttpSession();
            var server = new Mock<HttpServerUtilityBase>();

            context.Setup(ctx => ctx.Request).Returns(request.Object);
            context.Setup(ctx => ctx.Response).Returns(response.Object);
            context.Setup(ctx => ctx.Session).Returns(session);
            context.Setup(ctx => ctx.Server).Returns(server.Object);

            return context.Object;
        }
        public class MockHttpSession : System.Web.HttpSessionStateBase
        {
            Dictionary<string, object> m_SessionStorage = new Dictionary<string, object>();

            public override object this[string name]
            {
                get { return m_SessionStorage[name]; }
                set { m_SessionStorage[name] = value; }
            }
        }

        // The context each repository is going to get their data from
        class MyContext
        {
            public List<Food> foods { get; set; }
            public List<Pantry> pantrys { get; set; }
            public List<Ingredient>ingredients { get; set; }
            public List<Recipe>recipies { get; set; }
            public MyContext()
            {
                foods = new List<Food>(new Food[] { new Food() { FoodID = 0, Name = "food 0"},
                    new Food() {FoodID = 1, Name = "food 1"},
                    new Food() {FoodID = 2, Name = "food 2"} });
                pantrys = new List<Pantry>(new Pantry[] { new Pantry() { PantryID = 0,FoodID = 0,UserID = 1,Units = 1},
                    new Pantry() { PantryID = 1,FoodID = 1,UserID = 0, Units = 1},
                    new Pantry() { PantryID = 2,FoodID = 2,UserID = 1, Units = 1}});
            }
        }
        class MockIPantryRepository : IPantryRepository
        {
            MyContext c;
            public MockIPantryRepository(MyContext c)
            {
                this.c = c;
            }
            public IEnumerable<Pantry> Pantrys
            {

                get
                {
                    return c.pantrys;
                }
            }

            public void add(Pantry p)
            {
                c.pantrys.Add(p);
            }

            public void delete(int id)
            {
                Pantry p = c.pantrys.Select(x => x).Where(x => x.PantryID == id).First();
                c.pantrys.Remove(p);
                c.pantrys.Select(x => x);
            }

            public void save()
            {
                //save not needed
            }
            public void updatePantry(Pantry p)
            {
                Pantry temp = c.pantrys.Select(x => x).Where(x => x.PantryID == p.PantryID).First();
                temp.Units = p.Units;
            }
        }
        class MockIFoodRepository : IFoodRepository
        {
            private MyContext c;
            public MockIFoodRepository(MyContext c)
            {
                this.c = c;
            }
            public IEnumerable<Food> Foods
            {
                get
                {
                    return c.foods;
                }
            }

            public void DeleteFood(int food)
            {
                Food f = c.foods.Select(x => x).Where(x => x.FoodID == food).First();
                c.foods.Remove(f);
            }

            public void Dispose()
            {
                throw new NotImplementedException();
            }

            public Food GetFoodById(int foodId)
            {
                throw new NotImplementedException();
            }

            public void InsertFood(Food food)
            {
                food.FoodID = c.foods.Count();
                c.foods.Add(food);
                food.FoodID = c.foods.Count();
            }

            public void Save()
            {
                //don't have to save in mock
            }

            public void UpdateFood(Food food)
            {
                Food f = c.foods.Where(x => x.FoodID == food.FoodID).First();
                f.Name = food.Name;

            }
        }
        [TestMethod]
        public void TestMethod1()
        {

        }
    }
}


text:
   This file implements Dynamic K Max Pooling as described in the paper:
   "A Convolutional Neural Network for Modelling Sentences"
                   by Nal Kalchbrenner, Edward Grefenstette, Phil Blunsom

   The operation is simply selecting the k highest values out of a sequence.
   k can be a calculated value or pre-defined

   The value of k can be calulated as in the paper by using:
      k_top as minK
      (L-l)/L as factor

   Where:
      k_top is the desired sequence length at the end of the convolution part,
      L is the total number of layers,
      l is this layers number
]]

local TemporalDynamicKMaxPooling, parent = torch.class('nn.TemporalDynamicKMaxPooling', 'nn.Module')

function TemporalDynamicKMaxPooling:__init(minK, factor)
   parent.__init(self)

   self.minK = minK
   self.factor = factor or 0
end

function TemporalDynamicKMaxPooling:updateOutput(input)
   assert(input:dim() == 2 or input:dim() == 3, 'Only 2D or 3D(batch mode) accepted')

   local seqDim = input:dim()-1
   local k = math.max(self.minK, math.ceil(self.factor*input:size(seqDim)))
   assert(input:size(seqDim) >= self.minK, 'Input sequence length (' .. input:size(seqDim) .. ') too small for desired k value (' .. k .. ')')

   -- Sort input in descending order
   local sorted, allIndices = input:sort(seqDim,true)
   -- Reduce the indices to only include the top-k and return to original order by sorting
   self.indices = allIndices:narrow(seqDim, 1, k):sort(seqDim)

   self.output = input:gather(seqDim, self.indices)

   return self.output
end

function TemporalDynamicKMaxPooling:updateGradInput(input, gradOutput)
   if self.gradInput then
      local seqDim = input:dim()-1

      self.gradInput:resizeAs(input)
      self.gradInput:zero()

      -- Using the previously stored indices, add the gradOutputs to their respective
      -- input indices in the self.gradInput buffer
      local updateValues = self.gradInput:gather(seqDim, self.indices)
      updateValues:add(gradOutput)
      self.gradInput:scatter(seqDim, self.indices, updateValues)

      return self.gradInput
   end
end

function TemporalDynamicKMaxPooling:clearState()
   nn.utils.clear(self, 'indices')
   return parent.clearState(self)
end


text:
import { _ } from 'meteor/underscore';
import CursorMethods from './cursor';
import { DDPServer } from 'meteor/ddp-server';

const crossbar = DDPServer._InvalidationCrossbar;
// designed to paginate a list, works in conjunction with the methods
// do not call back to the main callback, only the array is changed in the collection
CursorMethods.prototype.paginate = function (fieldData, limit, infinite) {
  const sub = this.sub;
  const collection = this.collection;

  if (!this._id || !collection)
    throw new Error("you can't use this method without being within a document");

  const field = Object.keys(fieldData)[0];
  const copy = _.clone(fieldData)[field];
  const max = copy.length;
  const connectionId = sub.connection.id;

  fieldData[field] = copy.slice(0, limit);

  const listener = crossbar.listen({
    collection: 'paginations',
    id: connectionId,
  }, (data) => {
    if (!data.id || data.id !== connectionId) return;

    let skip = data.skip;

    if (skip >= max && !infinite)
      return;

    fieldData[field] = infinite ? copy.slice(0, skip): copy.slice(skip, skip + limit);
    sub.changed(collection, data._id, fieldData);
  });

  this.handler.addBasic(field, listener);

  return fieldData[field];
};

CursorMethods.prototype.listen = function (options, callback, run) {
  const sub = this.sub;
  const name = 'listen-' + this._publicationName;

  const listener = crossbar.listen({
    collection: name,
    id: sub.connection.id
  }, (data) => {
    if (!data.id || data.id !== sub.connection.id) return;

    _.extend(options, _.omit(data, 'collection', 'id'));
    callback(false);
  });

  const handler = this.handler.addBasic(name);

  if (run !== false) callback(true);

  return handler.set(listener);
};


text:
"use strict";

var docblock        = require('jstransform/src/docblock');
// var transform       = require('jstransform').transform;
var mercuryJSX  = require('mercury-jsx').transform;
// var visitors        = require('react-tools/vendor/fbtransform/visitors');
var through         = require('through');

var isJSXExtensionRe = /^.+\.jsx$/;

function parsePragma(data) {
  return docblock.parseAsObject(docblock.extract(data));
}

function process(file, isJSXFile, transformer) {
  transformer = transformer || mercuryJSX;

  var data = '';
  function write(chunk) {
    return data += chunk;
  }

  function compile() {
    // jshint -W040
    var isJSXPragma = parsePragma(data).jsx !== undefined;

    if (isJSXFile || isJSXPragma) {
      if (!isJSXPragma) {
        data = '/** @jsx h */' + data;
      }
      try {
        var transformed = transformer(data);
        this.queue(transformed);
      } catch (error) {
        console.log('error', error.stack);
        error.name = 'ReactifyError';
        error.message = file + ': ' + error.message;
        error.fileName = file;

        this.emit('error', error);
      }
    } else {
      this.queue(data);
    }
    return this.queue(null);
    // jshint +W040
  }

  return through(write, compile);
}

function getExtensionsMatcher(extensions) {
  return new RegExp('\\.(' + extensions.join('|') + ')$');
}

module.exports = function(file, options) {
  options = options || {};

  var isJSXFile;

  if (options.everything) {

    isJSXFile = true;
  } else {

    var extensions = ['jsx']
      .concat(options.extension)
      .concat(options.x)
      .filter(Boolean)
      .map(function(ext) { return ext[0] === '.' ? ext.slice(1) : ext });

    isJSXFile = getExtensionsMatcher(extensions).exec(file);
  }

  // var transformVisitors = [].concat(
  //   options.harmony || options.es6 ?
  //     visitors.getAllVisitors() :
  //     visitors.transformVisitors.react);

  // if (options.visitors) {
  //   [].concat(options.visitors).forEach(function(id) {
  //     transformVisitors = require(id).visitorList.concat(transformVisitors);
  //   });
  // }

  function transformer(source) {
    return mercuryJSX(source)
  }

  return process(file, isJSXFile, transformer);
};
module.exports.process = process;
module.exports.isJSXExtensionRe = isJSXExtensionRe;


text:
import { clone, extend } from 'lodash'
import { mount } from 'enzyme'
import React from 'react'
import configureStore from 'redux-mock-store'
import { Provider } from 'react-redux'
import Backbone from 'backbone'
import { Fixtures } from '@artsy/reaction/dist/Components/Publishing'
import Artwork from '../../../../../../../models/artwork.coffee'
import { SectionControls } from '../../../section_controls'
import { Autocomplete } from '/client/components/autocomplete2'
import { ImagesControls } from '../components/controls'
const { StandardArticle } = Fixtures
require('typeahead.js')

describe('ImagesControls', () => {
  let props
  const artwork = clone(StandardArticle.sections[4].images[2])

  const getWrapper = (props) => {
    const mockStore = configureStore([])
    const store = mockStore({
      app: {
        channel: { type: 'editorial' }
      },
      edit: {
        article: props.article,
        section: props.editSection
      }
    })
    return mount(
      <Provider store={store}>

          <ImagesControls {...props} />

      </Provider>
    )
  }

  const rawArtwork = {
    description: 'Acrylic on glass, 66.3 × 40 × 2.5 cm',
    title: 'Ryan Gander, Please be patient you two',
    type: 'artwork',
    _id: '5698bc71275b2479120000a9',
    _links: {
      self: {href: 'https://stagingapi.artsy.net/api/artworks/5698bc71275b2479120000a9'},
      thumbnail: {href: 'https://d32dm0rphc51dk.cloudfront.net/S8Jb9AX0ickx4qyXjxWPkg/square.jpg'}
    }
  }

  beforeEach(() => {
    props = {
      article: clone(StandardArticle),
      logErrorAction: jest.fn(),
      editSection: clone(StandardArticle.sections[4]),
      sectionIndex: 2,
      setProgress: jest.fn(),
      onChangeHeroAction: jest.fn(),
      onChangeSectionAction: jest.fn(),
      removeSectionAction: jest.fn()
    }

    SectionControls.prototype.isScrollingOver = jest.fn().mockReturnValue(true)
    SectionControls.prototype.isScrolledPast = jest.fn().mockReturnValue(false)
  })

  it('renders all fields', () => {
    const component = getWrapper(props)

    expect(component.find(SectionControls).length).toBe(1)
    expect(component.html()).toMatch('overflow_fillwidth')
    expect(component.html()).toMatch('')
    expect(component.html()).toMatch('column_width')
    expect(component.html()).toMatch('fillwidth')
    expect(component.html()).toMatch('image_set')
    expect(component.html()).toMatch('<input type="file"')
    expect(component.html()).toMatch('placeholder="Search artworks by title..."')
    expect(component.html()).toMatch('placeholder="Add artwork url"')
  })

  it('does not display artwork inputs or layouts if heroSection', () => {
    props.isHero = true
    const component = getWrapper(props)

    expect(component.html()).not.toMatch('class="layout"')
    expect(component.html()).not.toMatch('placeholder="Search for artwork by title"')
    expect(component.html()).not.toMatch('placeholder="Add artwork url"')
  })

  it('does not display layouts if article layout is news', () => {
    props.article.layout = 'news'
    const component = getWrapper(props)

    expect(component.html()).not.toMatch('class="layout"')
  })

  it('#componentWillUnmount removes the section on unmount if no images', () => {
    props.editSection.images = []
    const component = getWrapper(props).find(ImagesControls)

    component.instance().componentWillUnmount()
    expect(props.removeSectionAction.mock.calls[0][0]).toBe(props.sectionIndex)
  })

  describe('Artwork inputs', () => {
    it('#onUpload saves an image info after upload', () => {
      props.isHero = false
      const component = getWrapper(props).find(ImagesControls)

      component.instance().onUpload('http://image.jpg', 400, 800)
      const newImages = props.onChangeSectionAction.mock.calls[0][1]
      const newImage = props.onChangeSectionAction.mock.calls[0][1][3]

      expect(newImages.length).toBe(props.editSection.images.length + 1)
      expect(newImage.type).toMatch('image')
      expect(newImage.url).toMatch('http://image.jpg')
      expect(newImage.width).toBe(400)
      expect(newImage.height).toBe(800)
    })

    it('Autocomplete onSelect resets the section images', () => {
      props.editSection.images = []
      const component = getWrapper(props)
      const images = StandardArticle.sections[4].images

      component.find(Autocomplete).first().props().onSelect(images)
      expect(props.onChangeSectionAction.mock.calls[0][0]).toBe('images')
      expect(props.onChangeSectionAction.mock.calls[0][1]).toBe(images)
    })

    it('Autocomplete onSelect limits images to 1 if layout is news', () => {
      props.article.layout = 'news'
      props.editSection.images = clone(StandardArticle.sections[4].images)
      const component = getWrapper(props)
      const images = clone(props.editSection.images)
      const newImage = {type: 'image', url: 'http://image.jpg'}
      images.push(newImage)

      component.find(Autocomplete).first().props().onSelect(images)
      expect(props.onChangeSectionAction.mock.calls[0][0]).toBe('images')
      expect(props.onChangeSectionAction.mock.calls[0][1].length).toBe(1)
      expect(props.onChangeSectionAction.mock.calls[0][1][0]).toBe(newImage)
    })

    it('#filterAutocomplete returns formatted artworks', () => {
      const component = getWrapper(props).find(ImagesControls)
      const items = {_embedded: {results: [rawArtwork]}}
      const filtered = component.instance().filterAutocomplete(items)[0]

      expect(filtered._id).toBe(rawArtwork._id)
      expect(filtered.title).toBe(rawArtwork.title)
      expect(filtered.thumbnail_image).toBe(rawArtwork._links.thumbnail.href)
      expect(filtered.type).toBe(rawArtwork.type)
      expect(filtered.description).toBe(undefined)
    })

    it('#filterAutocomplete returns false for non-artwork items', () => {
      const component = getWrapper(props).find(ImagesControls)
      const items = {_embedded: {results: [rawArtwork, {type: 'artist'}]}}
      const filtered = component.instance().filterAutocomplete(items)

      expect(filtered[0].type).toBe('artwork')
      expect(filtered[1]).toBe(false)
    })

    it('#fetchDenormalizedArtwork returns a denormalized artwork', async () => {
      Artwork.prototype.denormalized = jest.fn().mockReturnValueOnce(artwork)
      Backbone.Model.prototype.fetch = jest.fn().mockReturnValueOnce(artwork)
      const component = getWrapper(props).find(ImagesControls)

      const fetchedArtwork = await component.instance().fetchDenormalizedArtwork('1234')
      expect(fetchedArtwork).toBe(artwork)
    })

    it('#fetchDenormalizedArtwork calls #logErrorAction on error', async () => {
      Backbone.Model.prototype.fetch = jest.fn(() => {
        const err = { message: 'an error' }
        throw err
      })
      const component = getWrapper(props).find(ImagesControls)

      await component.instance().fetchDenormalizedArtwork('1234')
      expect(props.logErrorAction.mock.calls.length).toBe(1)
    })

    it('#onNewImage updates the section images', () => {
      const component = getWrapper(props).find(ImagesControls)
      component.instance().onNewImage(
        {type: 'artwork', image: 'artwork.jpg'}
      )
      const newImages = props.onChangeSectionAction.mock.calls[0][1]
      const newImage = props.onChangeSectionAction.mock.calls[0][1][3]

      expect(props.onChangeSectionAction.mock.calls[0][0]).toBe('images')
      expect(newImages.length).toBe(props.editSection.images.length + 1)
      expect(newImage.type).toMatch('artwork')
      expect(newImage.image).toMatch('artwork.jpg')
    })

    it('#onNewImage can update hero section images', () => {
      props.isHero = true
      props.section = {type: 'image', images: clone(StandardArticle.sections[4].images)}
      const component = getWrapper(props).find(ImagesControls)
      component.instance().onNewImage(
        {type: 'artwork', image: 'artwork.jpg'}
      )
      const newImages = props.onChangeHeroAction.mock.calls[0][1]
      const newImage = props.onChangeHeroAction.mock.calls[0][1][3]

      expect(props.onChangeHeroAction.mock.calls[0][0]).toBe('images')
      expect(newImages.length).toBe(props.section.images.length + 1)
      expect(newImage.type).toMatch('artwork')
      expect(newImage.image).toMatch('artwork.jpg')
    })

    it('#onNewImage limits images to 1 if layout is news', () => {
      props.article.layout = 'news'
      props.editSection = {type: 'image', images: clone(StandardArticle.sections[4].images)}
      const component = getWrapper(props).find(ImagesControls)
      component.instance().onNewImage(
        {type: 'artwork', image: 'artwork.jpg'}
      )
      const newImages = props.onChangeSectionAction.mock.calls[0][1]
      const newImage = props.onChangeSectionAction.mock.calls[0][1][0]
      expect(props.onChangeSectionAction.mock.calls[0][0]).toBe('images')
      expect(newImages.length).toBe(1)
      expect(newImage.type).toMatch('artwork')
      expect(newImage.image).toMatch('artwork.jpg')
    })

    it('#inputsAreDisabled returns false if layout is not fillwidth', () => {
      const component = getWrapper(props).find(ImagesControls)

      const inputsAreDisabled = component.instance().inputsAreDisabled(props.section)
      expect(inputsAreDisabled).toBe(false)
    })

    it('#inputsAreDisabled returns true if fillwidth section has images', () => {
      props.editSection.layout = 'fillwidth'
      const component = getWrapper(props).find(ImagesControls)

      const inputsAreDisabled = component.instance().inputsAreDisabled(props.section)
      expect(inputsAreDisabled).toBe(true)
    })

    it('#fillWidthAlert calls #logErrorAction', () => {
      const component = getWrapper(props).find(ImagesControls)

      component.instance().fillWidthAlert()
      expect(component.props().logErrorAction.mock.calls.length).toBe(1)
    })

    it('Calls #logErrorAction via #fillWidthAlert if inputsAreDisabled and trying to add an image', () => {
      props.editSection.layout = 'fillwidth'
      const component = getWrapper(props)

      component.find('.edit-controls__artwork-inputs').at(0).simulate('click')
      expect(props.logErrorAction.mock.calls.length).toBe(1)
    })
  })

  describe('Image Set inputs', () => {
    beforeEach(() => {
      extend(props.editSection, {type: 'image_set', layout: 'mini'})
    })

    it('Renders the active image_set layout', () => {
      const component = getWrapper(props)

      expect(component.html()).toMatch(
        '

Mini
'
      )
    })

    it('changes image_set layout on button click', () => {
      const component = getWrapper(props)

      component.find('.radio-input').at(1).simulate('click')
      expect(props.onChangeSectionAction.mock.calls[0][0]).toBe('layout')
      expect(props.onChangeSectionAction.mock.calls[0][1]).toBe('full')
    })

    it('changes image_set title on input', () => {
      const component = getWrapper(props)
      const input = component.find('.edit-controls__image-set-inputs').find('input')
      const newTitle = 'A title for the Image Set'
      input.simulate('change', { target: { value: newTitle } })

      expect(props.onChangeSectionAction.mock.calls[0][0]).toBe('title')
      expect(props.onChangeSectionAction.mock.calls[0][1]).toBe(newTitle)
    })
  })
})


text:
package com.jquartz.rich.validation.core.expression.junction;

import com.google.common.base.Joiner;
import com.jquartz.rich.validation.core.api.textual.Tokens;
import com.jquartz.rich.validation.core.expression.Expression;

import java.util.Collection;

import static com.jquartz.rich.validation.core.evaluation.TruthValue.TRUE;
import static com.jquartz.rich.validation.core.evaluation.TruthValueBinaryOperator.AND;

public class LogicalAndJunction<T> extends LogicalOperatorJunction<T> {

    public LogicalAndJunction(Collection<Expression<T>> junctions) {
        super(junctions, AND, TRUE);
    }

    @Override
    public String getTextualRepresentation() {
        return Joiner.on(" " + Tokens.AND.toString() + " ").join(junctions);
    }

    @Override
    public String toString() {
        return getTextualRepresentation();
    }
}


text:
@implementation SinaweiboAuthViewController

- (DOUOAuth2VenderType)venderType
{
  return kDOUOAuth2VenderSinaWeibo;
}

- (NSString *)venderAPIKey
{
  return SINA_APPKEY;
}

- (NSString *)venderAPISecrect
{
  return SINA_SECRET;
}

- (NSString *)oauthRedirectURL
{
  return SINA_REDIRECT_URI;
}

@end


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  <title>Conduct Assessment Service</title>

  <link type="text/css" rel="stylesheet" media="screen" href="../assets/stylesheets/govuk-template.css">

  <link type="text/css" rel="stylesheet" media="print" href="../assets/stylesheets/govuk-template-print.css">

<link type="text/css" rel="stylesheet" media="all" href="../assets/stylesheets/fonts.css">

<link type="image/x-icon" href="../assets/images/favicon.ico" rel="shortcut icon">

<link href="../assets/images/apple-touch-icon-144x144.png" sizes="144x144" rel="apple-touch-icon-precomposed">

<link href="../assets/images/apple-touch-icon-114x114.png" sizes="114x114" rel="apple-touch-icon-precomposed">

<link href="../assets/images/apple-touch-icon-72x72.png" sizes="72x72" rel="apple-touch-icon-precomposed">

<link href="../assets/images/apple-touch-icon-57x57.png" rel="apple-touch-icon-precomposed">
<meta content="width=device-width, initial-scale=1" name="viewport">
<meta content="assets/images/opengraph-image.png" property="og:image">
<link type="text/css" rel="stylesheet" href="../assets/stylesheets/elements-page.css">

<link type="text/css" rel="stylesheet" href="../assets/stylesheets/main.css">

<link type="text/css" rel="stylesheet" media="screen" href="../assets/stylesheets/complete.css">

<link type="text/css" rel="stylesheet" media="screen" href="../assets/js/bootstrap-switch/bootstrap.min.css">

The Conduct Assessment Service uses cookies to make the site simpler. Find out more about cookies

      Skip to main content

             GOV.UK

            Conduct Assessment Service

            BETA
            This is a new service - your feedback will help us improve it

              Dashboard  |
              Manage Staff  |
              Change Password

                Logout (Mr D Smith)

            <form action="#" method="get">

                <input id="search" class="form-control input-lg" id="system-search" name="q" placeholder="Add text to filter" required>

                  <button type="submit" class="btn btn-lg"></button>

            </form>

                  IP no
                  Case Ref
                  Company name
                  Company no
                  Due date
                  Case status

                  1234
                   NCL12345
                  Cars R Us Ltd
                  01234567
                  02-11-2015

Not Started

                  1234
                   NCL99887766
                  Eat Sticky Buns Ltd
                  0988775
                  02-11-2015

In Progress

                  1234
                   NCL778845374
                  Fly By Night Ltd
                  7834456
                  02-11-2015

For Review

                  4444
                   NCL845732
                  Gym's R Great Ltd
                  099887766
                  02-02-2015

Submitted

                  5555
                   NCL458656
                  Bonkers Dogs Ltd
                  011223344
                  5-10-2015
                  Overdue

                1234
                 NCL12345
                Cars R Us Ltd
                01234567
                02-11-2015

Not Started

                1234
                 NCL99887766
                Eat Sticky Buns Ltd
                0988775
                02-11-2015

In Progress

                1234
                 NCL778845374
                Fly By Night Ltd
                7834456
                02-11-2015

For Review

                4444
                 NCL845732
                Gym's R Great Ltd
                099887766
                02-02-2015

Submitted

                5555
                 NCL458656
                Bonkers Dogs Ltd
                011223344
                5-10-2015
                Overdue

Contact us

Privacy

Cookies

Built by The Insolvency Service

Open Government Licence

All content is available under the Open Government Licence v2.0, except where otherwise stated

        © Crown copyright

  Window size:
  1194 x 754

Viewport size:
  1178 x 623


text:
type Heap<T: Node> = Array<T>;
type Node = {
  id: number,
  sortIndex: number,
  ...
};

export function push<T: Node>(heap: Heap<T>, node: T): void {
  const index = heap.length;
  heap.push(node);
  siftUp(heap, node, index);
}

export function peek<T: Node>(heap: Heap<T>): T | null {
  return heap.length === 0 ? null : heap[0];
}

export function pop<T: Node>(heap: Heap<T>): T | null {
  if (heap.length === 0) {
    return null;
  }
  const first = heap[0];
  const last = heap.pop();
  if (last !== first) {
    heap[0] = last;
    siftDown(heap, last, 0);
  }
  return first;
}

function siftUp<T: Node>(heap: Heap<T>, node: T, i: number): void {
  let index = i;
  while (index > 0) {
    const parentIndex = (index - 1) >>> 1;
    const parent = heap[parentIndex];
    if (compare(parent, node) > 0) {
      // The parent is larger. Swap positions.
      heap[parentIndex] = node;
      heap[index] = parent;
      index = parentIndex;
    } else {
      // The parent is smaller. Exit.
      return;
    }
  }
}

function siftDown<T: Node>(heap: Heap<T>, node: T, i: number): void {
  let index = i;
  const length = heap.length;
  const halfLength = length >>> 1;
  while (index < halfLength) {
    const leftIndex = (index + 1) * 2 - 1;
    const left = heap[leftIndex];
    const rightIndex = leftIndex + 1;
    const right = heap[rightIndex];

    // If the left or right node is smaller, swap with the smaller of those.
    if (compare(left, node) < 0) {
      if (rightIndex < length && compare(right, left) < 0) {
        heap[index] = right;
        heap[rightIndex] = node;
        index = rightIndex;
      } else {
        heap[index] = left;
        heap[leftIndex] = node;
        index = leftIndex;
      }
    } else if (rightIndex < length && compare(right, node) < 0) {
      heap[index] = right;
      heap[rightIndex] = node;
      index = rightIndex;
    } else {
      // Neither child is smaller. Exit.
      return;
    }
  }
}

function compare(a: Node, b: Node) {
  // Compare sort index first, then task id.
  const diff = a.sortIndex - b.sortIndex;
  return diff !== 0 ? diff : a.id - b.id;
}


text:
/* ImportHTML */

#import <Cocoa/Cocoa.h>
#import "Linkstr_AppDelegate.h"

@interface ImportHTML : NSObject
{
@private
    IBOutlet NSWindow *m_win;
//    IBOutlet NSTableView *m_table;
    IBOutlet NSArrayController *m_controller;
    IBOutlet NSButton *m_all;
    NSString *m_html;
    NSString *m_source;
    Linkstr_AppDelegate *m_delegate;
}

@property (retain) NSString *source;
@property (retain) Linkstr_AppDelegate *delegate;
@property (retain, getter=getHtml, setter=setHtml:) NSString* html;

- (id)initWithHtmlString:(NSString*)html
                  source:(NSString*)source
                 linkstr:(Linkstr_AppDelegate*)delegate;

- (void)insertCheckedLinks;
- (int)popup;
- (IBAction)done:(id)sender;
- (IBAction)setAll:(id)sender;

@end


text:
package com.lennerd.processing.twitter_graph;

import com.lennerd.processing.twitter_graph.twitter.MyStatus;
import de.looksgood.ani.Ani;
import de.looksgood.ani.AniSequence;
import processing.core.PApplet;
import processing.core.PVector;
import twitter4j.GeoLocation;

import java.io.Serializable;

public final class Line extends SkyObject {

    private static final long serialVersionUID = Sketch.SERIALIZATION_ID;

    private final MyStatus reply, status;
    private final String info;
    private float x1, x2, y1, y2;
    private float opacity;
    private Focus focus;
    private float radius;

    public Line(MyStatus reply, MyStatus status) {
        this.reply = reply;
        this.status = status;

        this.info = Point.buildInfo(status) + " — " + Point.buildInfo(reply);
    }

    @Override
    public void onDraw(PApplet sketch) {
        sketch.pushMatrix();
        sketch.pushStyle();

        sketch.noFill();
        sketch.stroke(this.color.red, this.color.green, this.color.blue,
                this.opacity);

        sketch.line(this.x1, this.y1, this.x2, this.y2);

        sketch.ellipseMode(PApplet.RADIUS);

        if (this.focus != null) {
            sketch.noStroke();
            sketch.fill(this.focus.color.red, this.focus.color.green,
                    this.focus.color.blue, this.focus.opacity);
            sketch.ellipse(this.focus.x, this.focus.y, this.radius, this.radius);
        }

        sketch.popMatrix();
        sketch.popStyle();
    }

    public MyStatus getReply() {
        return this.reply;
    }

    public MyStatus getStatus() {
        return this.status;
    }

    @Override
    public void onAdd(PApplet sketch) {
        GeoLocation statusLocation = this.status.getGeoLocation();
        GeoLocation replyLocation = this.reply.getGeoLocation();

        this.x1 = this.x2 = Sketch.calculateLongitude(sketch, statusLocation);
        this.y1 = this.y2 = Sketch.calculateLatitude(sketch, statusLocation);

        this.opacity = 50F;

        this.color = new StatusColor(this.status);
        this.color.extend(this.reply);

        this.radius = 1.5f;

        Ani.to(this,
                Sketch.ANI_DURATION,
                "x2:" + Sketch.calculateLongitude(sketch, replyLocation)
                        + ",y2:"
                        + Sketch.calculateLatitude(sketch, replyLocation)
        );
    }

    @Override
    public void onRemove(PApplet sketch) {
        Ani.to(this, Sketch.ANI_DURATION, "x2:" + this.x1 + ",y2:" + this.y1,
                Ani.getDefaultEasing(), "onEnd:onRemoved");
    }

    @Override
    public void onFocus(PApplet sketch) {
        this.focus = new Focus(this.x1, this.y1, this.color, Sketch.LINE_OPACITY);

        AniSequence sequence = new AniSequence(sketch);

        sequence.beginSequence();
        sequence.add(Ani.from(this.focus, Sketch.ANI_DURATION, "opacity", 0));
        sequence.add(Ani.to(this.focus, Sketch.ANI_DURATION, "x:" + this.x2
                + ",y:" + this.y2));
        sequence.add(Ani.to(this.focus, Sketch.ANI_DURATION, "opacity", 0,
                Ani.getDefaultEasing(), "onEnd:remove"));
        sequence.endSequence();

        sequence.start();
    }

    public void removePoint() {
        this.focus = null;
    }

    @Override
    public boolean equals(Object obj) {
        if (null == obj) {
            return false;
        }

        if (this == obj) {
            return true;
        }

        if (obj instanceof Line) {
            Line line = (Line) obj;
            MyStatus reply = line.getReply();
            MyStatus status = line.getStatus();

            if ((this.reply.equals(reply) && this.status.equals(status))
                    || (this.status.equals(reply) && this.reply.equals(status))) {
                return true;
            }
        }

        return false;
    }

    private class Focus implements Serializable {

        private static final long serialVersionUID = 1L;
        private float x;
        private float y;
        private StatusColor color;
        private float opacity;

        public Focus(float x, float y, StatusColor color, float opacity) {
            this.x = x;
            this.y = y;
            this.color = color;
            this.opacity = opacity;
        }

        @SuppressWarnings("unused")
        public void remove() {
            Line.this.focus = null;
        }
    }

    @Override
    public void addStatus(MyStatus status) {
    }

    @Override
    public boolean isMouseOver(int mouseX, int mouseY) {
        PVector lineStart, lineEnd, mouse, projection, temp;

        lineStart = new PVector(this.x1, this.y1);
        lineEnd = new PVector(this.x2, this.y2);
        mouse = new PVector(mouseX, mouseY);

        temp = PVector.sub(lineEnd, lineStart);

        float lineLength = temp.x * temp.x + temp.y * temp.y; // lineStart.dist(lineEnd);

        if (lineLength == 0F) {
            return mouse.dist(lineStart) <= InfoBox.MOUSE_OVER_BORDER;
        }

        float t = PVector.dot(PVector.sub(mouse, lineStart), temp) / lineLength;

        if (t < 0F) {
            return mouse.dist(lineStart) <= InfoBox.MOUSE_OVER_BORDER;
        }

        if (t > 1F) {
            return mouse.dist(lineEnd) <= InfoBox.MOUSE_OVER_BORDER;
        }

        projection = PVector.add(lineStart, PVector.mult(temp, t));

        return mouse.dist(projection) <= InfoBox.MOUSE_OVER_BORDER;

		/*
         * this.projection = null;
		 *
		 * lineStart = new PVector(this.x1, this.y1); lineEnd = new
		 * PVector(this.x2, this.y2); mouse = new PVector(mouseX, mouseY);
		 *
		 * float lineLength = lineStart.dist(lineEnd);
		 *
		 * if (lineLength == 0F) { return mouse.dist(lineStart) <
		 * InfoBox.MOUSE_OVER_BORDER; }
		 *
		 * float t = PVector.dot(PVector.sub(mouse, lineStart),
		 * PVector.sub(lineEnd, lineStart)) / lineLength;
		 *
		 * if (t < 0F) { PApplet.println("lineStart"); return
		 * mouse.dist(lineStart) < InfoBox.MOUSE_OVER_BORDER; }
		 *
		 * if (t > lineLength) { PApplet.println("lineEnd"); return
		 * mouse.dist(lineEnd) < InfoBox.MOUSE_OVER_BORDER; }
		 *
		 * this.projection = PVector.add(lineStart,
		 * PVector.mult(PVector.sub(lineEnd, lineStart), t));
		 *
		 * return mouse.dist(this.projection) < InfoBox.MOUSE_OVER_BORDER;
		 */
    }

    @Override
    public String getInfo() {
        return this.info;
    }

}


text:
[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Spreadsheet%20SDK%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Spreadsheet%20SDK%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=nm_7I0PN1TY](https://www.youtube.com/watch?v=nm_7I0PN1TY)

<!-- code block begin -->

##### **Program.cs:**

```
using Bytescout.Spreadsheet;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;

namespace WorkbookAutoCalculation
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Data to be written in spreadsheet
                var lstProducts = new List<InvoiceProduct> {
                    new InvoiceProduct{ ProductName = "Product 1", Price = 30, Quantity = 10 },
                    new InvoiceProduct{ ProductName = "Product 2", Price = 40, Quantity = 30 },
                    new InvoiceProduct{ ProductName = "Product 3", Price = 50, Quantity = 15 },
                    new InvoiceProduct{ ProductName = "Product 4", Price = 20, Quantity = 20 }
                };

                // Generate Workbook in memory
                var document = _GetSpreadsheet(lstProducts);

                // Export to XLSX
                document.SaveAsXLSX("Invoice.xlsx");
                //document.SaveAsXLS("Invoice.xls");

                // Open output file
                Process.Start("Invoice.xlsx");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Press enter key to exit...");
            Console.ReadLine();
        }

        /// <summary>
        /// Get Spreadsheet
        /// </summary>
        private static Spreadsheet _GetSpreadsheet(List<InvoiceProduct> lstProducts)
        {
            // Create new Spreadsheet
            Spreadsheet document = new Spreadsheet();

            // Enable auto-calculation of formulas
            document.Workbook.AutoCalculation = true;

            document.Workbook.DefaultFont = new SpreadsheetFont("Arial", 10);

            // Add new worksheet
            Worksheet Sheet = document.Workbook.Worksheets.Add("Invoice");

            int startRow = 0;

            // Add Product Listing
            string startAddress = "";
            string endAddress = "";

            Sheet.Cell((startRow), 0).Value = "Item";
            _AddAllBorders(Sheet.Cell(startRow, 0));
            Sheet.Cell(startRow, 0).Font = new Font("Arial", 11, FontStyle.Bold);

            Sheet.Cell(startRow, 1).Value = "Quantity";
            _AddAllBorders(Sheet.Cell(startRow, 1));
            Sheet.Cell(startRow, 1).AlignmentHorizontal = Bytescout.Spreadsheet.Constants.AlignmentHorizontal.Right;
            Sheet.Cell(startRow, 1).Font = new Font("Arial", 11, FontStyle.Bold);

            Sheet.Cell(startRow, 2).Value = "Price";
            _AddAllBorders(Sheet.Cell(startRow, 2));
            Sheet.Cell(startRow, 2).AlignmentHorizontal = Bytescout.Spreadsheet.Constants.AlignmentHorizontal.Right;
            Sheet.Cell(startRow, 2).Font = new Font("Arial", 11, FontStyle.Bold);

            Sheet.Cell(startRow, 3).Value = "Total";
            _AddAllBorders(Sheet.Cell(startRow, 3));
            Sheet.Cell(startRow, 3).AlignmentHorizontal = Bytescout.Spreadsheet.Constants.AlignmentHorizontal.Right;
            Sheet.Cell(startRow, 3).Font = new Font("Arial", 11, FontStyle.Bold);

            for (int i = 0; i < lstProducts.Count; i++)
            {
                Sheet.Cell((++startRow), 0).Value = lstProducts[i].ProductName;
                _AddAllBorders(Sheet.Cell(startRow, 0));

                Sheet.Cell(startRow, 1).Value = lstProducts[i].Quantity;
                Sheet.Cell(startRow, 1).AlignmentHorizontal = Bytescout.Spreadsheet.Constants.AlignmentHorizontal.Right;
                _AddAllBorders(Sheet.Cell(startRow, 1));

                Sheet.Cell(startRow, 2).Value = lstProducts[i].Price;
                Sheet.Cell(startRow, 2).AlignmentHorizontal = Bytescout.Spreadsheet.Constants.AlignmentHorizontal.Right;
                _AddAllBorders(Sheet.Cell(startRow, 2));

                // Calculated cell
                string formulaMultiplication = string.Format("={0}*{1}", Sheet.Cell(startRow, 1).GetAddress().ToString(), Sheet.Cell(startRow, 2).GetAddress().ToString());
                Sheet.Cell(startRow, 3).Formula = formulaMultiplication;
                Sheet.Cell(startRow, 3).AlignmentHorizontal = Bytescout.Spreadsheet.Constants.AlignmentHorizontal.Right;
                _AddAllBorders(Sheet.Cell(startRow, 3));

                // Address to be used for total sum
                if (i == 0)
                {
                    startAddress = Sheet.Cell(startRow, 3).GetAddress().ToString();
                }
                endAddress = Sheet.Cell(startRow, 3).GetAddress().ToString();
            }

            Sheet.Cell((++startRow), 2).Value = "TOTAL";
            Sheet.Cell(startRow, 2).Font = new Font("Arial", 11, FontStyle.Bold);
            Sheet.Cell(startRow, 2).AlignmentHorizontal = Bytescout.Spreadsheet.Constants.AlignmentHorizontal.Right;

            string formulaTotalSum = string.Format("=SUM({0}:{1})", startAddress, endAddress);
            Sheet.Cell(startRow, 3).Formula = formulaTotalSum;
            Sheet.Cell(startRow, 3).Font = new Font("Arial", 11, FontStyle.Bold);
            Sheet.Cell(startRow, 3).AlignmentHorizontal = Bytescout.Spreadsheet.Constants.AlignmentHorizontal.Right;

            // AutoFit all columns
            Sheet.Columns[0].AutoFit();
            Sheet.Columns[1].AutoFit();
            Sheet.Columns[2].AutoFit();
            Sheet.Columns[3].AutoFit();

            // Return all formatted document
            return document;
        }

        /// <summary>
        /// Add borders to cell
        /// </summary>
        private static void _AddAllBorders(Cell cell)
        {
            cell.LeftBorderStyle = Bytescout.Spreadsheet.Constants.LineStyle.Thin;
            cell.RightBorderStyle = Bytescout.Spreadsheet.Constants.LineStyle.Thin;
            cell.TopBorderStyle = Bytescout.Spreadsheet.Constants.LineStyle.Thin;
            cell.BottomBorderStyle = Bytescout.Spreadsheet.Constants.LineStyle.Thin;
        }

    }

    /// <summary>
    /// Invoice Product class
    /// </summary>
    public class InvoiceProduct
    {
        public string ProductName { get; set; }
        public int Quantity { get; set; }
        public decimal Price { get; set; }
    }

}

```

<!-- code block end -->

<!-- code block begin -->

##### **WorkbookAutoCalculation.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{99735776-2956-463D-9795-EBCE16928C30}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <RootNamespace>WorkbookAutoCalculation</RootNamespace>
    <AssemblyName>WorkbookAutoCalculation</AssemblyName>
    <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.Spreadsheet, Version=3.1.0.1715, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>c:\Program Files\Bytescout Spreadsheet SDK\net2.00\Bytescout.Spreadsheet.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
```

<!-- code block end -->


text:
@implementation AMDBaseModel

- (void)dealloc
{
    self.baseOtherinfo = nil;
}

//处理纠错能力  防止系统崩溃
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    [self.baseOtherinfo setObject:value forKey:key];
}

- (NSMutableDictionary *)baseOtherinfo
{
    if (_baseOtherinfo == nil) {
        _baseOtherinfo = [[NSMutableDictionary alloc]init];
    }
    return _baseOtherinfo;
}

@end


text:
package powered.by.sergey.binarystorage;

import java.util.List;

import javax.persistence.EntityManager;

public class CopyOfFileMetadataDAO {

	public FileMetadata readFileByID(String id) {
		EntityManager em = PersistenceManager.createEntityManager();
		try {
			return em.find(FileMetadata.class, id);
		} finally {
			em.close();
		}
	}

	public void deleteFileByID(String id) {
		EntityManager em = PersistenceManager.createEntityManager();
		try {
			em.getTransaction().begin();

			FileMetadata fm = em.find(FileMetadata.class, id);
			em.remove(fm);

			em.getTransaction().commit();
		} finally {
			if (em.getTransaction().isActive())
				em.getTransaction().rollback();
			em.close();
		}
	}

	public void save(FileMetadata attachment) {
		EntityManager em = PersistenceManager.createEntityManager();
		try {
			em.getTransaction().begin();

			em.persist(attachment);

			em.getTransaction().commit();
		} finally {
			if (em.getTransaction().isActive())
				em.getTransaction().rollback();
			em.close();
		}
	}

	public List<FileMetadata> readByCatalogAndGroup(String catalogType, String catalogId, String groupId) {
		EntityManager em = PersistenceManager.createEntityManager();
		try {
			return em.createNamedQuery("FileMetadata.GetByCatalogAndGroup", FileMetadata.class)
				.setParameter("catalogType", catalogType)
				.setParameter("catalogId", catalogId)
				.setParameter("groupId", groupId)
				.getResultList();
		} finally {
			em.close();
		}
	}

}


text:
function Country(name, capital, population, largestCity) {
  this.name = name;
  this.capital = capital;
  this.population = population;
  this.largestCity = largestCity;
  this.unread = 3;
  this.decrement = function() {
    this.unread--;
  }
  this.fact = function() {
    var remaining = this.unread;
    if (remaining == 0) {
      this.unread = 3;
      return ("You have already learned about " + this.name + "! Resetting facts so you can review!");

      //this.fact();
    }
    else if (remaining == 3) {
      this.decrement();
      return ("The capital of " + this.name + " is " + this.capital + ".");

    }
    else if (remaining == 2) {
      this.decrement();
      return ("The population of " + this.name + " is " + this.population + ".");

    }
    else if (remaining == 1) {
      this.decrement();
      return ("The largest city in " + this.name + " is " + this.largestCity + ".");

    }
  }
}

//here I am creating a bunch of Country objects. Thanks wikipedia!
var Peru = new Country('Peru', 'Lima', '31 million', 'Lima');
var Colombia = new Country('Colombia', 'Bogot\341', '48 million', 'Bogot\341');
var Mongolia = new Country('Mongolia', 'Ulaanbaatar', '3 million', 'Ulaanbaatar');
var China = new Country('China', 'Beijing', '1.37 billion', 'Shanghai');
var uae = new Country('United Arab Emirates', 'Abu Dhabi', '9 million', 'Dubai');
var Brazil = new Country('Brazil', 'Bras\355lia', '205 million', 'S\343o Paulo');
var Canada = new Country('Canada', 'Ottawa', '36 million', 'Toronto');
var India = new Country('India', 'New Delhi', '1.3 billion', 'Mumbai');
var Morocco = new Country('Morocco', 'Rabat', '34 million', 'Casablanca');
var Tanzania = new Country('Tanzania', 'Dodoma', '50 million', 'Dar es Salaam');
var Australia = new Country('Australia', 'Canberra', '24 million', 'Sydney');
var Cameroon = new Country('Cameroon', 'Yaound\351', '22 million', 'Douala');
var Ecuador = new Country('Ecuador', 'Quito', '16 million', 'Guayaquil');
var Nigeria = new Country('Nigeria', 'Abuja', '182 million', 'Lagos');
var Turkey = new Country('Turkey', 'Ankara', '77 million', 'Istanbul');
var Vietnam = new Country('Vietnam', 'Hanoi', '91 million', 'Ho Chi Minh City');
var Kazakhstan = new Country('Kazakhstan', 'Astana', '17 million', 'Almaty');
var Pakistan = new Country('Pakistan', 'Islamabad', '199 million', 'Karachi');
var Belize = new Country('Belize', 'Belmopan', '340 thousand', 'Belize City');
var Syria = new Country('Syria', 'Damascus', '17 million', 'Aleppo');
var Myanmar = new Country('Myanmar', 'Naypyidaw', '51 million', 'Yangon');

//here I will create an array of all the country objects in case I want to use it later
var database = [Peru, Colombia, Mongolia, China, uae, Brazil, Canada, India, Morocco, Tanzania, Australia, Ecuador, Cameroon, Nigeria, Turkey, Vietnam];

function getTarget(e) {
  if (!e) {
    e = window.event;
  }
  return e.target || e.srcElement;
}

function displayFact(e) {
  var board = document.getElementById('knowledge');
  var target = getTarget(e);
  var country = target.textContent;
  var att = eval(country);
  var result = att.fact();
  board.textContent = result;
  if (e.preventDefault) {
    e.preventDefault();
  } else {
    e.returnValue = false;
  }
}

var elem = document.getElementById('counts');
if (elem.addEventListener) {
  elem.addEventListener('click', function(e) {
    displayFact(e);
  }, false);
} else {
  elem.attachEvent('onclick', function(e) {
    displayFact(e);
  });
}


text:
using System.Collections.Generic;
using System.Xml;
using System.Xml.XPath;
using DotA2StatsParser.Model;

namespace DotA2StatsParser.Controller.Yasp
{
    internal class YaspMappingController : MappingController
    {
        private dynamic dotabuffUrls;

        internal dynamic UrlPath { get { return dotabuffUrls.URL; } }

        internal YaspMappingController(JsonPaths jsonPaths)
        {
            JsonController jsonReader = new JsonController();

            dotabuffUrls = jsonReader.ReadFromFile(jsonPaths.UrlsUri);
        }

        internal Dictionary<string, string> GetAllUrlsAsDictionary()
        {
            return GetMappingAsDictionary(UrlPath);
        }
    }
}


text:
@implementation LBMineCenterPayPagesTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

@end


text:
export default function (router) {
    router.redirect({
        '*': '/index'
    });

    router.map({
        '/index': {
            name: 'index',
            component: require('./components/Index.vue')
        },
        '/category': {
            name: 'category',
            component: require('./components/Category.vue')
        },
        '/:hashid/commodity': {
            name: 'commodity',
            component: require('./components/Commodity/CommodityDetail.vue')
        },
        '/cart': {
            name: 'cart',
            component: require('./components/Cart.vue')
        },
        '/usercenter': {
            name: 'usercenter',
            component: require('./components/UserCenter.vue')
        },
        '/attr': {
            name: 'attribute',
            component: require('./components/Attribute/Attribute.vue'),
            subRoutes: {
                '/:hashid/topic': {
                    name: 'aTopic',
                    component: require('./components/Attribute/Topic.vue')
                },
                '/:hashid/plate': {
                    name: 'aPlate',
                    component: require('./components/Attribute/Plate.vue')
                },
                '/:hashid/category': {
                    name: 'aCategory',
                    component: require('./components/Attribute/Category.vue')
                }
            }
        },
        '/address': {
            name: 'address',
            component: require('./components/Address/AddressList.vue')
        },
        '/add-address': {
            name: 'add-address',
            component: require('./components/Address/AddressAdd.vue')
        },
        '/:hashid/edit-address': {
            name: 'edit-address',
            component: require('./components/Address/AddressEdit.vue')
        },
        '/:hashid/choose-address': {
            name: 'choose-address',
            component: require('./components/Address/AddressChoose.vue')
        },
        '/ordersettle': {
            name: 'order-settle',
            component: require('./components/Order/OrderSettle.vue')
        },
        '/:type/orderlist': {
            name: 'order-list',
            component: require('./components/Order/OrderList.vue')
        },
        '/:hashid/orderdetail': {
            name: 'order-detail',
            component: require('./components/Order/OrderDetail.vue')
        },
        '/:hashid/orderpay': {
            name: 'orderpay',
            component: require('./components/Order/OrderPay.vue')
        },
        '/suggestion': {
            name: "suggestion",
            component: require('./components/Suggestion/Suggestion.vue')
        }
    });
}


text:
'use strict'

const awsCommand = require('./aws-command')

exports.build = build

// builds a paging function - pagedFn((err, items) => ...)
// eg:
//   build(['logs', 'describe-log-groups'], 'logGroups', '--starting-token', 'nextToken')
//   build(['logs', 'get-log-events', ...], 'events', '--next-token', 'nextForwardToken')
function build (cmd, collProperty, nextOption, nextProperty) {
  return function builtPager (cb) {
    const items = []

    awsCommand.run(cmd, awsCommandDone)

    function awsCommandDone (err, data) {
      if (err) return cb(err)

      // err if our collection property not found
      const collValue = data[collProperty]
      if (collValue == null) {
        return cb(new Error(`expected property ${collProperty} in data: ${JSON.stringify(data)}`))
      }

      // no items? done
      if (collValue.length === 0) return cb(null, items)

      // copy items to our list
      for (let item of collValue) items.push(item)

      // no next property? done
      if (data[nextProperty] == null) return cb(null, items)

      // set up next paged call
      const nextCmd = cmd.slice()
      nextCmd.push(nextOption)
      nextCmd.push(data[nextProperty])

      awsCommand.run(nextCmd, awsCommandDone)
    }
  }
}


text:
package org.hibernate.validator.referenceguide.chapter06.constraintcomposition.reportassingle;

//end::include[]

import jakarta.validation.Payload;
import jakarta.validation.ReportAsSingleViolation;

//tag::include[]
//...
@ReportAsSingleViolation
public @interface ValidLicensePlate {

	String message() default "{org.hibernate.validator.referenceguide.chapter06." +
			"constraintcomposition.reportassingle.ValidLicensePlate.message}";

	Class<?>[] groups() default { };

	Class<? extends Payload>[] payload() default { };
}
//end::include[]


text:
<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox">

    {% if site.author.github %}

    {% endif %}

	  {% if site.author.linkedin %}

    {% endif %}

{{ site.description }}

    Home

    {% assign pages_list = site.pages | sort:"url" %}
    {% for node in pages_list %}
      {% if node.title != null %}
        {% if node.layout == "page" %}
          {{ node.title }}
        {% endif %}
      {% endif %}
    {% endfor %}

    Download
    GitHub project
    Currently v{{ site.version }}

      © {{ site.time | date: '%Y' }}. All rights reserved.


text:
/**
 * Die Konfiguration der Datenbankschicht für die Wertpapierverwaltung.
 *
 * @author Frank W. Rahn
 */
package de.rahn.finances.domains.config;


text:
namespace ssdb{

class ClientImpl : public Client{
private:
	friend class Client;

	Link *link;
	std::vector<std::string> resp_;
public:
	ClientImpl();
	~ClientImpl();

	virtual const std::vector<std::string>* request(const std::vector<std::string> &req);
	virtual const std::vector<std::string>* request(const std::string &cmd);
	virtual const std::vector<std::string>* request(const std::string &cmd, const std::string &s2);
	virtual const std::vector<std::string>* request(const std::string &cmd, const std::string &s2, const std::string &s3);
	virtual const std::vector<std::string>* request(const std::string &cmd, const std::string &s2, const std::string &s3, const std::string &s4);
	virtual const std::vector<std::string>* request(const std::string &cmd, const std::string &s2, const std::string &s3, const std::string &s4, const std::string &s5);
	virtual const std::vector<std::string>* request(const std::string &cmd, const std::string &s2, const std::string &s3, const std::string &s4, const std::string &s5, const std::string &s6);
	virtual const std::vector<std::string>* request(const std::string &cmd, const std::vector<std::string> &s2);
	virtual const std::vector<std::string>* request(const std::string &cmd, const std::string &s2, const std::vector<std::string> &s3);

	virtual Status dbsize(int64_t *ret);
	virtual Status get_kv_range(std::string *start, std::string *end);
	virtual Status set_kv_range(const std::string &start, const std::string &end);

	virtual Status get(const std::string &key, std::string *val);
	virtual Status set(const std::string &key, const std::string &val);
	virtual Status setx(const std::string &key, const std::string &val, int ttl);
	virtual Status del(const std::string &key);
	virtual Status incr(const std::string &key, int64_t incrby, int64_t *ret);
	virtual Status keys(const std::string &key_start, const std::string &key_end,
		uint64_t limit, std::vector<std::string> *ret);
	virtual Status scan(const std::string &key_start, const std::string &key_end,
		uint64_t limit, std::vector<std::string> *ret);
	virtual Status rscan(const std::string &key_start, const std::string &key_end,
		uint64_t limit, std::vector<std::string> *ret);
	virtual Status multi_get(const std::vector<std::string> &keys, std::vector<std::string> *ret);
	virtual Status multi_set(const std::map<std::string, std::string> &kvs);
	virtual Status multi_del(const std::vector<std::string> &keys);

	virtual Status hget(const std::string &name, const std::string &key, std::string *val);
	virtual Status hset(const std::string &name, const std::string &key, const std::string &val);
	virtual Status hdel(const std::string &name, const std::string &key);
	virtual Status hincr(const std::string &name, const std::string &key, int64_t incrby, int64_t *ret);
	virtual Status hsize(const std::string &name, int64_t *ret);
	virtual Status hclear(const std::string &name, int64_t *ret=NULL);
	virtual Status hkeys(const std::string &name, const std::string &key_start, const std::string &key_end,
		uint64_t limit, std::vector<std::string> *ret);
	virtual Status hgetall(const std::string &name, std::vector<std::string> *ret);
	virtual Status hscan(const std::string &name, const std::string &key_start, const std::string &key_end,
		uint64_t limit, std::vector<std::string> *ret);
	virtual Status hrscan(const std::string &name, const std::string &key_start, const std::string &key_end,
		uint64_t limit, std::vector<std::string> *ret);
	virtual Status multi_hget(const std::string &name, const std::vector<std::string> &keys,
		std::vector<std::string> *ret);
	virtual Status multi_hset(const std::string &name, const std::map<std::string, std::string> &kvs);
	virtual Status multi_hdel(const std::string &name, const std::vector<std::string> &keys);

	virtual Status zget(const std::string &name, const std::string &key, int64_t *ret);
	virtual Status zset(const std::string &name, const std::string &key, int64_t score);
	virtual Status zdel(const std::string &name, const std::string &key);
	virtual Status zincr(const std::string &name, const std::string &key, int64_t incrby, int64_t *ret);
	virtual Status zsize(const std::string &name, int64_t *ret);
	virtual Status zclear(const std::string &name, int64_t *ret=NULL);
	virtual Status zrank(const std::string &name, const std::string &key, int64_t *ret);
	virtual Status zrrank(const std::string &name, const std::string &key, int64_t *ret);
	virtual Status zrange(const std::string &name,
		uint64_t offset, uint64_t limit,
		std::vector<std::string> *ret);
	virtual Status zrrange(const std::string &name,
		uint64_t offset, uint64_t limit,
		std::vector<std::string> *ret);
	virtual Status zkeys(const std::string &name, const std::string &key_start,
		int64_t *score_start, int64_t *score_end,
		uint64_t limit, std::vector<std::string> *ret);
	virtual Status zscan(const std::string &name, const std::string &key_start,
		int64_t *score_start, int64_t *score_end,
		uint64_t limit, std::vector<std::string> *ret);
	virtual Status zrscan(const std::string &name, const std::string &key_start,
		int64_t *score_start, int64_t *score_end,
		uint64_t limit, std::vector<std::string> *ret);
	virtual Status multi_zget(const std::string &name, const std::vector<std::string> &keys,
		std::vector<std::string> *scores);
	virtual Status multi_zset(const std::string &name, const std::map<std::string, int64_t> &kss);
	virtual Status multi_zdel(const std::string &name, const std::vector<std::string> &keys);

	virtual Status qpush(const std::string &name, const std::string &item, int64_t *ret_size=NULL);
	virtual Status qpush(const std::string &name, const std::vector<std::string> &items, int64_t *ret_size=NULL);
	virtual Status qpop(const std::string &name, std::string *item);
	virtual Status qpop(const std::string &name, int64_t limit, std::vector<std::string> *ret);
	virtual Status qslice(const std::string &name, int64_t begin, int64_t end, std::vector<std::string> *ret);
	virtual Status qrange(const std::string &name, int64_t begin, int64_t limit, std::vector<std::string> *ret);
	virtual Status qclear(const std::string &name, int64_t *ret=NULL);
};

}; // namespace ssdb

#endif