text:
<!doctype html>

    <title>CodeMirror</title>
    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
    <link rel="stylesheet" type="text/css" href="css/docs.css"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <link rel="alternate" href="http://twitter.com/statuses/user_timeline/242283288.rss" type="application/rss+xml"/>

{ } CodeMirror

/* In-browser code editing
   made bearable */

CodeMirror is a JavaScript library that can
  be used to create a relatively pleasant editor interface for
  code-like content ― computer programs, HTML markup, and
  similar. If a mode has been written for the language you are
  editing, the code will be coloured, and the editor will optionally
  help you with indentation.

This is the project page for CodeMirror 2, the currently more
  actively developed, and recommended
  version. CodeMirror 1 is still available
  from here.

Supported modes:

JavaScript

XML/HTML

CSS

HTML mixed-mode

Python

PHP

diff

C, Java, and similar

sTeX, LaTeX

Haskell

Smalltalk

reStructuredText

PL/SQL

Lua

Usage demos:

Autocompletion

Mode overlays

Search/replace

Auto-resizing editor

Setting breakpoints

Highlighting the current line

Theming

Stand-alone highlighting

Getting the code

All of CodeMirror is released under a MIT-style license. To get it, you can download
  the latest
  release or the current development
  snapshot as zip files. To create a custom minified script file,
  you can use the compression API.

We use git for version control.
  The main repository can be fetched in this way:

git clone http://marijnhaverbeke.nl/git/codemirror2

CodeMirror can also be found on GitHub at marijnh/CodeMirror2.
  If you plan to hack on the code and contribute patches, the best way
  to do it is to create a GitHub fork, and send pull requests.

Documentation

The manual is your first stop for
  learning how to use this library. It starts with a quick explanation
  of how to use the editor, and then describes all of the (many)
  options and methods that CodeMirror exposes.

For those who want to learn more about the code, there is
  an overview of the internals available.
  The source code
  itself is, for the most part, also well commented.

Support and bug reports

There is
  a Google
  group (a sort of mailing list/newsgroup thing) for discussion
  and news related to CodeMirror. Reporting bugs is best done
  on github.
  You can also e-mail me
  directly: Marijn
  Haverbeke.

Supported browsers

The following browsers are able to run CodeMirror:

Firefox 2 or higher

Chrome, any version

Safari 3 or higher

Internet Explorer 6 or higher

Opera 9 or higher (with some key-handling problems on OS X)

I am not actively testing against every new browser release, and
  vendors have a habit of introducing bugs all the time, so I am
  relying on the community to tell me when something breaks.
  See here for information on how to contact
  me.

  Download the latest release

Make a donation

Paypal

Bank

    Bank: Rabobank

    Country: Netherlands

    SWIFT: RABONL2U

    Account: 147850770

    Name: Marijn Haverbeke

    IBAN: NL26 RABO 0147 8507 70

Releases:

07-06-2011: Version 2.1:

Add
  a theme system
  (demo). Note that this is not
  backwards-compatible—you'll have to update your styles and
  modes!

07-06-2011: Version 2.02:

Add a Lua mode.

Fix reverse-searching for a regexp.

Empty lines can no longer break highlighting.

Rework scrolling model (the outer wrapper no longer does the scrolling).

Solve horizontal jittering on long lines.

Add runmode.js.

Immediately re-highlight text when typing.

Fix problem with 'sticking' horizontal scrollbar.

26-05-2011: Version 2.01:

Add a Smalltalk mode.

Add a reStructuredText mode.

Add a Python mode.

Add a PL/SQL mode.

coordsChar now works

Fix a problem where onCursorActivity interfered with onChange.

Fix a number of scrolling and mouse-click-position glitches.

Pass information about the changed lines to onChange.

Support cmd-up/down on OS X.

Add triple-click line selection.

Don't handle shift when changing the selection through the API.

Support "nocursor" mode for readOnly option.

Add an onHighlightComplete option.

Fix the context menu for Firefox.

28-03-2011: Version 2.0:

CodeMirror 2 is a complete rewrite that's
  faster, smaller, simpler to use, and less dependent on browser
  quirks. See this
  and this
  for more information.

28-03-2011: Version 1.0:

Fix error when debug history overflows.

Refine handling of C# verbatim strings.

Fix some issues with JavaScript indentation.

22-02-2011: Version 2.0 beta 2:

Somewhate more mature API, lots of bugs shaken out.

17-02-2011: Version 0.94:

tabMode: "spaces" was modified slightly (now indents when something is selected).

Fixes a bug that would cause the selection code to break on some IE versions.

Disabling spell-check on WebKit browsers now works.

08-02-2011: Version 2.0 beta 1:

CodeMirror 2 is a complete rewrite of
  CodeMirror, no longer depending on an editable frame.

Older releases...

  <form action="https://www.paypal.com/cgi-bin/webscr" method="post" id="paypal">
    <input type="hidden" name="cmd" value="_s-xclick"/>
    <input type="hidden" name="hosted_button_id" value="3FVHS5FGUY7CC"/>
  </form>


text:
using System;
using System.Globalization;
using System.Runtime.InteropServices.ComTypes;

namespace MsgPack.Serialization.DefaultSerializers
{
	/// <summary>
	///		Provides runtime selection ability for <see cref="FILETIME"/> serialization.
	/// </summary>
	internal class FileTimeMessagePackSerializerProvider : MessagePackSerializerProvider
	{
		private readonly IMessagePackSingleObjectSerializer _unixEpoc;
		private readonly IMessagePackSingleObjectSerializer _native;

		public FileTimeMessagePackSerializerProvider( SerializationContext context, bool isNullable )
		{
			if ( isNullable )
			{
#if !UNITY
				this._unixEpoc =
					new NullableMessagePackSerializer<FILETIME>( context, new UnixEpocFileTimeMessagePackSerializer( context ) );
				this._native =
					new NullableMessagePackSerializer<FILETIME>( context, new NativeFileTimeMessagePackSerializer( context ) );
#else
				this._unixEpoc =
					new NullableMessagePackSerializer( context, typeof( FILETIME? ), new UnixEpocFileTimeMessagePackSerializer( context ) );
				this._native =
					new NullableMessagePackSerializer( context, typeof( FILETIME? ), new NativeFileTimeMessagePackSerializer( context ) );
#endif // !UNITY
			}
			else
			{
				this._unixEpoc = new UnixEpocFileTimeMessagePackSerializer( context );
				this._native = new NativeFileTimeMessagePackSerializer( context );
			}
		}

		public override object Get( SerializationContext context, object providerParameter )
		{
			if ( providerParameter is DateTimeConversionMethod )
			{
				switch ( ( DateTimeConversionMethod )providerParameter )
				{
					case DateTimeConversionMethod.Native:
					{
						return this._native;
					}
					case DateTimeConversionMethod.UnixEpoc:
					{
						return this._unixEpoc;
					}
				}
			}

			switch ( context.DefaultDateTimeConversionMethod )
			{
				case DateTimeConversionMethod.Native:
				{
					return this._native;
				}
				case DateTimeConversionMethod.UnixEpoc:
				{
					return this._unixEpoc;
				}
				default:
				{
					throw new NotSupportedException(
						String.Format(
							CultureInfo.CurrentCulture,
							"Unknown {0} value '{1:G}'({1:D})'",
							typeof( DateTimeConversionMethod ),
							context.DefaultDateTimeConversionMethod
						)
					);
				}
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.springfox.loader</groupId>
    <artifactId>springfox-loader</artifactId>
    <version>2.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <springfox.version>2.9.2</springfox.version>
        <spring.version>2.1.1.RELEASE</spring.version>
        <jackson.version>2.9.7</jackson.version>

        <cglib.version>3.2.10</cglib.version>
        <spock.version>1.1-groovy-2.4</spock.version>
        <jsonpath.version>2.4.0</jsonpath.version>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-beans</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-aop</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>${spring.version}</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.4.0-b180725.0427</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>${jsonpath.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>${cglib.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-core</artifactId>
            <version>${spock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-spring</artifactId>
            <version>${spock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>versions-maven-plugin</artifactId>
                <version>2.5</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.gmavenplus</groupId>
                <artifactId>gmavenplus-plugin</artifactId>
                <version>1.5</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20</version>
                <configuration>
                    <includes>
                        <include>**/*Spec.java</include>
                    </includes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>add-test-source</id>
                        <phase>generate-test-sources</phase>
                        <goals>
                            <goal>add-test-source</goal>
                        </goals>
                        <configuration>
                            <sources>
                                <source>src/test/groovy</source>
                            </sources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>3.0.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.4</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.9</version>
                <executions>
                    <execution>
                        <id>prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.eluder.coveralls</groupId>
                <artifactId>coveralls-maven-plugin</artifactId>
                <version>4.3.0</version>
                <configuration>
                    <repoToken>${env.COVERALLS_REPO_TOKEN}</repoToken>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>http://repo.spring.io/release</url>
        </repository>
        <repository>
            <id>jcenter</id>
            <url>http://jcenter.bintray.com/</url>
        </repository>
    </repositories>

    <distributionManagement>
        <repository>
            <id>bintray-jarlehansen-maven</id>
            <name>jarlehansen-maven</name>
            <url>https://api.bintray.com/maven/jarlehansen/maven/springfox-loader/;publish=1</url>
        </repository>
    </distributionManagement>
</project>


text:
namespace ceres {
namespace internal {

// LowRankInverseHessian is a positive definite approximation to the
// Hessian using the limited memory variant of the
// Broyden-Fletcher-Goldfarb-Shanno (BFGS)secant formula for
// approximating the Hessian.
//
// Other update rules like the Davidon-Fletcher-Powell (DFP) are
// possible, but the BFGS rule is considered the best performing one.
//
// The limited memory variant was developed by Nocedal and further
// enhanced with scaling rule by Byrd, Nocedal and Schanbel.
//
// Nocedal, J. (1980). "Updating Quasi-Newton Matrices with Limited
// Storage". Mathematics of Computation 35 (151): 773–782.
//
// Byrd, R. H.; Nocedal, J.; Schnabel, R. B. (1994).
// "Representations of Quasi-Newton Matrices and their use in
// Limited Memory Methods". Mathematical Programming 63 (4):
class LowRankInverseHessian : public LinearOperator {
 public:
  // num_parameters is the row/column size of the Hessian.
  // max_num_corrections is the rank of the Hessian approximation.
  // use_approximate_eigenvalue_scaling controls whether the initial
  // inverse Hessian used during Right/LeftMultiply() is scaled by
  // the approximate eigenvalue of the true inverse Hessian at the
  // current operating point.
  // The approximation uses:
  // 2 * max_num_corrections * num_parameters + max_num_corrections
  // doubles.
  LowRankInverseHessian(int num_parameters,
                        int max_num_corrections,
                        bool use_approximate_eigenvalue_scaling);
  virtual ~LowRankInverseHessian() {}

  // Update the low rank approximation. delta_x is the change in the
  // domain of Hessian, and delta_gradient is the change in the
  // gradient.  The update copies the delta_x and delta_gradient
  // vectors, and gets rid of the oldest delta_x and delta_gradient
  // vectors if the number of corrections is already equal to
  // max_num_corrections.
  bool Update(const Vector& delta_x, const Vector& delta_gradient);

  // LinearOperator interface
  virtual void RightMultiply(const double* x, double* y) const;
  virtual void LeftMultiply(const double* x, double* y) const {
    RightMultiply(x, y);
  }
  virtual int num_rows() const { return num_parameters_; }
  virtual int num_cols() const { return num_parameters_; }

 private:
  const int num_parameters_;
  const int max_num_corrections_;
  const bool use_approximate_eigenvalue_scaling_;
  double approximate_eigenvalue_scale_;
  ColMajorMatrix delta_x_history_;
  ColMajorMatrix delta_gradient_history_;
  Vector delta_x_dot_delta_gradient_;
  std::list<int> indices_;
};

}  // namespace internal
}  // namespace ceres

#endif  // CERES_INTERNAL_LOW_RANK_INVERSE_HESSIAN_H_


text:
package com.github.sd4324530.jtuple;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author peiyu
 */
public class Tuple3Test {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Test
    public void testWith() {
        Tuple3 tuple3 = Tuple3.with(123, "test", 186.5);
        log.debug("tuple3:{}", tuple3.toString());
        log.debug("first:{}", tuple3.first);
        log.debug("second:{}", tuple3.second);
        log.debug("third:{}", tuple3.third);
    }

    @Test
    public void testSwap() {
        Tuple3 tuple3 = Tuple3.with(123, "test", 186.5);
        log.debug("reverse:{}", tuple3.reverse().toString());
    }
}


text:
package org.sidoh.reactor_simulator.simulator;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

public class ReactorParser {

  public static final char CONTROL_ROD = 'X';
  private FakeReactorWorld world;

  public ReactorParser(int height, String[] lines) {
    String first = lines[0].replaceAll(" ", "");
    this.world = new FakeReactorWorld(lines.length + 1, height, first.length() + 1);
    for (int i = 0; i < lines.length; i++) {
      String line = lines[i].replaceAll(" ", "");
      for (int j = 0; j < line.length(); j++) {
        char c = line.charAt(j);
        parse(i, j, c, world);
      }

    }
  }

  public static void parse(int i, int j, char c, FakeReactorWorld world) {
    if (c == CONTROL_ROD) {
      world.makeControlRod(i + 1, j + 1);
    } else if (c == 'O') {
      //Air column
    } else {
      String coolant = getCoolant(c);
      world.makeCoolantColumn(i + 1, j + 1, coolant);
    }
  }

  public FakeReactorWorld getWorld() {
    return world;
  }

  private static String getCoolant(char c) {
    return mappings.get(c);
  }

  public static BiMap<Character, String> mappings = HashBiMap.create();

  static {
    mappings.put('X', "entity:controlRod");
    mappings.put('O', "fluid:air");
    mappings.put('E', "fluid:ender");
    mappings.put('C', "fluid:cryotheum");
    mappings.put('D', "block:blockDiamond");
    mappings.put('P', "fluid:pyrotheum");
    mappings.put('G', "block:blockGraphite");
    mappings.put('M', "block:blockManyullyn");
  }
}


text:
package com.ociweb.pronghorn.ring.threading;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ociweb.pronghorn.GraphManager;
import com.ociweb.pronghorn.ring.stage.PronghornStage;

public class ThreadPerStageManager extends StageManager {
	private static final Logger log = LoggerFactory.getLogger(ThreadPerStageManager.class);

	private ExecutorService executorService;
	private volatile boolean isShutDownNow = false;
	private volatile boolean isShuttingDown = false;

	public ThreadPerStageManager(GraphManager graphManager) {
		super(graphManager);

		this.executorService = Executors.newCachedThreadPool();

	}

	public void startup() {

		int i = PronghornStage.totalStages();
		while (--i>=0) {
			PronghornStage stage = GraphManager.getStage(graphManager, i);
			if (null!=stage) {
				stage.startup();
				int rate = GraphManager.getScheduleRate(graphManager, stage.stageId);
				if (0==rate) {
					executorService.execute(buildRunnable(stage));
				} else {
					executorService.execute(buildRunnable(rate, stage));
				}
			}
		}
	}

	public void shutdown(){
		GraphManager.terminateInputStages(graphManager);
	}

	/**
	 * Normal shutdown request, blocks until all the stages have finished by seeing the poison pill.
	 *
	 * @param timeout
	 * @param unit
	 * @return
	 */
	public boolean awaitTermination(long timeout, TimeUnit unit) {

		///TOOD: for simplicity this needs to terminate the inputs AND the inputs can block if needed.??

		isShuttingDown = true;
		executorService.shutdown();
		try {
			boolean cleanExit = executorService.awaitTermination(timeout, unit);
			assert(validShutdownState());
			return cleanExit;
		} catch (InterruptedException e) {
			executorService.shutdownNow();
			Thread.currentThread().interrupt();
		} catch (Throwable e) {
			log.trace("awaitTermination", e);
			return false;
		}
		return true;
	}

	/**
	 * Do not call this method except when the system has become hung.
	 * Work in the flow may be lost as a result.
	 */
	public boolean TerminateNow() {

		isShuttingDown = true;
		isShutDownNow = true;
		try {
			//give the stages 1 full second to shut down cleanly
			return executorService.awaitTermination(1, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			executorService.shutdownNow();
			Thread.currentThread().interrupt();
		}
		return true;
	}

	protected Runnable buildRunnable(final PronghornStage stage) {

		return new Runnable() {
			//once we get a thread we never give it back
			//because this is true we can name the thread as the name of the stage

			@Override
			public String toString() {
				//must pass stage name so thread knows name
				return stage.toString();
			}

			///TODO: call terminate from the source stage and set isShutting down.
			///TODO: convert all stages to use the stateless shutdown
			///TDOO: may have upstream must return true for source till it calls shutdown.

			@Override
			public void run() {
				try {
					do {
						assert(confirmRunStart(stage));
						stage.run();
						assert(confirmRunStop(stage));

					} while (!isShutDownNow && (!isShuttingDown || GraphManager.mayHaveUpstreamData(graphManager, stage.stageId) ));

					stage.shutdown();

				} catch (Throwable t) {
					log.error("Unexpected error in stage {}", stage);
					log.error("Stacktrace",t);
					GraphManager.shutdownNeighborRings(graphManager, stage);
					assert(confirmRunStop(stage));
				}
			}
		};
	}

	protected Runnable buildRunnable(final int nsScheduleRate, final PronghornStage stage) {

		return new Runnable() {
			//once we get a thread we never give it back
			//because this is true we can name the thread as the name of the stage

			@Override
			public String toString() {
				//must pass stage name so thread knows name
				return stage.toString();
			}

			/**
			 * Run the stage such that the leading edge of each run is nsScheduledRate apart.
			 * If the runtime of one pass is longer than the rate the runs will happen sequentially with no delay.
			 *
			 * stops calling when terminate is started
			 */
			@Override
			public void run() {
				try {
					do {
						long start = System.nanoTime();
						assert(confirmRunStart(stage));
						stage.run();

						int sleepFor = nsScheduleRate - (int)(System.nanoTime()-start);
						if (sleepFor>0) {
							int sleepMs = sleepFor/1000000;
							int sleepNs = sleepFor%1000000;
							Thread.sleep(sleepMs, sleepNs);
						};
						assert(confirmRunStop(stage));

					} while (!isShutDownNow && !isShuttingDown);

					stage.shutdown();

				} catch (Throwable t) {
					log.error("Unexpected error in stage {}", stage);
					log.error("Stacktrace",t);
					GraphManager.shutdownNeighborRings(graphManager, stage);
					Thread.currentThread().interrupt();
					assert(confirmRunStop(stage));
				}
			}
		};
	}
}


text:
namespace {

const wchar_t kStandardLogFile[] = L"operation_log.txt";

bool GetCrashServiceDirectory(FilePath* dir) {
  FilePath temp_dir;
  if (!file_util::GetTempDir(&temp_dir))
    return false;
  temp_dir = temp_dir.Append(L"chrome_crashes");
  if (!file_util::PathExists(temp_dir)) {
    if (!file_util::CreateDirectory(temp_dir))
      return false;
  }
  *dir = temp_dir;
  return true;
}

}  // namespace.

int __stdcall wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd_line,
                       int show_mode) {
  // Manages the destruction of singletons.
  base::AtExitManager exit_manager;

  CommandLine::Init(0, NULL);

  // We use/create a directory under the user's temp folder, for logging.
  FilePath operating_dir;
  GetCrashServiceDirectory(&operating_dir);
  FilePath log_file = operating_dir.Append(kStandardLogFile);

  // Logging to a file with pid, tid and timestamp.
  logging::InitLogging(log_file.value().c_str(), logging::LOG_ONLY_TO_FILE,
                       logging::LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE);
  logging::SetLogItems(true, true, true, false);

  LOG(INFO) << "session start. cmdline is [" << cmd_line << "]";

  CrashService crash_service(operating_dir.ToWStringHack());
  if (!crash_service.Initialize(::GetCommandLineW()))
    return 1;

  LOG(INFO) << "ready to process crash requests";

  // Enter the message loop.
  int retv = crash_service.ProcessingLoop();
  // Time to exit.
  LOG(INFO) << "session end. return code is " << retv;
  return retv;
}


text:
namespace {
    const std::string default_ca = "default_ca";
}

CASettings::CASettings(CONF* conf)
{
    auto casect_values = NCONF_get_section(conf, "ca");
    if (sk_CONF_VALUE_num(casect_values) == 0) {
        BOOST_LOG_TRIVIAL(trace) << "No ca section";
        return;
    }

    auto keys = ConfHelper::to_map(casect_values);

    if (!keys.count("default_ca")) {
        BOOST_LOG_TRIVIAL(trace) << "No default_ca";
        return;
    }

    // Find default_ca section naming the CA section
    ca_section_name = keys["default_ca"];
    BOOST_LOG_TRIVIAL(debug) << "CA section named: \"" << ca_section_name << "\"";

    values = ConfHelper::to_map(NCONF_get_section(conf, ca_section_name.c_str()));

}

Menu::Item CASettings::createMenu(CASettings& settings) {
    Menu mnu("CA settings");
    return {"CA", mnu};
}


text:
typedef struct {
    double x, y;
} Dpoint2d;

class CDemoView : public CScrollView
{
protected: // create from serialization only
	CDemoView();
	DECLARE_DYNCREATE(CDemoView)

// Attributes
public:
	CDemoDoc* GetDocument();

// Operations
public:

// Overrides
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CDemoView)
	public:
	virtual void OnDraw(CDC* pDC);  // overridden to draw this view
	virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
	protected:
	virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
	virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
	virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
	virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint);
	virtual void OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView);
	//}}AFX_VIRTUAL

// Implementation
public:
	void GetImageXY(CDemoDoc *pDoc, CxImage *ima, long *x, long *y);
	bool SetImageRectSelection(CDemoDoc *pDoc,CRect *rect);
	virtual ~CDemoView();
#ifdef _DEBUG
	virtual void AssertValid() const;
	virtual void Dump(CDumpContext& dc) const;
#endif

#if CXIMAGE_DEMO_SELECT
	long m_SelCount;
	long m_SelShift;
	void DrawSelection();
	CPoint m_RefPoint,m_RefScroll;
#endif
protected:
	CBrush m_brHatch;

	CRectTracker m_tracker;

// Generated message map functions
protected:
	//{{AFX_MSG(CDemoView)
	afx_msg void OnMouseMove(UINT nFlags, CPoint point);
	afx_msg BOOL OnEraseBkgnd(CDC* pDC);
	afx_msg void OnSetFocus(CWnd* pOldWnd);
	afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
	afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
	afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
	afx_msg void OnTimer(UINT nIDEvent);
	afx_msg void OnDestroy();
	afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
	afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
	afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
	//}}AFX_MSG
	afx_msg LRESULT OnNewImage(WPARAM wParam, LPARAM lParam);
	afx_msg LRESULT OnNewProgress(WPARAM wParam, LPARAM lParam);
	DECLARE_MESSAGE_MAP()
#ifdef VATI_EXTENSIONS
private:
	bool     m_suppressContextMenu;
	Dpoint2d m_oldPnt;
	Dpoint2d m_orgPnt;
	Dpoint2d m_dpnt[6];
#endif
};

#ifndef _DEBUG  // debug version in demoView.cpp
inline CDemoDoc* CDemoView::GetDocument()
   { return (CDemoDoc*)m_pDocument; }
#endif

/////////////////////////////////////////////////////////////////////////////


text:
'use strict';
// =========================================================================
//
// Routes for conditions
//
// =========================================================================
var Condition  = require ('../controllers/condition.controller');
var routes = require ('../../../core/server/controllers/core.routes.controller');
var policy = require ('../../../core/server/controllers/core.policy.controller');

module.exports = function (app) {
	routes.setCRUDRoutes (app, 'condition', Condition, policy);
};


text:
package org.cam.core.parser;

/**
 * Created by yaohui on 14-9-21.
 */
public class User3 {

    private String id;
    private int age;
    private String name;
    private boolean isEducated;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isEducated() {
        return isEducated;
    }

    public void setEducated(boolean isEducated) {
        this.isEducated = isEducated;
    }
}


text:
namespace llvm {
class DWPError : public ErrorInfo<DWPError> {
public:
  DWPError(std::string Info) : Info(std::move(Info)) {}
  void log(raw_ostream &OS) const override { OS << Info; }
  std::error_code convertToErrorCode() const override {
    llvm_unreachable("Not implemented");
  }
  static char ID;

private:
  std::string Info;
};
}

#endif


text:
"""
   Copyright 2013 DISQUS

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

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

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

import sys

from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, ValidationError
from django.db import connections, transaction
from django.db.models import loading, Manager, Model, signals
from django.db.models.base import ModelBase, subclass_exception
from django.db.models.fields import PositiveIntegerField
from django.db.models.fields.related import ForeignKey, ManyToOneRel, \
  RECURSIVE_RELATIONSHIP_CONSTANT, ReverseSingleRelatedObjectDescriptor
from django.db.utils import DatabaseError

from sqlshards.db.shards.fields import AutoSequenceField
from sqlshards.db.shards.helpers import get_sharded_id_sequence_name
from sqlshards.db.shards.manager import MasterPartitionManager
from sqlshards.utils import wraps

class PartitionedForeignKey(ForeignKey):
    """
    Behaves identical to a ForeignKey except it allows referencing an fkey
    that would live on the same cluster.
    """
    def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs):
        try:
            to._meta.object_name.lower()
        except AttributeError:  # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT
            assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
        else:
            # For backwards compatibility purposes, we need to *try* and set
            # the to_field during FK construction. It won't be guaranteed to
            # be correct until contribute_to_class is called. Refs #12190.
            to_field = to_field or (to._meta.pk and to._meta.pk.name)
        kwargs['verbose_name'] = kwargs.get('verbose_name', None)

        kwargs['rel'] = rel_class(to, to_field,
            related_name=kwargs.pop('related_name', None),
            limit_choices_to=kwargs.pop('limit_choices_to', None),
            parent_link=kwargs.pop('parent_link', False))
        super(ForeignKey, self).__init__(**kwargs)

        self.db_index = True

    def contribute_to_related_class(self, cls, related):
        # Reverse lookups not supported currently
        return

    def contribute_to_class(self, cls, name):
        # Pull in PartitionedReverseRelatedObjectDescriptor
        super(ForeignKey, self).contribute_to_class(cls, name)
        setattr(cls, self.name, PartitionedReverseRelatedObjectDescriptor(self))
        if isinstance(self.rel.to, basestring):
            target = self.rel.to
        else:
            target = self.rel.to._meta.db_table
        cls._meta.duplicate_targets[self.column] = (target, "o2m")

    def south_field_triple(self):
        "Returns a suitable description of this field for South."
        from south.modelsinspector import introspector
        field_class = "django.db.models.PositiveIntegerField"
        args, kwargs = introspector(self)
        return (field_class, [], {'db_column': "%r" % self.column})

class PartitionedReverseRelatedObjectDescriptor(ReverseSingleRelatedObjectDescriptor):
    """
    Identical to ReverseSingleRelatedObjectDescriptor except that we pass the key
    to the manager and relying on outside routing.
    """
    def __get__(self, instance, instance_type=None):
        if instance is None:
            return self

        cache_name = self.field.get_cache_name()
        try:
            return getattr(instance, cache_name)
        except AttributeError:
            val = getattr(instance, self.field.attname)
            if val is None:
                # If NULL is an allowed value, return it.
                if self.field.null:
                    return None
                raise self.field.rel.to.DoesNotExist
            other_field = self.field.rel.get_related_field()
            relname = self.field.rel.field_name
            if other_field.rel:
                params = {'%s__pk' % relname: val}
            else:
                params = {'%s__exact' % relname: val}

            # Ensure key is sent to the manager
            for field_name in instance._shards.key:
                params[field_name] = getattr(instance, field_name)

            # If the related manager indicates that it should be used for
            # related fields, respect that.
            rel_mgr = self.field.rel.to._default_manager
            rel_obj = rel_mgr.get(**params)
            setattr(instance, cache_name, rel_obj)
            return rel_obj

def resend_signal(new_sender):
    @wraps(new_sender)
    def wrapped(**kwargs):
        signal = kwargs.pop('signal')
        kwargs['sender'] = new_sender
        signal.send(**kwargs)
    return wrapped

def get_cluster_sizes(connections):
    """
    Returns a dictionary mapping clusters of servers (given
    by their naming scheme) and the number of connections in
    that cluster.
    """
    import re
    expr = re.compile(r'.*\.shard\d+$')
    clusters = {}
    for conn in connections:
        if not expr.match(conn):
            continue
        cluster = conn.split('.shard', 1)[0]
        if cluster not in clusters:
            clusters[cluster] = 1
        else:
            clusters[cluster] += 1
    return clusters

DEFAULT_NAMES = ('num_shards', 'key', 'sequence', 'abstract', 'cluster')
CLUSTER_SIZES = get_cluster_sizes(connections)

class MasterShardOptions(object):
    def __init__(self, options, nodes=[]):
        self.options = options
        self.nodes = nodes
        self.model = None
        self.name = None
        self.size = None

    def __repr__(self):
        return u'<%s: model=%s, options=%s, nodes=%s>' % (
            self.__class__.__name__, self.model,
            self.options, len(self.nodes))

    @property
    def is_child(self):
        return False

    @property
    def is_master(self):
        return True

    def contribute_to_class(self, cls, name):
        self.name = name
        self.model = cls
        setattr(cls, name, self)

        opts = self.options

        if opts:
            for k in (k for k in DEFAULT_NAMES if hasattr(opts, k)):
                setattr(self, k, getattr(opts, k))

        if not hasattr(self, 'sequence'):
            self.sequence = cls._meta.db_table

        if hasattr(self, 'cluster'):
            self.size = CLUSTER_SIZES[self.cluster]

        # We support both key = 'field_name' and key = ['field_name']
        # style declerations
        if hasattr(self, 'key') and isinstance(self.key, basestring):
            self.key = (self.key,)

    def get_key_from_instance(self, instance):
        """
        Return the routing key for an instance.

        >>> shard_key = Model._shards.get_key_from_instance(instance)
        """
        return self.get_key_from_kwargs(**dict((f, getattr(instance, f)) for f in self.key))

    def get_key_from_kwargs(self, **kwargs):
        """
        Return the routing key for an object given ``kwargs``.

        >>> shard_key = Model._shards.get_key_from_instance(forum_id=1)
        """
        return sum(int(kwargs[f]) for f in self.key)

class ShardOptions(object):
    def __init__(self, parent, num):
        self.parent = parent
        self.num = num
        self.model = None
        self.name = None

    def __repr__(self):
        return u'<%s: model=%s, parent=%s, num=%s>' % (
            self.__class__.__name__, self.model,
            self.parent, self.num)

    @property
    def is_child(self):
        return True

    @property
    def is_master(self):
        return False

    @property
    def key(self):
        return self.parent._shards.key

    @property
    def cluster(self):
        return self.parent._shards.cluster

    @property
    def sequence(self):
        return self.parent._shards.sequence

    def get_all_databases(self):
        """
        Returns a list of all database aliases that this shard is
        bound to.
        """
        return (self.get_database(), self.get_database(slave=True))

    def get_database(self, slave=False):
        parent = self.parent._shards
        if not parent.size:
            return
        alias = parent.cluster
        if slave:
            alias += '.slave'
        alias += '.shard%d' % (self.num % parent.size,)
        return alias

    def get_key_from_instance(self, *args, **kwargs):
        return self.parent._shards.get_key_from_instance(*args, **kwargs)

    def get_key_from_kwargs(self, *args, **kwargs):
        return self.parent._shards.get_key_from_kwargs(*args, **kwargs)

    def contribute_to_class(self, cls, name):
        self.name = name
        self.model = cls
        setattr(cls, name, self)

def generate_child_partition(parent, num):
    opts = parent._meta
    partition_name = '%s_Partition%s' % (parent.__name__, num)

    # HACK: Attempting to initialize a model twice results in a broken model
    # even though ModelBase is supposed to handle this case already.  Instead,
    # we explicitly check to make sure the model wasn't created yet by
    # using get_model to prevent this case.
    app_label = parent._meta.app_label
    m = loading.get_model(app_label, partition_name, seed_cache=False)
    if m is not None:
        return m

    partition = ModelBase(partition_name, (parent,), {
        '__module__': parent.__module__,
        'objects': Manager(),
        'Meta': type('Meta', (object,), {
            'managed': True,
            'db_table': '%s_%s' % (parent._meta.db_table, num),
            'unique_together': opts.unique_together,
        }),
        '_shards': ShardOptions(parent=parent, num=num),
    })
    partition.add_to_class('DoesNotExist', subclass_exception('DoesNotExist', (parent.DoesNotExist,), parent.__module__))
    partition.add_to_class('MultipleObjectsReturned', subclass_exception('MultipleObjectsReturned', (parent.MultipleObjectsReturned,), parent.__module__))

    # Connect signals so we can re-send them
    signaler = resend_signal(parent)
    for signal in (signals.pre_save, signals.post_save, signals.pre_delete, signals.post_delete,
                   signals.pre_init, signals.post_init, signals.m2m_changed):
        signal.connect(signaler, sender=partition, weak=False)

    # Ensure the partition is available within the module scope
    module = sys.modules[parent.__module__]
    setattr(module, partition.__name__, partition)

    # Register all partitions with Django
    loading.register_models(app_label, partition)

    return partition

class PartitionDescriptor(ModelBase):
    """
    Creates  partitions from the base model and attaches them to ``cls._shardss``.
    All children will also have ``cls._shards`` referencing the parent model.

    Also enforces the base model to be abstract, and assumes it's not a real table.
    """
    def __new__(cls, name, bases, attrs):
        # Force this model to be abstract as it's not a real table
        if 'Meta' not in attrs:
            is_abstract = False
            attrs['Meta'] = type('Meta', (object,), {
                'abstract': True,
            })
        else:
            is_abstract = getattr(attrs['Meta'], 'abstract', False)
            attrs['Meta'].abstract = True

        attrs['objects'] = MasterPartitionManager()

        new_cls = super(PartitionDescriptor, cls).__new__(cls, name, bases, attrs)

        attr_shardopts = attrs.pop('Shards', None)

        # HACK: non-abstract inheritance is not supported due to issues with metaclass
        # recursion
        if not any(b._shards.abstract if hasattr(b, '_shards') else True for b in bases):
            return new_cls

        if not attr_shardopts:
            shardopts = getattr(new_cls, 'Shards', None)
        else:
            shardopts = attr_shardopts
        base_shardopts = getattr(new_cls, '_shards', None)

        shards = []
        new_cls.add_to_class('_shards', MasterShardOptions(shardopts, nodes=shards))

        if base_shardopts:
            for k in DEFAULT_NAMES:
                if not hasattr(new_cls._shards, k):
                    setattr(new_cls._shards, k, getattr(base_shardopts, k, None))

        # We record the true abstract switch as part of _shards
        new_cls._shards.abstract = is_abstract

        if is_abstract:
            return new_cls

        # Some basic validation
        for k in DEFAULT_NAMES:
            if getattr(new_cls._shards, k, None) is None:
                raise ValidationError('Missing shard configuration value for %r on %r.' % (k, new_cls))

        new_cls.add_to_class('DoesNotExist', subclass_exception('DoesNotExist', (ObjectDoesNotExist,), new_cls.__module__))
        new_cls.add_to_class('MultipleObjectsReturned', subclass_exception('MultipleObjectsReturned', (MultipleObjectsReturned,), new_cls.__module__))

        # Because we're an abstract model, we must also fake our own registration
        app_label = new_cls._meta.app_label
        loading.register_models(app_label, new_cls)

        new_cls._really_prepare()

        # We need to create a model for each partition instance which is assigned to the
        # appropriate table
        for n in xrange(new_cls._shards.num_shards):
            partition = generate_child_partition(new_cls, n)

            # Add to list of partitions for this master
            shards.append(partition)

        return new_cls

    # Kill off default _prepare function
    _really_prepare = ModelBase._prepare
    # _prepare = lambda x: None

class PartitionModel(Model):
    __metaclass__ = PartitionDescriptor

    class Meta:
        abstract = True


text:
package emengjzs.emengdb.db;

import emengjzs.emengdb.util.byt.Slice;

import java.util.Comparator;

/**
 * Created by emengjzs on 2016/8/31.
 */
public class InternalKeyComparator implements Comparator<byte[]> {
    private InternalKeyCoder internalKeyCoder;
    private Comparator<Slice> userComparator;

    public InternalKeyComparator(Comparator<Slice> userComparator) {
        this.userComparator = userComparator;
    }

    public InternalKeyComparator() {
        this(Slice::compareTo);
    }

    public void setInternalKeyCoder(InternalKeyCoder internalKeyCoder) {
        this.internalKeyCoder = internalKeyCoder;
    }

    /**
     * user_key + -> seq - -> flag -
     */
    @Override
    public int compare(byte[] internalKey1, byte[] internalKey2) {
        Slice userKeySlice1 = internalKeyCoder.getUserKeySlice(internalKey1);
        Slice userKeySlice2 = internalKeyCoder.getUserKeySlice(internalKey2);

        /* user_key cmp(+) */
        int res = userComparator.compare(userKeySlice1, userKeySlice2);

        if (res == 0) {

            /* seq cmp(-) ,  flag cmp(-)*/
            return Long.compareUnsigned(
                    internalKeyCoder.decodeSeqAndType(internalKey1, userKeySlice1.length()),
                    internalKeyCoder.decodeSeqAndType(internalKey2, userKeySlice2.length()));
        }
        return res;
    }

    public Comparator<Slice> getUserComparator() {
        return this.userComparator;
    }

}


text:
package org.ujorm.wicket;

import java.io.Serializable;
import org.apache.wicket.protocol.http.WebApplication;
import org.ujorm.orm.OrmHandler;
import org.ujorm.orm.OrmHandlerProvider;
import org.ujorm.orm.Session;
import org.ujorm.tools.Assert;

/**
 * ORM Session Provider
 * @author Pavel Ponec
 */
public class OrmSessionProvider implements Serializable {
    private static final long serialVersionUID = 20130720L;

    /** Orm Session */
    private transient Session session;

    /** Create current ORM Handler */
    public static OrmHandler getOrmHandler() throws IllegalStateException {
        final WebApplication application = WebApplication.get();
        Assert.isTrue(application instanceof OrmHandlerProvider
                , "The {} must to implement: {}"
                , WebApplication.class
                , OrmHandlerProvider.class);
        return ((OrmHandlerProvider) application).getOrmHandler();
    }

    /** Create and cache the ORM Session, where created session must be closed later */
    public Session getSession() throws IllegalStateException {
        if (session == null) {
            session = getOrmHandler().createSession();
        }
        return session;
    }

    /** Close the session (if any)
     * and release the session for a garbage collector. */
    public boolean closeSession() {
        final boolean result = session != null;
        if (result) {
            session.close();
            session = null;
        }
        return result;
    }

    /** Is the session open? */
    public boolean isOpenSesson() {
        return session != null;
    }

}


text:
namespace tesseract {

/// Add coordinates to specified TextBlock, TextLine or String bounding box.
/// Add word confidence if adding to a String bounding box.
///
static void AddBoxToAlto(const ResultIterator* it, PageIteratorLevel level,
                         std::stringstream& alto_str) {
  int left, top, right, bottom;
  it->BoundingBox(level, &left, &top, &right, &bottom);

  int hpos = left;
  int vpos = top;
  int height = bottom - top;
  int width = right - left;

  alto_str << " HPOS=\"" << hpos << "\"";
  alto_str << " VPOS=\"" << vpos << "\"";
  alto_str << " WIDTH=\"" << width << "\"";
  alto_str << " HEIGHT=\"" << height << "\"";

  if (level == RIL_WORD) {
    int wc = it->Confidence(RIL_WORD);
    alto_str << " WC=\"0." << wc << "\"";
  } else {
    alto_str << ">";
  }
}

///
/// Append the ALTO XML for the beginning of the document
///
bool TessAltoRenderer::BeginDocumentHandler() {
  AppendString(
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
      "<alto xmlns=\"http://www.loc.gov/standards/alto/ns-v3#\" "
      "xmlns:xlink=\"http://www.w3.org/1999/xlink\" "
      "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
      "xsi:schemaLocation=\"http://www.loc.gov/standards/alto/ns-v3# "
      "http://www.loc.gov/alto/v3/alto-3-0.xsd\">\n"
      "\t<Description>\n"
      "\t\t<MeasurementUnit>pixel</MeasurementUnit>\n"
      "\t\t<sourceImageInformation>\n"
      "\t\t\t<fileName>");

  AppendString(title());

  AppendString(
      "\t\t\t</fileName>\n"
      "\t\t</sourceImageInformation>\n"
      "\t\t<OCRProcessing ID=\"OCR_0\">\n"
      "\t\t\t<ocrProcessingStep>\n"
      "\t\t\t\t<processingSoftware>\n"
      "\t\t\t\t\t<softwareName>tesseract ");
  AppendString(TessBaseAPI::Version());
  AppendString(
      "</softwareName>\n"
      "\t\t\t\t</processingSoftware>\n"
      "\t\t\t</ocrProcessingStep>\n"
      "\t\t</OCRProcessing>\n"
      "\t</Description>\n"
      "\t<Layout>\n");

  return true;
}

///
/// Append the ALTO XML for the layout of the image
///
bool TessAltoRenderer::AddImageHandler(TessBaseAPI* api) {
  const std::unique_ptr<const char[]> text(api->GetAltoText(imagenum()));
  if (text == nullptr) return false;

  AppendString(text.get());

  return true;
}

///
/// Append the ALTO XML for the end of the document
///
bool TessAltoRenderer::EndDocumentHandler() {
  AppendString("\t</Layout>\n</alto>\n");

  return true;
}

TessAltoRenderer::TessAltoRenderer(const char* outputbase)
    : TessResultRenderer(outputbase, "xml") {}

///
/// Make an XML-formatted string with ALTO markup from the internal
/// data structures.
///
char* TessBaseAPI::GetAltoText(int page_number) {
  return GetAltoText(nullptr, page_number);
}

///
/// Make an XML-formatted string with ALTO markup from the internal
/// data structures.
///
char* TessBaseAPI::GetAltoText(ETEXT_DESC* monitor, int page_number) {
  if (tesseract_ == nullptr || (page_res_ == nullptr && Recognize(monitor) < 0))
    return nullptr;

  int lcnt = 0, bcnt = 0, wcnt = 0;

  if (input_file_ == nullptr) SetInputName(nullptr);

#ifdef _WIN32
  // convert input name from ANSI encoding to utf-8
  int str16_len =
      MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1, nullptr, 0);
  wchar_t* uni16_str = new WCHAR[str16_len];
  str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1,
                                  uni16_str, str16_len);
  int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, nullptr,
                                     0, nullptr, nullptr);
  char* utf8_str = new char[utf8_len];
  WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str, utf8_len,
                      nullptr, nullptr);
  *input_file_ = utf8_str;
  delete[] uni16_str;
  delete[] utf8_str;
#endif

  std::stringstream alto_str;
  alto_str
      << "\t\t<Page WIDTH=\"" << rect_width_ << "\" HEIGHT=\""
      << rect_height_
      << "\" PHYSICAL_IMG_NR=\"" << page_number << "\""
      << " ID=\"page_" << page_number << "\">\n"
      << "\t\t\t<PrintSpace HPOS=\"0\" VPOS=\"0\""
      << " WIDTH=\"" << rect_width_ << "\""
      << " HEIGHT=\"" << rect_height_ << "\">\n";

  ResultIterator* res_it = GetIterator();
  while (!res_it->Empty(RIL_BLOCK)) {
    if (res_it->Empty(RIL_WORD)) {
      res_it->Next(RIL_WORD);
      continue;
    }

    if (res_it->IsAtBeginningOf(RIL_BLOCK)) {
      alto_str << "\t\t\t\t<TextBlock ID=\"block_" << bcnt << "\"";
      AddBoxToAlto(res_it, RIL_BLOCK, alto_str);
      alto_str << "\n";
    }

    if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) {
      alto_str << "\t\t\t\t\t<TextLine ID=\"line_" << lcnt << "\"";
      AddBoxToAlto(res_it, RIL_TEXTLINE, alto_str);
      alto_str << "\n";
    }

    alto_str << "\t\t\t\t\t\t<String ID=\"string_" << wcnt << "\"";
    AddBoxToAlto(res_it, RIL_WORD, alto_str);
    alto_str << " CONTENT=\"";

    bool last_word_in_line = res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD);
    bool last_word_in_block = res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD);

    int left, top, right, bottom;
    res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom);

    do {
      const std::unique_ptr<const char[]> grapheme(
          res_it->GetUTF8Text(RIL_SYMBOL));
      if (grapheme && grapheme[0] != 0) {
        alto_str << HOcrEscape(grapheme.get()).c_str();
      }
      res_it->Next(RIL_SYMBOL);
    } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD));

    alto_str << "\"/>";

    wcnt++;

    if (last_word_in_line) {
      alto_str << "\n\t\t\t\t\t</TextLine>\n";
      lcnt++;
    } else {
      int hpos = right;
      int vpos = top;
      res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom);
      int width = left - hpos;
      alto_str << "<SP WIDTH=\"" << width << "\" VPOS=\"" << vpos
               << "\" HPOS=\"" << hpos << "\"/>\n";
    }

    if (last_word_in_block) {
      alto_str << "\t\t\t\t</TextBlock>\n";
      bcnt++;
    }
  }

  alto_str << "\t\t\t</PrintSpace>\n"
           << "\t\t</Page>\n";
  const std::string& text = alto_str.str();

  char* result = new char[text.length() + 1];
  strcpy(result, text.c_str());
  delete res_it;
  return result;
}

}  // namespace tesseract


text:
<resources>

        <style name="progress_dialog" parent="@android:style/Theme.Dialog">
            <item name="android:windowFrame">@null</item>
            <item name="android:windowIsFloating">true</item>
            <item name="android:windowIsTranslucent">true</item>
            <item name="android:windowNoTitle">true</item>
            <item name="android:background">@null</item>
            <item name="android:windowBackground">@null</item>
            <item name="android:backgroundDimEnabled">false</item>
        </style>

    <style name="mySwitch" parent="Theme.AppCompat.Light">
        <!-- switch 打开时的按钮的颜色 轨迹颜色默认为30%(看效果就明白30%是怎么回事了)这个颜色 -->
        <item name="colorControlActivated">#FF4081</item>
        <!--  switch关闭时的按钮的颜色 -->
        <item name="colorSwitchThumbNormal">#FFF</item>
        <!-- switch关闭时的轨迹的颜色 30%这个颜色 -->
        <item name="android:colorForeground">#D3D3D3</item>

    </style>

    <style name="ShowPhotoResult" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="colorPrimaryDark">#384A56</item>

    </style>

    <style name="login" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorAccent">#000</item>
        <item name="colorPrimaryDark">#90000000</item>
    </style>

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorAccent">#FF4081</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>

    </style>

    <style name="AppTheme.Wait" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorAccent">#FF4081</item>
        <item name="colorPrimaryDark">#90000000</item>

    </style>

    <style name="Discuss" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorAccent">#FF4081</item>
        <item name="colorPrimaryDark">#D3D3D3</item>

    </style>

    <style name="AppTheme.main" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowIsTranslucent">false</item>

    </style>

    <style name="FruitActivityTheme" parent="AppTheme">
        <item name="android:windowIsTranslucent">true</item><!--设置这个手势滑动的时候就不会变黑 ,具体查看git-->
        <item name="android:windowAnimationStyle">@style/SlideRightAnimation</item>

    </style>

    <style name="AppTheme.translucent">
        <item name="colorPrimary">@color/black</item>
        <item name="android:windowBackground">@color/black</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.search" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorAccent">#00000000</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>

    </style>

    <style name="FlowLayout">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_marginTop">5dp</item>
        <item name="item_textColor">#9A9A9A</item>
        <item name="item_backgroundColor">#1E1E1E</item>
        <item name="item_selectedTextColor">#000000</item>
        <item name="item_selectedBackgroundColor">#ffffff</item>
        <item name="item_radius">5dp</item>
        <item name="item_strokeColor">#939393</item>
        <item name="item_selectedStrokeColor">#939393</item>
        <item name="item_strokeWidth">1px</item>
        <item name="item_horizontalSpacing">3dp</item>
        <item name="item_horizontalPadding">5dp</item>
        <item name="item_verticalPadding">5dp</item>
        <item name="item_width">111</item>
        <item name="item_height">30</item>
        <item name="item_maxEms">5</item>
        <item name="item_multiChooseable">true</item>
    </style>

    <style name="FlowLayout1">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_marginTop">5dp</item>
        <item name="item_textColor">#9A9A9A</item>
        <item name="item_backgroundColor">#1E1E1E</item>
        <item name="item_selectedTextColor">#000000</item>
        <item name="item_selectedBackgroundColor">#ffffff</item>
        <item name="item_radius">5dp</item>
        <item name="item_strokeColor">#939393</item>
        <item name="item_selectedStrokeColor">#939393</item>
        <item name="item_strokeWidth">1px</item>
        <item name="item_horizontalSpacing">10dp</item>
        <item name="item_horizontalPadding">5dp</item>
        <item name="item_verticalPadding">5dp</item>
        <item name="item_width">168</item>
        <item name="item_height">30</item>
        <item name="item_maxEms">5</item>
        <item name="item_multiChooseable">true</item>
    </style>
</resources>


text:
#include <libcgc.h>
#include <stdlib.h>
#include <stdio.h>

#include "monte.h"
#include "block.h"

#define PI 3.14126535
#define CHECKS 0x1000
#define COUNTER_MAX 0x100

uint8* random_page = (uint8*)RANDOM_PAGE_ADDRESS;

float64 kajigger;
uint64 counter;

float64 splatter = 128.0;
float64 scaler = 1.0;

float64 monte_gen();
float64 kajigger_from_random_int(uint64 random_int);

void monte_initialize() {
  uint64* random_uint_page = (uint64*) random_page;
  kajigger = kajigger_from_random_int(random_uint_page[0]);
  counter = 0;
}

float64 kajigger_from_random_int(uint64 random_int) {
  float64 cast = (float64) random_int;
  float64 sine = sin(cast);
  uint64  sine_bytes = *((uint64*)&sine);
  uint64 new_sine_bytes = sine_bytes & 0xffffffffffff0000;
  return *((float64*)&new_sine_bytes);
}

void monte_adjust(float64 new_splatter, float64 new_scaler) {
  splatter = new_splatter;
  scaler = new_scaler;
}

float64 monte_gen_step(float64 kj, uint64 ctr, float64 spl, float64 scl) {
  float64 line = tan(sin(kj + (spl * ctr))) * (2.0 / PI);
  return (line + 1) * scl;
}

float64 monte_gen() {
  float64 result = monte_gen_step(kajigger, counter, splatter, scaler);
  counter++;
  if (counter >= COUNTER_MAX) counter = 0;

  return result;
}

uint8 monte_happy() {
  uint64 in_circle = 0;

  for (int i = 0; i < CHECKS; i++) {
    float64 x = monte_gen();
    float64 y = monte_gen();

    float64 dist = sqrt((x * x) + (y * y));

    if (dist <= 1) in_circle++;
  }

  float64 ratio = ((float64) in_circle) / ((float64)CHECKS);

  float64 diff = fabs((4 * ratio) - PI);

  float64 doubler_size = 50 * log10(1.0 / diff);
  /* printf("scl %f rat %f dif %f dbl %f\n", scaler, ratio, diff, doubler_size); */
  if (doubler_size > 254.0) return 0xff;
  if (doubler_size < 1.0) return 0;

  return (uint8) doubler_size;
}

uint8 check_random_params(float64 check_kj,
                          uint64 check_counter,
                          float64 spl,
                          float64 scl) {
  float64 existing_kajigger = kajigger;
  kajigger = check_kj;
  uint64 existing_counter = counter;
  counter = check_counter;

  float64 existing_splatter = splatter;
  float64 existing_scaler = scaler;

  splatter = spl;
  scaler = scl;
  uint8 size = monte_happy();

  counter = existing_counter;
  kajigger = existing_kajigger;
  splatter = existing_splatter;
  scaler = existing_scaler;

  return size;
}


text:
namespace ash {
namespace mus {

StatusLayoutManager::StatusLayoutManager(ui::Window* owner)
    : LayoutManager(owner),
      alignment_(mash::shelf::mojom::Alignment::BOTTOM),
      auto_hide_behavior_(mash::shelf::mojom::AutoHideBehavior::NEVER) {
  AddLayoutProperty(ui::mojom::WindowManager::kPreferredSize_Property);
}

StatusLayoutManager::~StatusLayoutManager() {}

// We explicitly don't make assertions about the number of children in this
// layout as the number of children can vary when the application providing the
// status area restarts.

void StatusLayoutManager::LayoutWindow(ui::Window* window) {
  if (GetAshWindowType(window) != mojom::AshWindowType::STATUS_AREA) {
    // TODO(jamescook): Layout for notifications and other windows.
    NOTIMPLEMENTED() << "Non-status-area window needs layout.";
    return;
  }
  gfx::Size size = GetWindowPreferredSize(window);
  if (alignment_ == mash::shelf::mojom::Alignment::BOTTOM) {
    const int y = owner()->bounds().height() - size.height();
    // TODO(msw): Place the status area widget on the left for RTL UIs.
    window->SetBounds(gfx::Rect(owner()->bounds().width() - size.width(), y,
                                size.width(), size.height()));
  } else {
    const int x = (alignment_ == mash::shelf::mojom::Alignment::LEFT)
                      ? 0
                      : (owner()->bounds().width() - size.width());
    window->SetBounds(gfx::Rect(x, owner()->bounds().height() - size.height(),
                                size.width(), size.height()));
  }
}

void StatusLayoutManager::SetAlignment(
    mash::shelf::mojom::Alignment alignment) {
  if (alignment_ == alignment)
    return;

  alignment_ = alignment;
  for (ui::Window* window : owner()->children())
    LayoutWindow(window);
}

void StatusLayoutManager::SetAutoHideBehavior(
    mash::shelf::mojom::AutoHideBehavior auto_hide) {
  if (auto_hide_behavior_ == auto_hide)
    return;

  auto_hide_behavior_ = auto_hide;
  NOTIMPLEMENTED();
}

}  // namespace mus
}  // namespace ash


text:
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *

from enum import Enum
from typing import Dict, List, Callable, Tuple
import traceback
import requests
import json

# Disable insecure warnings
requests.packages.urllib3.disable_warnings()

MAX_API_COUNT: int = 100000
BASE_URL = "https://api-feeds.cyren.com/v1/feed"
VERSION = "1.5.0"
BAD_IP_RISK_BOUNDARY = 80

class FeedPath(str, Enum):
    DATA = "data"
    INFO = "info"

class FeedName(str, Enum):
    IP_REPUTATION = "ip_reputation"
    PHISHING_URLS = "phishing_urls"
    MALWARE_URLS = "malware_urls"
    MALWARE_FILES = "malware_files"

class RelationshipIndicatorType(str, Enum):
    IP = "IP"
    URL = "URL"
    SHA256 = "SHA-256"
    UNKNOWN = "UNKNOWN"

class FeedAction(str, Enum):
    ADD = "+"
    UPDATE = "="
    REMOVE = "-"

    def get_human_readable_name(self):
        name = str(self.name)
        return name.lower()

class FeedCategory(str, Enum):
    SPAM = "spam"
    PHISHING = "phishing"
    MALWARE = "malware"
    CONFIRMED_CLEAN = "confirmed clean"

class FeedSource(str, Enum):
    PRIMARY = "primary"
    RELATED = "related"

def get_relationship_value_type(relationship: Dict) -> Tuple[RelationshipIndicatorType, str, str]:
    related_entity_type = relationship.get("related_entity_type", "")
    relationship_value = relationship.get("related_entity_identifier", "")
    if related_entity_type == "file":
        return RelationshipIndicatorType.SHA256, relationship_value, FeedIndicatorType.File
    elif related_entity_type == "ip":
        return RelationshipIndicatorType.IP, relationship_value, FeedIndicatorType.IP

    return RelationshipIndicatorType.UNKNOWN, "", ""

class FeedEntryBase(object):
    def __init__(self, entry: Dict, feed_name: str):
        self.entry = entry
        self.feed_name = feed_name
        self.payload = self.entry.get("payload", dict())
        self.meta = self.payload.get("meta", dict())
        self.detection = self.payload.get("detection", dict())
        self.categories = self.detection.get("category", [])
        self.action = FeedAction(self.payload.get("action"))
        self.relationships = self.payload.get("relationships", [])

    def to_indicator_objects(self) -> List[Dict]:
        fields = self.get_fields()
        if any(self.relationships):
            relationship_indicators = []
            for relationship in self.relationships:
                relationship_type, relationship_value, _ = get_relationship_value_type(relationship)
                if not relationship_value:
                    continue

                relationship_indicators.append(dict(indicatortype=relationship_type.value,
                                                    relationshiptype=relationship.get("relationship_type", ""),
                                                    timestamp=relationship.get("relationship_ts"),
                                                    description=relationship.get("relationship_description", ""),
                                                    value=relationship_value,
                                                    entitycategory=relationship.get("related_entity_category", "")))
            fields["cyrenfeedrelationships"] = relationship_indicators

        raw_json = self.entry.copy()
        raw_json["source_tag"] = FeedSource.PRIMARY
        raw_json["tags"] = self.get_tags()
        primary = dict(value=self.get_value(), type=self.get_type(),
                       rawJSON=raw_json, score=self.get_score(),
                       fields=fields)

        indicators = self.get_indicators_from_relationships(primary)
        indicators.append(primary)
        return indicators

    def get_indicators_from_relationships(self, primary_indicator: Dict) -> List[Dict]:
        indicators = []
        for relationship in self.relationships:
            relationship_type, relationship_value, indicator_type = get_relationship_value_type(relationship)
            if not relationship_value:
                continue

            fields = dict(cyrenfeedrelationships=[dict(indicatortype=self.get_relationship_indicator_type().value,
                                                       relationshiptype=relationship.get("relationship_type"),
                                                       timestamp=relationship.get("relationship_ts"),
                                                       value=primary_indicator["value"],
                                                       entitycategory=relationship.get("related_entity_category"),
                                                       description=relationship.get("relationship_description"))])
            raw_json = dict(payload=relationship, source_tag=FeedSource.RELATED)
            indicators.append(dict(value=relationship_value,
                                   type=indicator_type,
                                   rawJSON=raw_json,
                                   score=self.get_relationship_score(primary_indicator, relationship),
                                   fields=fields))

        return indicators

    def get_score(self) -> int:
        if self.action in [FeedAction.ADD, FeedAction.UPDATE]:
            if FeedCategory.CONFIRMED_CLEAN in self.categories:
                return Common.DBotScore.NONE
            else:
                return Common.DBotScore.BAD

        if self.action == FeedAction.REMOVE:
            return Common.DBotScore.NONE

        return Common.DBotScore.BAD

    def get_relationship_score(self, primary_indicator: Dict, relationship: Dict) -> int:
        return Common.DBotScore.NONE

    def get_tags(self) -> List:
        detection_methods = self.payload.get("detection_methods", [])
        return self.categories + detection_methods

    def get_fields(self) -> Dict:
        timestamp = self.entry.get("timestamp")
        fields = dict(updateddate=timestamp,
                      indicatoridentification=self.payload.get("identifier"))

        if self.action == FeedAction.ADD:
            fields["published"] = timestamp

        return fields

    def get_offset(self) -> int:
        offset = self.entry.get("offset")
        if not offset:
            raise ValueError("expected an 'offset' field")

        return offset

    def get_type(self) -> str:
        raise NotImplementedError

    def get_value(self) -> str:
        raise NotImplementedError

    def get_relationship_indicator_type(self) -> RelationshipIndicatorType:
        raise NotImplementedError

class UrlFeedEntry(FeedEntryBase):
    def get_type(self) -> str:
        return FeedIndicatorType.URL

    def get_value(self) -> str:
        value = self.payload.get("url", "")
        value = value.rstrip("\n").rstrip("/")
        return value

    def get_tags(self) -> List:
        industries = self.detection.get("industry", [])
        brands = self.detection.get("brand", [])
        return super().get_tags() + industries + brands

    def get_relationship_indicator_type(self) -> RelationshipIndicatorType:
        return RelationshipIndicatorType.URL

class MalwareUrlFeedEntry(UrlFeedEntry):
    def get_relationship_score(self, primary_indicator: Dict, relationship: Dict) -> int:
        if primary_indicator["score"] < 2 or not relationship.get("related_entity_type") == "file":
            return super().get_relationship_score(primary_indicator, relationship)

        return primary_indicator["score"]

class IpReputationFeedEntry(FeedEntryBase):
    def get_type(self) -> str:
        return FeedIndicatorType.IP

    def get_value(self) -> str:
        return self.payload.get("identifier")

    def get_score(self) -> int:
        if self.action in [FeedAction.ADD, FeedAction.UPDATE]:
            if FeedCategory.SPAM in self.categories:
                risk = self.detection.get("risk", 0)
                if risk >= BAD_IP_RISK_BOUNDARY:
                    return Common.DBotScore.BAD
                return Common.DBotScore.SUSPICIOUS
            if FeedCategory.PHISHING in self.categories or FeedCategory.MALWARE in self.categories:
                return Common.DBotScore.SUSPICIOUS
            if FeedCategory.CONFIRMED_CLEAN in self.categories:
                return Common.DBotScore.NONE

        if self.action == FeedAction.REMOVE:
            return Common.DBotScore.NONE

        return Common.DBotScore.BAD

    def get_relationship_indicator_type(self) -> RelationshipIndicatorType:
        return RelationshipIndicatorType.IP

class MalwareFileFeedEntry(FeedEntryBase):
    def get_type(self) -> str:
        return FeedIndicatorType.File

    def get_value(self) -> str:
        return self.payload.get("identifier")

    def get_tags(self) -> List:
        family_names = self.detection.get("family_name", [])
        return super().get_tags() + family_names

    def get_relationship_indicator_type(self) -> RelationshipIndicatorType:
        return RelationshipIndicatorType.SHA256

FEED_TO_ENTRY_CLASS: Dict[str, Callable] = {
    FeedName.IP_REPUTATION: IpReputationFeedEntry,
    FeedName.PHISHING_URLS: UrlFeedEntry,
    FeedName.MALWARE_URLS: MalwareUrlFeedEntry,
    FeedName.MALWARE_FILES: MalwareFileFeedEntry,
}

FEED_TO_VERSION: Dict[str, str] = {
    FeedName.IP_REPUTATION: "_v2",
    FeedName.PHISHING_URLS: "_v2",
    FeedName.MALWARE_URLS: "_v2",
    FeedName.MALWARE_FILES: "_v2",
}

FEED_OPTION_TO_FEED: Dict[str, str] = {
    "IP Reputation": FeedName.IP_REPUTATION,
    "Phishing URLs": FeedName.PHISHING_URLS,
    "Malware URLs": FeedName.MALWARE_URLS,
    "Malware Hashes": FeedName.MALWARE_FILES,
}

class InvalidAPITokenException(Exception):
    pass

class InvalidAPIUrlException(Exception):
    pass

class Client(BaseClient):
    PARAMS = {"format": "jsonl"}
    INVALID_TOKEN_TEXTS = [
        "unable to parse claims from token",
        "unable to parse token from header",
        "token was revoked",
        "claims are invalid",
    ]

    def __init__(self, feed_name: str, api_token: str, *args, **kwargs):
        if not feed_name:
            raise ValueError("please specify a correct feed name")

        super().__init__(*args, **kwargs)
        self.feed_name = feed_name
        self.request_headers = {
            "Authorization": f"Bearer {api_token}",
            "Cyren-Client-Name": "Palo Alto Cortex XSOAR",
            "Cyren-Client-Version": VERSION,
        }

    def _is_invalid_token(self, response: requests.Response) -> bool:
        if response.status_code != 400:
            return False

        for invalid_text in self.INVALID_TOKEN_TEXTS:
            if invalid_text in response.text:
                return True

        return False

    def _do_request(self, path: str, offset: int = -1, count: int = 0) -> requests.Response:
        params = self.PARAMS.copy()
        params["feedId"] = f"{self.feed_name}{FEED_TO_VERSION[self.feed_name]}"
        if offset > -1:
            params["offset"] = str(offset)
        if count > 0:
            params["count"] = str(count)

        demisto.debug(f"using path {path}, params {params} for request")

        try:
            response = self._http_request(method="GET", url_suffix=path,
                                          headers=self.request_headers,
                                          params=params, resp_type="",
                                          ok_codes=[200, 204, 201, 400, 404])
        except requests.ConnectionError as e:
            raise requests.ConnectionError(f"Failed to establish a new connection: {str(e)}")

        if self._is_invalid_token(response):
            raise InvalidAPITokenException()

        if response.status_code == 404:
            raise InvalidAPIUrlException()

        response.raise_for_status()

        return response

    def fetch_entries(self, offset: int, count: int) -> List[Dict]:
        result = []
        response = self._do_request(path=FeedPath.DATA, offset=offset, count=count)

        for json_line in response.content.splitlines():
            try:
                result.append(json.loads(json_line))
            except json.JSONDecodeError as je:
                demisto.info(f"error while parsing single JSON feed line: {str(je)} {json_line!r}")
                continue

        return result

    def get_offsets(self) -> Dict[str, int]:
        response = self._do_request(path=FeedPath.INFO)
        try:
            return json.loads(response.content)
        except Exception as e:
            demisto.error(f"error while parsing JSON: {str(e)} {response.content!r}")
            raise

def store_offset_in_context(offset: int) -> int:
    integration_context = get_integration_context()
    integration_context["offset"] = offset
    set_integration_context(integration_context)
    return offset

def get_offset_from_context() -> int:
    integration_context = get_integration_context()
    return integration_context.get("offset")

def test_module_command(client: Client) -> str:
    try:
        entries = client.fetch_entries(0, 10)
        if not any(entries):
            return "Test failed because no indicators could be fetched!"
    except InvalidAPITokenException:
        return "Test failed because of an invalid API token!"
    except InvalidAPIUrlException:
        return "Test failed because of an invalid API URL!"
    except Exception as e:
        return f"Test failed because of: {str(e)}!"

    return "ok"

def get_indicators_command(client: Client, args: Dict) -> CommandResults:
    max_indicators = int(args.get("max_indicators", 50))

    count = max_indicators
    end_offset = client.get_offsets().get("endOffset")
    if end_offset:
        offset = max(end_offset - max_indicators + 1, 0)
    else:
        offset = 0

    entries = client.fetch_entries(offset, count)
    indicators, _ = feed_entries_to_indicator(entries, client.feed_name)

    human_readable = tableToMarkdown("Indicators from Cyren Threat InDepth:", indicators,
                                     headers=["value", "type", "rawJSON", "score"])
    return CommandResults(readable_output=human_readable,
                          raw_response=indicators)

def reset_offset_command(client: Client, args: Dict) -> CommandResults:
    offset = int(args.get("offset", -1))
    offset_stored = get_offset_from_context()
    offset_api = int(client.get_offsets().get("endOffset", -1))
    if offset < 0 or offset > offset_api:
        offset = offset_api

    store_offset_in_context(offset)

    offset_stored_text = offset_stored or "not set before"
    readable_output = (
        f"Reset Cyren Threat InDepth {client.feed_name} feed client offset to {offset} "
        f"(API provided max offset of {offset_api}, was {offset_stored_text})."
    )
    return CommandResults(readable_output=readable_output, raw_response=offset)

def get_offset_command(client: Client, args: Dict) -> CommandResults:
    offset_stored = get_offset_from_context()
    offset_api = int(client.get_offsets().get("endOffset", -1))
    offset_api_text = f"(API provided max offset of {offset_api})"
    if offset_stored:
        readable_output = (
            f"Cyren Threat InDepth {client.feed_name} feed client offset is {offset_stored} "
            f"{offset_api_text}."
        )
    else:
        readable_output = (
            f"Cyren Threat InDepth {client.feed_name} feed client offset has not been set yet "
            f"{offset_api_text}."
        )
    return CommandResults(readable_output=readable_output, raw_response=offset_stored)

def feed_entries_to_indicator(entries: List[Dict], feed_name: str) -> Tuple[List[Dict], int]:
    indicators: List[Dict] = []
    max_offset: int = -1
    for entry in entries:
        entry_obj = FEED_TO_ENTRY_CLASS[feed_name](entry, feed_name)
        max_offset = max(entry_obj.get_offset() + 1, max_offset)
        indicators = indicators + entry_obj.to_indicator_objects()

    return indicators, max_offset

def fetch_indicators_command(client: Client, initial_count: int, max_indicators: int, update_context: bool) -> List[Dict]:
    offset = get_offset_from_context()
    count = max_indicators
    if not offset:
        offset = int(client.get_offsets().get("endOffset", -1))
        if initial_count > 0:
            offset = offset - initial_count + 1
            count = max_indicators + initial_count

    count = min(MAX_API_COUNT, count)

    entries = client.fetch_entries(offset, count)
    demisto.debug(f"pulled {len(entries)} for {client.feed_name}")
    indicators, max_offset = feed_entries_to_indicator(entries, client.feed_name)
    demisto.debug(f"about to ingest {len(indicators)} for {client.feed_name}")

    if update_context:
        store_offset_in_context(max_offset)

    return indicators

def main():
    params = demisto.params()
    api_token = params.get("apikey")

    feed_name = params.get("feed_name")
    feed_name = FEED_OPTION_TO_FEED.get(feed_name, "")

    max_indicators = int(params.get("max_indicators", MAX_API_COUNT))
    if max_indicators > MAX_API_COUNT:
        demisto.info(f"using a maximum value for max_indicators of {MAX_API_COUNT} instead of {max_indicators}!")
        max_indicators = MAX_API_COUNT

    proxy = params.get("proxy", False)
    verify_certificate = not params.get("insecure", False)

    demisto.info(f"using feed {feed_name}, max {max_indicators}")
    commands: Dict[str, Callable] = {
        "cyren-threat-indepth-get-indicators": get_indicators_command,
        "cyren-threat-indepth-reset-client-offset": reset_offset_command,
        "cyren-threat-indepth-get-client-offset": get_offset_command,
    }

    command = demisto.command()
    demisto.info(f"Command being called is {command}")

    error = None
    try:
        client = Client(feed_name=feed_name,
                        base_url=BASE_URL,
                        verify=verify_certificate,
                        api_token=api_token,
                        proxy=proxy)

        if command == "fetch-indicators":
            indicators = fetch_indicators_command(client=client,
                                                  initial_count=0,
                                                  max_indicators=max_indicators,
                                                  update_context=True)
            for b in batch(indicators, batch_size=2000):
                demisto.createIndicators(b)
        elif command == "test-module":
            return_outputs(test_module_command(client))
        else:
            return_results(commands[command](client, demisto.args()))
    except InvalidAPITokenException:
        error = "Invalid API token!"
    except InvalidAPIUrlException:
        error = "Invalid API URL!"
    except Exception as e:
        demisto.error(traceback.format_exc())
        error = f"Error failed to execute {command}, error: [{e}]"

    if error:
        return_error(error)

if __name__ == "__builtin__" or __name__ == "builtins":
    main()


text:
import { formatDate } from 'pool-request/helpers/format-date';
import { module, test } from 'qunit';

module('Unit | Helper | format-date');

test('formats date', function(assert) {
  let result = formatDate([new Date(10000000000)]);
  assert.equal(result, '26/04/70');
});

test('returns empty string if no date passed in', function(assert) {
  let result = formatDate();
  assert.equal(result, '');
});


text:
namespace Encog.ML.Data.Versatile.Division
{
    /// <summary>
    /// A division of data inside of a versatile data set.
    /// </summary>
    public class DataDivision
    {
        /// <summary>
        /// The count of items in this partition.
        /// </summary>
        public int Count { get; set; }

        /// <summary>
        /// The percent of items in this partition.
        /// </summary>
        public double Percent { get; private set; }

        /// <summary>
        /// The dataset that we are dividing.
        /// </summary>
        public MatrixMLDataSet Dataset { get; set; }

        /// <summary>
        /// The mask of items we are to use.
        /// </summary>
        public int[] Mask { get; private set; }

        /// <summary>
        /// Construct a division.
        /// </summary>
        /// <param name="thePercent">The desired percentage in this division.</param>
        public DataDivision(double thePercent)
        {
            Percent = thePercent;
        }

        /// <summary>
        /// Allocat space to hold the mask.
        /// </summary>
        /// <param name="theSize">The mask size.</param>
        public void AllocateMask(int theSize)
        {
            Mask = new int[theSize];
        }

    }
}


text:
<?php

namespace Dosi\AuthBundle\DependencyInjection\Security\Factory;

use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AbstractFactory;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Abstract Single Sign On factory.
 */
abstract class AbstractSsoFactory extends AbstractFactory
{
    public function __construct()
    {
        $this->addOption('create_users', false);
        $this->addOption('created_users_roles', array('ROLE_USER'));
        $this->addOption('login_action', 'DosiAuthBundle:Sso:login');
        $this->addOption('logout_action', 'DosiAuthBundle:Sso:logout');
    }

    public function create(ContainerBuilder $container, $id, $config, $userProviderId, $defaultEntryPointId)
    {
        $this->createLogoutSuccessHandler($container, $id, $config);

        return parent::create($container, $id, $config, $userProviderId, $defaultEntryPointId);
    }

    public function getPosition()
    {
        return 'form';
    }

    protected function createAuthProvider(ContainerBuilder $container, $id, $config, $userProviderId)
    {
        $provider = 'security.authentication.provider.sso.'.$id;

        $container
            ->setDefinition($provider, new DefinitionDecorator('security.authentication.provider.sso'))
            ->replaceArgument(0, new Reference($userProviderId))
            ->replaceArgument(2, $config['create_users'])
            ->replaceArgument(3, $config['created_users_roles'])
        ;

        return $provider;
    }

    public function addConfiguration(NodeDefinition $node)
    {
        parent::addConfiguration($node);

        $node
            ->children()
                ->arrayNode('created_users_roles')
                    ->prototype('scalar')->end()
                ->end()
            ->end()
        ;
    }

    protected function createLogoutSuccessHandler(ContainerBuilder $container, $id, $config)
    {
        $templateHandler = 'security.logout.sso.success_handler';
        $realHandler     = 'security.logout.success_handler';

        // don't know if this is the right way, but it works
        $container
            ->setDefinition($realHandler.'.'.$id, new DefinitionDecorator($templateHandler))
            ->addArgument($config)
        ;
    }
}


text:
package server

import "fmt"

// Handle the "USER" command
func (c *clientHandler) handleUSER() {
	c.user = c.param
	c.writeMessage(331, "OK")
}

// Handle the "PASS" command
func (c *clientHandler) handlePASS() {
	var err error
	if c.driver, err = c.daddy.driver.AuthUser(c, c.user, c.param); err == nil {
		c.writeMessage(230, "Password ok, continue")
	} else if err != nil {
		c.writeMessage(530, fmt.Sprintf("Authentication problem: %v", err))
		c.disconnect()
	} else {
		c.writeMessage(530, "I can't deal with you (nil driver)")
		c.disconnect()
	}
}