text:
package hudson.init.impl;

import hudson.init.Initializer;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.compression.CompressionFilter;
import org.kohsuke.stapler.compression.UncaughtExceptionHandler;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.kohsuke.stapler.Stapler;

/**
 * @author Kohsuke Kawaguchi
 */
public class InstallUncaughtExceptionHandler {
    @Initializer
    public static void init(final Jenkins j) throws IOException {
        CompressionFilter.setUncaughtExceptionHandler(j.servletContext, new UncaughtExceptionHandler() {
            @Override
            public void reportException(Throwable e, ServletContext context, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
                req.setAttribute("javax.servlet.error.exception",e);
                try {
                    WebApp.get(j.servletContext).getSomeStapler()
                            .invoke(req,rsp, Jenkins.getInstance(), "/oops");
                } catch (ServletException x) {
                    if (!Stapler.isSocketException(x)) {
                        throw x;
                    }
                } catch (IOException x) {
                    if (!Stapler.isSocketException(x)) {
                        throw x;
                    }
                }
            }
        });
        try {
            Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler());
            DefaultUncaughtExceptionHandler.LOGGER.log(Level.FINE, "Successfully installed a global UncaughtExceptionHandler.");
        }
        catch (SecurityException ex) {
            DefaultUncaughtExceptionHandler.LOGGER.log(Level.SEVERE,
                                                       "Failed to set the default UncaughtExceptionHandler.  " +
                                                       "If any threads die due to unhandled coding errors then there will be no logging of this information.  " +
                                                       "The lack of this diagnostic information will make it harder to track down issues which will reduce the supportability of Jenkins.  " +
                                                       "It is highly recomended that you consult the documentation that comes with you servlet container on how to allow the " +
                                                       "`setDefaultUncaughtExceptionHandler` permission and enable it.", ex);
        }
    }

    /** An UncaughtExceptionHandler that just logs the exception */
    private static class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

        private static final Logger LOGGER = Logger.getLogger(InstallUncaughtExceptionHandler.class.getName());

        @Override
        public void uncaughtException(Thread t, Throwable ex) {
            // if this was an OutOfMemoryError then all bets about logging are off - but in the absence of anything else...
            LOGGER.log(Level.SEVERE,
                       "A thread (" + t.getName() + '/' + t.getId()
                                     + ") died unexpectedly due to an uncaught exception, this may leave your Jenkins in a bad way and is usually indicative of a bug in the code.",
                       ex);
        }

    }
}


text:
/** @file assume.h
	@author Jukka Jylänki
	@brief Global compilation defines. */
#pragma once

#include <sstream>
#include "../MathBuildConfig.h"
#include "MathNamespace.h"
#include <stdio.h>
#include "myassert.h"
#include "MathLog.h"

#ifndef MARK_UNUSED
/// If a variable is labelled with this directive, the compiler should not emit a warning even if it is unused in the code.
#define MARK_UNUSED(x) ((void)x)
#endif

#ifdef __GNUC__
/// If a variable or a function definition is labelled with this directive, the compiler should not emit a warning even if it is unused
/// in the code.
#define DONT_WARN_UNUSED __attribute__((unused))
#else
#define DONT_WARN_UNUSED
#endif

#ifndef ARRAY_LENGTH
#define ARRAY_LENGTH(x) (sizeof((x))/sizeof((x)[0]))
#endif

// The assume() macro is used to check preconditions on the math-related functions, e.g. whether vectors are normalized, check that division by zero doesn't occur, orthonormal bases, and so on.

// The assume() macro operates differently depending on which #defines are present:
// #define MATH_ASSERT_ON_ASSUME - the assume() macro resolves to the assert() macro.
// #define MATH_DISABLE_ASSUME   - the assume() macro is silent, and disabled altogether. (no prints or breaks or anything, the checks by assume() are ignored)
// If neither of the above is defined (default), then
//  - WIN32: if MathBreakOnAssume() == true, the system will break to debugger using a call to DebugBreak().
//  - Other: if MathBreakOnAssume() == true, the assume() macro is equal to the assert() macro.
//  -   All: if MathBreakOnAssume() == false, the assume() macro uses printf() to log warnings of failed math-related assumptions.

MATH_BEGIN_NAMESPACE

/// Assigns mathBreakOnAssume = isEnabled;
void SetMathBreakOnAssume(bool isEnabled);

/// Returns the current state of the math break-on-assume flag.
/// The default startup value for this flag is false.
bool MathBreakOnAssume();

/// Breaks to debugger if math break-on-assume flag
/// Returns the current state of the math break-on-assume flag.
bool AssumeFailed();

template<typename T>
inline std::string ObjToString(const T &obj)
{
	return obj.ToString();
}
/*
template<>
inline std::string ObjToString<const char*>(const char * const & obj)
{
	return obj;
}
*/
template<>
inline std::string ObjToString<std::string>(const std::string &obj)
{
	return obj;
}

template<>
inline std::string ObjToString<float>(const float &obj)
{
	std::stringstream ss;
	ss << obj;
	return ss.str();
}

template<>
inline std::string ObjToString<int>(const int &obj)
{
	std::stringstream ss;
	ss << obj;
	return ss.str();
}

template<>
inline std::string ObjToString<bool>(const bool &obj)
{
	std::stringstream ss;
	ss << obj;
	return ss.str();
}

template<>
inline std::string ObjToString<u32>(const u32 &obj)
{
	std::stringstream ss;
	ss << obj;
	return ss.str();
}

MATH_END_NAMESPACE

// If MATH_ENABLE_INSECURE_OPTIMIZATIONS is defined, all input data is assumed to be correct and will
// not be checked against at runtime.
// If this flag is undefined (the default), all input is sanity checked so that user cannot crash the system
// e.g. with out-of-bounds accesses.
//#define MATH_ENABLE_INSECURE_OPTIMIZATIONS

#ifdef FAIL_USING_EXCEPTIONS
#include <stdexcept>
#define assume_failed(message) throw std::runtime_error((message))
#elif defined(MATH_ASSERT_ON_ASSUME)
#define assume(x) assert(x)
#define assume_failed(message) assert(false && #message)
#elif defined(MATH_SILENT_ASSUME)
#define assume(x) ((void)0)
#define assume_failed(message) ((void)0)
#else
#define assume_failed(message) LOGE("Assumption \"%s\" failed! in file %s, line %d!", message, __FILE__, __LINE__)
#endif

#ifndef assume
#define assume(x) \
	MULTI_LINE_MACRO_BEGIN \
		if (!(x)) \
			assume_failed(#x " in " __FILE__ ":" STRINGIZE(__LINE__)); \
	MULTI_LINE_MACRO_END
#endif

// In assume1-assume4, print1-print4 are additional helper parameters that get printed out to log in case of failure.
#define assume1(x, print1) \
	MULTI_LINE_MACRO_BEGIN \
		if (!(x)) \
			assume_failed(((#x ", " #print1 ": ") + MATH_NS::ObjToString(print1) + \
			                  (" in " __FILE__ ":" STRINGIZE(__LINE__))).c_str()); \
	MULTI_LINE_MACRO_END
#define assert1 assume1

#define assume2(x, print1, print2) \
	MULTI_LINE_MACRO_BEGIN \
		if (!(x)) \
			assume_failed(((#x ", " #print1 ": ") + MATH_NS::ObjToString(print1) + \
			                  (", " #print2 ": ") + MATH_NS::ObjToString(print2) + \
			                  (" in " __FILE__ ":" STRINGIZE(__LINE__))).c_str()); \
	MULTI_LINE_MACRO_END
#define assert2 assume2

#define assume3(x, print1, print2, print3) \
	MULTI_LINE_MACRO_BEGIN \
		if (!(x)) \
			assume_failed(((#x ", " #print1 ": ") + MATH_NS::ObjToString(print1) + \
			                  (", " #print2 ": ") + MATH_NS::ObjToString(print2) + \
			                  (", " #print3 ": ") + MATH_NS::ObjToString(print3) + \
			                  (" in " __FILE__ ":" STRINGIZE(__LINE__))).c_str()); \
	MULTI_LINE_MACRO_END
#define assert3 assume3

#define assume4(x, print1, print2, print3, print4) \
	MULTI_LINE_MACRO_BEGIN \
		if (!(x)) \
			assume_failed(((#x ", " #print1 ": ") + MATH_NS::ObjToString(print1) + \
			                  (", " #print2 ": ") + MATH_NS::ObjToString(print2) + \
			                  (", " #print3 ": ") + MATH_NS::ObjToString(print3) + \
			                  (", " #print4 ": ") + MATH_NS::ObjToString(print4) + \
			                  (" in " __FILE__ ":" STRINGIZE(__LINE__))).c_str()); \
	MULTI_LINE_MACRO_END
#define assert4 assume4

// If MATH_ASSERT_CORRECTNESS is defined, the function mathassert() is enabled to test
// that all forms of optimizations inside the math library produce proper results.
#ifdef MATH_ASSERT_CORRECTNESS
#define mathassert(x) assert(x)
#else
#define mathassert(x) ((void)0)
#endif

// Kill both assume() and mathassert() macros in OPTIMIZED_RELEASE builds.
#ifdef OPTIMIZED_RELEASE
#ifdef assume
#undef assume
#endif
#ifdef mathassert
#undef mathassert
#endif
#define assume(x) ((void)0)
#define mathassert(x) ((void)0)
#endif

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

    <ImageView
        android:id="@+id/img_donation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="4dp"
        android:layout_centerVertical="true"
        android:background="#044BFF"
        />

    <TextView
        android:id="@+id/action_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/img_donation"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="TextView"
        android:textSize="16sp"
        android:textStyle="bold" />

    <Spinner
        android:id="@+id/bairros_spinner"
        android:visibility="gone"
        android:layout_width="95dp"
        android:layout_height="50dp"
        android:layout_alignParentRight="true"
        android:layout_centerInParent="true"
        android:layout_toRightOf="@+id/action_title" />

</RelativeLayout>


text: <dhtmlx-event-details (closeDetailEvent)="setEvent()" [event]="activeEvent"></dhtmlx-event-details>


text:
<!DOCTYPE html >

          <title></title>
          <meta name="description" content="" />
          <meta name="keywords" content="" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../lib/ref-index.css" media="screen" type="text/css" rel="stylesheet" />

Implicits

text

in

LangBundle

isContentTerm

LangBundle

isHashtag

LangBundle

isMention

LangBundle


text:
import { describe, it, before } from 'mocha';
import expect from 'unexpected';

import {
  asyncPhase,
  request,
  response,
  fail,
  reset,
  REQUEST_PHASE,
  RESET_PHASE,
  FAIL_PHASE,
  RESPONSE_PHASE,
  isAsync,
  baseType,
  asyncState,
  initialAsyncState,
  asyncStatesMap,
} from '../../../src/redux/async-helpers';

describe('Async helpers', () => {
  describe('Async phases', () => {
    const table = [
      { maker: request, phase: REQUEST_PHASE },
      { maker: response, phase: RESPONSE_PHASE },
      { maker: fail, phase: FAIL_PHASE },
      { maker: reset, phase: RESET_PHASE },
    ];

    for (const { maker, phase } of table) {
      it(`should create '${phase}' type`, () => {
        expect(asyncPhase(maker('TEST')), 'to be', phase);
      });
    }

    for (const { maker, phase } of table) {
      it(`should check that '${phase}' type is async`, () => {
        expect(isAsync(maker('TEST')), 'to be true');
      });
    }

    for (const { maker, phase } of table) {
      it(`should extract the base type from '${phase}' type`, () => {
        expect(baseType(maker('TEST')), 'to be', 'TEST');
      });
    }
  });

  describe('asyncState reducer', () => {
    const actionType = 'TEST';
    let reducer;
    before(() => {
      reducer = asyncState(actionType);
    });

    it('should return initial state', () => {
      const state = reducer(undefined, { type: 'UNKNOWN' });
      expect(state, 'to be', initialAsyncState);
    });

    it('should not touch state on unknown action', () => {
      const initialState = 42;
      const state = reducer(initialState, { type: 'UNKNOWN' });
      expect(state, 'to be', initialState);
    });

    it('should process the REQUEST action', () => {
      const state = reducer(initialAsyncState, { type: request(actionType) });
      expect(state, 'to equal', { ...initialAsyncState, loading: true });
    });

    it('should process the RESPONSE action', () => {
      const state = reducer(initialAsyncState, { type: response(actionType) });
      expect(state, 'to equal', { ...initialAsyncState, success: true });
    });

    it('should process the FAIL action without payload', () => {
      const state = reducer(initialAsyncState, { type: fail(actionType) });
      expect(state, 'to equal', { ...initialAsyncState, error: true });
    });

    it('should process the FAIL action without error in payload', () => {
      const state = reducer(initialAsyncState, {
        type: fail(actionType),
        payload: { err: 'AAA!' },
      });
      expect(state, 'to equal', { ...initialAsyncState, error: true, errorText: 'AAA!' });
    });

    it('should process the RESET action after RESPONSE', () => {
      let state = reducer(initialAsyncState, { type: response(actionType) });
      state = reducer(state, { type: reset(actionType) });
      expect(state, 'to equal', initialAsyncState);
    });
  });

  describe('asyncStatesMap reducer', () => {
    describe('with default parameters', () => {
      const actionType = 'TEST';
      let reducer;
      before(() => {
        reducer = asyncStatesMap(actionType);
      });

      it('should return initial state', () => {
        const state = reducer(undefined, { type: 'UNKNOWN' });
        expect(state, 'to equal', {});
      });

      it('should process the REQUEST action', () => {
        const state = reducer(
          {},
          {
            type: request(actionType),
            payload: { id: 'id1' },
          },
        );
        expect(state, 'to equal', { id1: { ...initialAsyncState, loading: true } });
      });

      it('should process two actions with different ids', () => {
        let state = {};
        state = reducer(state, {
          type: request(actionType),
          payload: { id: 'id1' },
        });
        state = reducer(state, {
          type: response(actionType),
          request: { id: 'id2' },
        });
        expect(state, 'to equal', {
          id1: { ...initialAsyncState, loading: true },
          id2: { ...initialAsyncState, success: true },
        });
      });
    });

    describe('with keyMustExist', () => {
      const actionType = 'TEST';
      let reducer;
      before(() => {
        reducer = asyncStatesMap(actionType, { keyMustExist: true });
      });

      it('should process the REQUEST action of existing key', () => {
        const state = reducer(
          { id1: initialAsyncState },
          {
            type: request(actionType),
            payload: { id: 'id1' },
          },
        );
        expect(state, 'to equal', { id1: { ...initialAsyncState, loading: true } });
      });

      it('should not process the REQUEST action of non-existing key', () => {
        const initialState = { id2: initialAsyncState };
        const state = reducer(initialState, {
          type: request(actionType),
          payload: { id: 'id1' },
        });
        expect(state, 'to be', initialState);
      });
    });

    describe('with applyState function', () => {
      const actionType = 'TEST';
      let reducer;
      before(() => {
        reducer = asyncStatesMap(actionType, {
          applyState: (prev = { foo: 42 }, async) => ({ ...prev, async }),
        });
      });

      it('should process the REQUEST action of existing key', () => {
        const state = reducer(
          { id1: { foo: 41, async: initialAsyncState } },
          {
            type: request(actionType),
            payload: { id: 'id1' },
          },
        );
        expect(state, 'to equal', {
          id1: { foo: 41, async: { ...initialAsyncState, loading: true } },
        });
      });

      it('should process the REQUEST action of non-existing key', () => {
        const state = reducer(
          { id2: { foo: 41, async: initialAsyncState } },
          {
            type: request(actionType),
            payload: { id: 'id1' },
          },
        );
        expect(state, 'to equal', {
          id1: { foo: 42, async: { ...initialAsyncState, loading: true } },
          id2: { foo: 41, async: initialAsyncState },
        });
      });
    });
  });
});


text:
package com.example.asset;

// [START asset_quickstart_search_all_resources]
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.AssetServiceClient.SearchAllResourcesPagedResponse;
import com.google.cloud.asset.v1.SearchAllResourcesRequest;
import java.io.IOException;
import java.util.Arrays;

public class SearchAllResourcesExample {

  // Searches for all the resources within the given scope.
  public static void searchAllResources(String scope, String query) {
    // TODO(developer): Replace these variables before running the sample.
    String[] assetTypes = {};
    int pageSize = 0;
    String pageToken = "";
    String orderBy = "";

    SearchAllResourcesRequest request =
        SearchAllResourcesRequest.newBuilder()
            .setScope(scope)
            .setQuery(query)
            .addAllAssetTypes(Arrays.asList(assetTypes))
            .setPageSize(pageSize)
            .setPageToken(pageToken)
            .setOrderBy(orderBy)
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AssetServiceClient client = AssetServiceClient.create()) {
      SearchAllResourcesPagedResponse response = client.searchAllResources(request);
      System.out.println("Search completed successfully:\n" + response.getPage().getValues());
    } catch (IOException e) {
      System.out.println(String.format("Failed to create client:%n%s", e.toString()));
    } catch (InvalidArgumentException e) {
      System.out.println(String.format("Invalid request:%n%s", e.toString()));
    } catch (ApiException e) {
      System.out.println(String.format("Error during SearchAllResources:%n%s", e.toString()));
    }
  }
}
// [END asset_quickstart_search_all_resources]


text:
import pathlib

import numpy as np

import matplotlib

matplotlib.pyplot.ioff()

import WrightTools as wt

import pycmds.project.classes as pc
import pycmds.project.widgets as pw
import somatic.acquisition as acquisition

import pycmds.hardware.opas.opas as opas
import pycmds.hardware.spectrometers as spectrometers
import pycmds.devices.devices as devices

### define ####################################################################

module_name = "MOTORTUNE"

### custom classes ############################################################

class MotorGUI:
    def __init__(self, name, center, width, number, use_tune_points):
        self.name = name
        self.use_tune_points = use_tune_points
        self.input_table = pw.InputTable()
        self.input_table.add(name, None)
        allowed = ["Set", "Scan", "Static"]
        self.method = pc.Combo(allowed_values=allowed)
        if self.use_tune_points is not None:
            self.use_tune_points.updated.connect(self.update_disabled)
        self.method.updated.connect(self.update_disabled)
        self.input_table.add("Method", self.method)
        self.center = pc.Number(initial_value=center)
        self.input_table.add("Center", self.center)
        self.width = pc.Number(initial_value=width)
        self.input_table.add("Width", self.width)
        self.npts = pc.Number(initial_value=number, decimals=0)
        self.input_table.add("Number", self.npts)
        self.update_disabled()

    def update_disabled(self):
        self.center.set_disabled(True)
        self.width.set_disabled(True)
        self.npts.set_disabled(True)
        method = self.method.read()
        if method == "Set":
            self.center.set_disabled(self.use_tune_points.read())
        elif method == "Scan":
            self.center.set_disabled(self.use_tune_points.read())
            self.width.set_disabled(False)
            self.npts.set_disabled(False)
        elif method == "Static":
            self.center.set_disabled(False)

class OPA_GUI:
    def __init__(self, hardware, layout, use_tune_points):
        self.hardware = hardware
        motor_names = self.hardware.motor_names
        self.motors = []
        for name in motor_names:
            motor = MotorGUI(name, 30, 1, 11, use_tune_points)
            if layout is not None:
                layout.addWidget(motor.input_table)
            self.motors.append(motor)
        self.hide()  # initialize hidden

    def hide(self):
        for motor in self.motors:
            motor.input_table.hide()

    def show(self):
        for motor in self.motors:
            motor.input_table.show()

### Worker ####################################################################

class Worker(acquisition.Worker):
    def process(self, scan_folder):
        if not self.aqn.read("processing", "do post process"):
            self.upload(self.scan_folders[self.scan_index], reference_image=None)
            return
        # get path
        data_path = devices.data_path.read()
        # make data object
        data = wt.data.from_PyCMDS(data_path, verbose=False)
        data_path = pathlib.Path(data_path)
        data_folder = data_path.parent
        ouput_folder = data_folder
        channel_path = data_folder / channel
        if data.ndim > 2:
            output_folder = channel_path
            channel_path.mkdir()
        file_name = data_path.stem
        file_extension = data_path.suffix
        # make all images
        channel = self.aqn.read("processing", "channel")
        image_fname = channel
        if data.ndim == 1:
            filepaths = wt.artists.quick1D(
                data,
                channel=channel,
                autosave=True,
                save_directory=output_folder,
                fname=image_fname,
                verbose=False,
            )
        else:
            filepaths = wt.artists.quick2D(
                data,
                -1,
                -2,
                channel=channel,
                autosave=True,
                save_directory=output_folder,
                fname=image_fname,
                verbose=False,
            )
        # get output image
        if len(filepaths) == 1:
            output_image_path = filepaths[0]
        else:
            output_image_path = str(output_folder / "animation.gif")
            wt.artists.stitch_to_animation(images=filepaths, outpath=output_image_path)
        # upload
        self.upload(self.scan_folders[self.scan_index], reference_image=output_image_path)

    def run(self):
        # assemble axes
        axes = []
        # get OPA properties
        opa_name = self.aqn.read("motortune", "opa name")
        opa_names = [h.name for h in opas.hardwares]
        opa_index = opa_names.index(opa_name)
        opa_hardware = opas.hardwares[opa_index]
        opa_friendly_name = opa_hardware.name
        curve = opa_hardware.curve
        motor_names = self.aqn.read("motortune", "motor names")
        # tune points
        if self.aqn.read("motortune", "use tune points"):
            motors_excepted = []  # list of indicies
            for motor_name in motor_names:
                if not self.aqn.read(motor_name, "method") == "Set":
                    motors_excepted.append(motor_name)
            if self.aqn.read("spectrometer", "method") == "Set":
                identity = opa_friendly_name + "=wm"
                hardware_dict = {
                    opa_friendly_name: [
                        opa_hardware,
                        "set_position_except",
                        ["destination", motors_excepted],
                    ],
                    "wm": [spectrometers.hardwares[0], "set_position", None],
                }
                axis = acquisition.Axis(
                    curve.setpoints[:],
                    curve.setpoints.units,
                    opa_friendly_name,
                    identity,
                    hardware_dict,
                )
                axes.append(axis)
            else:
                hardware_dict = {
                    opa_friendly_name: [
                        opa_hardware,
                        "set_position_except",
                        ["destination", motors_excepted],
                    ]
                }
                axis = acquisition.Axis(
                    curve.setpoints[:],
                    curve.setpoints.units,
                    opa_friendly_name,
                    opa_friendly_name,
                    hardware_dict,
                )
                axes.append(axis)
        # motor
        for motor_name in motor_names:
            if self.aqn.read(motor_name, "method") == "Scan":
                motor_units = None
                name = "_".join([opa_friendly_name, motor_name])
                width = self.aqn.read(motor_name, "width") / 2.0
                npts = self.aqn.read(motor_name, "number")
                if self.aqn.read("motortune", "use tune points"):
                    center = 0.0
                    identity = "D" + name
                    motor_positions = curve[motor_name][:]
                    kwargs = {"centers": motor_positions}
                else:
                    center = self.aqn.read(motor_name, "center")
                    identity = name
                    kwargs = {}
                points = np.linspace(center - width, center + width, npts)
                hardware_dict = {name: [opa_hardware, "set_motor", [motor_name, "destination"]]}
                axis = acquisition.Axis(
                    points, motor_units, name, identity, hardware_dict, **kwargs
                )
                axes.append(axis)
            elif self.aqn.read(motor_name, "method") == "Set":
                pass
            elif self.aqn.read(motor_name, "method") == "Static":
                opa_hardware.q.push("set_motor", [motor_name, self.aqn.read(motor_name, "center")])
        # mono
        if self.aqn.read("spectrometer", "method") == "Scan":
            name = "wm"
            units = "wn"
            width = self.aqn.read("spectrometer", "width") / 2.0
            npts = self.aqn.read("spectrometer", "number")
            if self.aqn.read("motortune", "use tune points"):
                center = 0.0
                identity = "D" + name
                curve = curve.copy()
                curve.convert("wn")
                # centers_shape = [a.points.size for a in axes]
                # centers = np.transpose(curve.setpoints[:] * np.ones(centers_shape).T)
                kwargs = {"centers": curve.setpoints[:]}
            else:
                center = self.aqn.read("spectrometer", "center")
                center = wt.units.convert(
                    center, self.aqn.read("spectrometer", "center units"), "wn"
                )
                identity = name
                kwargs = {}
            points = np.linspace(center - width, center + width, npts)
            axis = acquisition.Axis(points, units, name, identity, **kwargs)
            axes.append(axis)
        elif self.aqn.read("spectrometer", "method") == "Set":
            if self.aqn.read("motortune", "use tune points"):
                # already handled above
                pass
            else:
                center = self.aqn.read("spectrometer", "center")
                center = wt.units.convert(
                    center, self.aqn.read("spectrometer", "center units"), "wn"
                )
                spectrometers.hardwares[0].set_position(center, "wn")
        elif self.aqn.read("spectrometer", "method") == "Static":
            center = self.aqn.read("spectrometer", "center")
            center = wt.units.convert(center, self.aqn.read("spectrometer", "center units"), "wn")
            spectrometers.hardwares[0].set_position(center, "wn")
        # handle centers
        for axis_index, axis in enumerate(axes):
            centers_shape = [a.points.size for i, a in enumerate(axes) if not i == axis_index]
            ones = np.ones(centers_shape)
            if hasattr(axis, "centers"):
                # arrays always follow
                axis.centers = np.transpose(axis.centers * ones.T)
        # launch
        pre_wait_methods = [
            lambda: opa_hardware.q.push("wait_until_still"),
            lambda: opa_hardware.q.push("get_motor_positions"),
            lambda: opa_hardware.q.push("get_position"),
        ]
        # do scan
        self.scan(axes, constants=[], pre_wait_methods=pre_wait_methods)
        if not self.stopped.read():
            self.finished.write(True)  # only if acquisition successfull

### GUI #######################################################################

class GUI(acquisition.GUI):
    def create_frame(self):
        # shared settings
        input_table = pw.InputTable()
        allowed = [hardware.name for hardware in opas.hardwares]
        self.opa_combo = pc.Combo(allowed)
        input_table.add("OPA", self.opa_combo)
        self.opa_combo.updated.connect(self.on_opa_combo_updated)
        self.use_tune_points = pc.Bool(initial_value=True)
        input_table.add("Use Tune Points", self.use_tune_points)
        self.layout.addWidget(input_table)
        # motor settings
        self.opa_guis = [
            OPA_GUI(hardware, self.layout, self.use_tune_points) for hardware in opas.hardwares
        ]
        self.opa_guis[0].show()
        # mono settings
        allowed = ["Set", "Scan", "Static"]
        self.mono_method_combo = pc.Combo(allowed, disable_under_module_control=True)
        self.mono_method_combo.updated.connect(self.update_mono_settings)
        self.mono_center = pc.Number(
            initial_value=7000, units="wn", disable_under_module_control=True
        )
        self.mono_width = pc.Number(
            initial_value=500, units="wn", disable_under_module_control=True
        )
        self.mono_width.set_disabled_units(True)
        self.mono_npts = pc.Number(initial_value=51, decimals=0, disable_under_module_control=True)
        input_table = pw.InputTable()
        input_table.add("Spectrometer", None)
        input_table.add("Method", self.mono_method_combo)
        input_table.add("Center", self.mono_center)
        input_table.add("Width", self.mono_width)
        input_table.add("Number", self.mono_npts)
        self.layout.addWidget(input_table)
        self.update_mono_settings()
        # processing
        input_table = pw.InputTable()
        input_table.add("Processing", None)
        self.do_post_process = pc.Bool(initial_value=True)
        input_table.add("Process", self.do_post_process)
        # TODO: allowed values, update
        self.main_channel = pc.Combo()
        input_table.add("Channel", self.main_channel)
        self.layout.addWidget(input_table)

    def load(self, aqn_path):
        aqn = wt.kit.INI(aqn_path)
        # shared settings
        self.opa_combo.write(aqn.read("motortune", "opa name"))
        self.use_tune_points.write(aqn.read("motortune", "use tune points"))
        # motor settings
        opa = self.opa_guis[self.opa_combo.read_index()]
        for motor, motor_name in zip(opa.motors, aqn.read("motortune", "motor names")):
            motor.method.write(aqn.read(motor_name, "method"))
            motor.center.write(aqn.read(motor_name, "center"))
            motor.width.write(aqn.read(motor_name, "width"))
            motor.npts.write(aqn.read(motor_name, "number"))
        # mono settings
        self.mono_method_combo.write(aqn.read("spectrometer", "method"))
        self.mono_center.write(aqn.read("spectrometer", "center"))
        self.mono_width.write(aqn.read("spectrometer", "width"))
        self.mono_npts.write(aqn.read("spectrometer", "number"))
        # processing
        self.do_post_process.write(aqn.read("processing", "do post process"))
        self.main_channel.write(aqn.read("processing", "channel"))
        # allow devices to read from aqn
        self.device_widget.load(aqn_path)

    def on_device_settings_updated(self):
        self.main_channel.set_allowed_values(devices.control.channel_names)

    def on_opa_combo_updated(self):
        self.show_opa_gui(self.opa_combo.read_index())

    def save(self, aqn_path):
        aqn = wt.kit.INI(aqn_path)
        opa = self.opa_guis[self.opa_combo.read_index()]
        scanned_motor_names = []
        for motor in opa.motors:
            if motor.method == "Scan":
                scanned_motor_names.append(motor.name)
        scanned_motor_names = str(scanned_motor_names).replace("'", "")
        aqn.write(
            "info",
            "description",
            "MOTORTUNE: {} {}".format(self.opa_combo.read(), scanned_motor_names),
        )
        # shared settings
        aqn.add_section("motortune")
        aqn.write("motortune", "opa name", self.opa_combo.read())
        aqn.write(
            "motortune",
            "motor names",
            [motor.name for motor in self.opa_guis[self.opa_combo.read_index()].motors],
        )
        aqn.write("motortune", "use tune points", self.use_tune_points.read())
        # motor settings
        for motor in opa.motors:
            aqn.add_section(motor.name)
            aqn.write(motor.name, "method", motor.method.read())
            aqn.write(motor.name, "center", motor.center.read())
            aqn.write(motor.name, "width", motor.width.read())
            aqn.write(motor.name, "number", motor.npts.read())
        # mono settings
        aqn.add_section("spectrometer")
        aqn.write("spectrometer", "method", self.mono_method_combo.read())
        aqn.write("spectrometer", "center", self.mono_center.read())
        aqn.write("spectrometer", "center units", self.mono_center.units)
        aqn.write("spectrometer", "width", self.mono_width.read())
        aqn.write("spectrometer", "number", self.mono_npts.read())
        # processing
        aqn.add_section("processing")
        aqn.write("processing", "do post process", self.do_post_process.read())
        aqn.write("processing", "channel", self.main_channel.read())
        # allow devices to save to aqn
        self.device_widget.save(aqn_path)

    def show_opa_gui(self, index):
        for gui in self.opa_guis:
            gui.hide()
        self.opa_guis[index].show()

    def update_mono_settings(self):
        self.mono_center.set_disabled(True)
        self.mono_width.set_disabled(True)
        self.mono_npts.set_disabled(True)
        method = self.mono_method_combo.read()
        if method == "Set":
            self.mono_center.set_disabled(self.use_tune_points.read())
        elif method == "Scan":
            self.mono_center.set_disabled(self.use_tune_points.read())
            self.mono_width.set_disabled(False)
            self.mono_npts.set_disabled(False)
        elif method == "Static":
            self.mono_center.set_disabled(False)

def mkGUI():
    global gui
    gui = GUI(module_name)

def load():
    return True


text:
package bnfc.abs.Absyn; // Java Package generated by the BNF Converter.

public class PParamConstr extends Pattern {
  public final String uident_;
  public final ListPattern listpattern_;
  public PParamConstr(String p1, ListPattern p2) { uident_ = p1; listpattern_ = p2; }

  public <R,A> R accept(bnfc.abs.Absyn.Pattern.Visitor<R,A> v, A arg) { return v.visit(this, arg); }

  public boolean equals(Object o) {
    if (this == o) return true;
    if (o instanceof bnfc.abs.Absyn.PParamConstr) {
      bnfc.abs.Absyn.PParamConstr x = (bnfc.abs.Absyn.PParamConstr)o;
      return this.uident_.equals(x.uident_) && this.listpattern_.equals(x.listpattern_);
    }
    return false;
  }

  public int hashCode() {
    return 37*(this.uident_.hashCode())+this.listpattern_.hashCode();
  }

}


text:
package com.sun.xml.internal.ws.api;

import com.sun.xml.internal.ws.developer.MemberSubmissionAddressing;
import com.sun.xml.internal.ws.developer.MemberSubmissionAddressingFeature;

import javax.xml.ws.WebServiceFeature;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;

/**
 *

 * This annotation should be used on a constructor of classes extending {@link WebServiceFeature} other than
 * Spec defined features, to help JAX-WS runtime recognize feature extensions.
 *

 *

 * For WebServiceFeature annotations to be recognizable by JAX-WS runtime, the feature annotation should point
 * to a corresponding bean (class extending WebServiceFeature). Only one of the constructors in the bean MUST be marked
 * with @FeatureConstructor whose value captures the annotaion attribute names for the corresponding parameters.
 *

 * For example,
 * @see MemberSubmissionAddressingFeature
 * @see MemberSubmissionAddressing
 *
 * @see com.sun.xml.internal.ws.developer.Stateful
 * @see com.sun.xml.internal.ws.developer.StatefulFeature
 *
 * @author Rama Pulavarthi
 */
@Retention(RUNTIME)
@Target(ElementType.CONSTRUCTOR)

public @interface FeatureConstructor {
    /**
     * The name of the parameter.
     */
    String[] value() default {};
}


text:
namespace gdata {
namespace service {

HTTPSQuery::MessageNotReceivedException::MessageNotReceivedException()
	: utils::GDataException("Response message is not received")
{
}

HTTPSQuery::MessageNotReceivedException::~MessageNotReceivedException() throw()
{
}

HTTPSQuery::ResponseCodeException::ResponseCodeException(uint32_t response_code)
	: utils::GDataException("Response code is " + Poco::NumberFormatter().format(response_code))
{
}

HTTPSQuery::ResponseCodeException::~ResponseCodeException() throw()
{
}

HTTPSQuery::HTTPSQuery()
	: m_uri(""), m_method(""), m_data(""),
	  m_headers(std::map<std::string, std::string>()), m_query("")
{
}

HTTPSQuery::~HTTPSQuery()
{
}

void HTTPSQuery::add_header(const std::string& name, const std::string& value)
{
	m_headers[name] = value;
}

void HTTPSQuery::add_query_field(const std::string& name, const std::string& value)
{
	if (m_query.length())
		m_query += "&";

	m_query += name + "=" + value;
}

std::string HTTPSQuery::run()
{
	try
	{
		Poco::URI uri(m_uri);
		uri.setRawQuery(m_query);

		Poco::Net::Context::Ptr context(new Poco::Net::Context(Poco::Net::Context::CLIENT_USE,
															   "", Poco::Net::Context::VERIFY_NONE));
		Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(), context);

		std::string path(uri.getPathAndQuery());
		Poco::Net::HTTPRequest request(m_method, path, Poco::Net::HTTPMessage::HTTP_1_0);

		for (std::map<std::string, std::string>::iterator iter = m_headers.begin();
			 iter != m_headers.end(); ++iter)
			request.set(iter->first, iter->second);

		session.sendRequest(request);

		Poco::Net::HTTPResponse response;
		std::istream &is = session.receiveResponse(response);

		if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK)
			throw ResponseCodeException(response.getStatus());

		std::string output;
		Poco::StreamCopier::copyToString(is, output);

		return output;
	}
	catch (Poco::Exception &ex)
	{
		throw MessageNotReceivedException();
	}
}

void HTTPSQuery::set_data(const std::string& data)
{
	m_data = data;
}

void HTTPSQuery::set_method(const HTTPMethod& method)
{
	m_method = method_to_string(method);
}

void HTTPSQuery::set_uri(const std::string& uri)
{
	m_uri = uri;
}

} // namespace service
} // namespace gdata


text:
import os, argparse, string
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware, SharedDataMiddleware
from flask import Flask
from mpcontribs.webui.main import main_bp
from mpcontribs.webui.webui import ingester_bp
from mpcontribs.users_modules import add_all_dash_apps
from test_site.wsgi import application as django_app
from test_site.settings import PROXY_URL_PREFIX, STATIC_URL, STATIC_ROOT

class CustomTemplate(string.Template):
    delimiter = "$$"

def cli():
    parser = argparse.ArgumentParser(
        description="Command Line Interface for MPContribs WebUI",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument("--sbx", help="ArchieML Sandbox Content")
    parser.add_argument("--debug", action="store_true", help="run in debug mode")
    parser.add_argument(
        "--start-jupyter", action="store_true", help="start Jupyter server"
    )
    parser.add_argument(
        "--start-mongodb", action="store_true", help="start MongoDB server"
    )
    jpy_base_url = os.environ.get("JPY_BASE_URL")
    if os.environ.get("DEPLOYMENT") == "MATGEN":
        default_jupyter_url = "https://jupyterhub.materialsproject.org" + jpy_base_url
    else:
        default_jupyter_url = "http://localhost:"
        default_jupyter_url += "8000" + jpy_base_url if jpy_base_url else "8888"
    parser.add_argument(
        "--jupyter-url",
        metavar="URL",
        dest="jupyter_url",
        default=default_jupyter_url,
        help="Jupyter URL",
    )
    args = parser.parse_args()

    if args.start_mongodb:
        dbpath = os.path.join("/", "data", "db")
        if not os.path.exists(dbpath):
            dbpath = os.path.join(os.getcwd(), "db")
            if not os.path.exists(dbpath):
                os.makedirs(dbpath)

    jpy_user = os.environ.get("JPY_USER")
    custom_js = "/home/jovyan/work/MPContribs/notebooks/profile/custom/custom.js"
    if jpy_user is not None and not os.path.exists(custom_js):
        with open("{}_template".format(custom_js), "r") as f:
            fstr = f.read()
            template = CustomTemplate(fstr)
            text = template.substitute({"JPY_USER": jpy_user})
            with open(custom_js, "w") as f2:
                f2.write(text)

    app = Flask(__name__)
    app.debug = args.debug
    app.config["SANDBOX_CONTENT"] = args.sbx
    app.config["START_JUPYTER"] = args.start_jupyter
    app.config["START_MONGODB"] = args.start_mongodb
    app.config["JUPYTER_URL"] = args.jupyter_url
    app.register_blueprint(main_bp, url_prefix=PROXY_URL_PREFIX)
    app.register_blueprint(ingester_bp, url_prefix=PROXY_URL_PREFIX + "/ingester")
    try:
        app = add_all_dash_apps(app)
    except ImportError:
        print("Dash not installed.")
    application = DispatcherMiddleware(
        app, {PROXY_URL_PREFIX + "/test_site": django_app}
    )
    application = SharedDataMiddleware(application, {STATIC_URL[:-1]: STATIC_ROOT})

    run_simple(
        "0.0.0.0",
        5000,
        application,
        use_reloader=args.debug,  # ssl_context='adhoc',
        use_debugger=args.debug,
        use_evalex=args.debug,
        threaded=True,
    )

if __name__ == "__main__":
    cli()


text:
<!DOCTYPE html>

    <title>Map Generator</title>

    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="description" content="A hexagon based, random map generator written in javascript. You can change the size of the map and of a single hexagon, pick the amount of countries, decide between compact or total random country shapes, add a variance for the country size and toggle distortion." />
    <meta name="author" content="David Strauß" />
    <meta name="author" content="Eberhard Gräther" />
    <meta name="author" content="Christian Winkler" />

    <link href='style.css' rel='stylesheet' type='text/css'>

      <button id=red style="background: #ff0000" onclick="coloring('#ff0000')">______</button>
    <button id=green style="background: #00ff00"onclick="coloring('#00ff00')">______</button>
    <button id=blue style="background: #0000ff"onclick="coloring('#0000ff')">______</button>
    <button id=yellow style="background: #ffff00"onclick ="coloring('#ffff00')">______</button>
    <button id= clear onclick="coloring('#fff')">eraser</button>

     Choose your color here

    <button id= check onclick="check()">check coloring</button>
        <button id= check onclick="increment(1)">graph</button>

            <form>
                <fieldset id="firstColumn">
                    Size of map (px): <input type="text" id="mapWidth" value="400"/> x <input type="text" id="mapHeight" value="500"/>

                    Size of a hexagon(px)(+easy,-hard): <input type="text" id="hexagonSize" value="40"/>

                    Number of countries: <input type="text" id="numberOfCountries" value="8"/>
                </fieldset>
                <fieldset id="secondColumn">
                    Country size variance (0 - 0.9): <input type="text" id="countrySizeVariance" value="0.5"/>

                   <input type="checkbox" id="useDistortion">
                </fieldset>
                <fieldset id="thirdColumn">
                    Compact country shapes:<input type="checkbox" id="useCompactShapes">

                    Show centers and connections:<input type="button" id="showCentersAndConnection" onclick="showCentersAndConnection++">

                    <input type="button" id="generate" value="Generate New Map">
                    <input type="button" value="generate new map" onClick="window.location.reload()">
                    <input type="button" id="check" value="check coloring">

                </fieldset>
            </form>


text:
namespace content {
struct ContextMenuParams;
struct OpenURLParams;
class WebContents;
}

namespace extensions {

class ExtensionOptionsGuest;

// Interface to handle communication between ExtensionOptionsGuest (in
// extensions) with the browser.
class ExtensionOptionsGuestDelegate {
 public:
  explicit ExtensionOptionsGuestDelegate(ExtensionOptionsGuest* guest);
  virtual ~ExtensionOptionsGuestDelegate();

  // Called from ExtensionOptionsGuest::DidInitialize().
  virtual void DidInitialize() = 0;

  // Shows the context menu for the guest.
  // Returns true if the context menu was handled.
  virtual bool HandleContextMenu(const content::ContextMenuParams& params) = 0;

  virtual content::WebContents* OpenURLInNewTab(
      const content::OpenURLParams& params) = 0;

  ExtensionOptionsGuest* extension_options_guest() const { return guest_; }

 private:
  ExtensionOptionsGuest* const guest_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionOptionsGuestDelegate);
};

}  // namespace extensions

#endif  // EXTENSIONS_BROWSER_GUEST_VIEW_EXTENSION_OPTIONS_EXTENSION_OPTIONS_GUEST_DELEGATE_H_


text:
package fr.vsct.dt.maze

import java.util.function.Consumer

import scala.language.implicitConversions

/**
  * Implicits to compile with 2.11
  */
package object helpers {

  implicit def functionToConsumer[A, B](f: (A) => B): Consumer[A] = new Consumer[A] {
    override def accept(t: A): Unit = f(t)
  }

}


text:
import itertools

class Slot:

    def __init__(self, tup):

        self.data = tup
        self.size = len(tup)
        self.is_covered = False  # can be covered\excluded == True or uncovered == False

    def __repr__(self):
        return "Slot: " + str(self.data)

    def set_covered(self, bool_val=True):
        self.is_covered = bool_val

    def __iter__(self):
        return iter(self.data)

def gen_slots(values_list):
    slot_list = []
    for comb in itertools.product(*values_list):
        slot_list.append(Slot(list(comb)))
    return slot_list

class ParameterInteractionStructure:

    def __init__(self, parameters):
        self.member_parameters = frozenset(parameters)
        self.slots = gen_slots([x.get_values_list() for x in parameters])

    def is_covered(self):
        return all([slot.is_covered for slot in self.slots])

    def __repr__(self):
        return ''.join([x.get_param_name() for x in self.member_parameters])

    def get_uncovered_slots_count(self):
        return sum(not slot.is_covered for slot in self.slots)

    def get_next_slot(self):
        return next(slot for slot in self.slots if not slot.is_covered)

    def get_params_set(self):
        return self.member_parameters

    def get_slots(self):
            return [x for x in self.slots]


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.microsoft.recognizers.text.samples.simpleconsole</groupId>
    <artifactId>recognizers-text-samples-simple-console</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>${project.groupId}:${project.artifactId}</name>
    <description>Microsoft.Recognizers.Text - Simple Console sample</description>
    <url>https://github.com/Microsoft/Recognizers-Text/</url>

    <parent>
        <groupId>com.microsoft.recognizers.text</groupId>
        <artifactId>recognizers-text-java</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../../</relativePath>
    </parent>

    <licenses>
        <license>
            <name>MIT License</name>
            <url>http://www.opensource.org/licenses/mit-license.php</url>
        </license>
    </licenses>

    <developers>
        <developer>
            <name>Microsoft Recognizers-Text</name>
            <email></email>
            <organization>Microsoft</organization>
            <organizationUrl>https://www.microsoft.com/</organizationUrl>
        </developer>
    </developers>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.microsoft.recognizers.text</groupId>
            <artifactId>recognizers-text</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.recognizers.text.number</groupId>
            <artifactId>recognizers-text-number</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.recognizers.text.numberwithunit</groupId>
            <artifactId>recognizers-text-number-with-unit</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.6.0</version>
                <configuration>
                    <mainClass>com.microsoft.recognizers.text.samples.simpleconsole.Sample</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.microsoft.recognizers.text.samples.simpleconsole.Sample</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
package io.reactivesocket.rx;

public interface Observer<T> {

	public void onNext(T t);

	public void onError(Throwable e);

	public void onComplete();

	public void onSubscribe(Disposable d);
}


text:
require 'chef/shell_out'

include_recipe 'git'
include_recipe 'nodejs'

package 'python-dev'
package 'make'
package 'python-virtualenv'

directory node['mozilla-firefox-sync']['server']['path'] do
  recursive true
end

git node['mozilla-firefox-sync']['server']['path'] do
  repository node['mozilla-firefox-sync']['repository']
  revision node['mozilla-firefox-sync']['server']['version']
  action :checkout
  notifies :run, 'bash[build_source]', :immediately
end

bash 'build_source' do
  code 'make build'
  cwd node['mozilla-firefox-sync']['server']['path']
  action :nothing
  notifies :run, 'bash[install_gunicorn]', :immediately
end

bash 'install_gunicorn' do
  code './local/bin/easy_install gunicorn'
  cwd node['mozilla-firefox-sync']['server']['path']
  action :nothing
end

ruby_block 'create_random' do
  begin
    cmd = Mixlib::ShellOut.new('head -c 20 /dev/urandom | sha1sum  | rev | cut -c 4- | rev')
    cmd.run_command
    node.set_unless['mozilla-firefox-sync']['auth_secret'] = cmd.stdout
  end
  only_if { node['mozilla-firefox-sync']['auth_secret'].nil? }
end

template "#{node['mozilla-firefox-sync']['server']['path']}/syncserver.ini" do
  variables(
      public_url: "https://#{node['fqdn']}",
      db_dir: node['mozilla-firefox-sync']['server']['path'],
      secret: node['mozilla-firefox-sync']['auth_secret'],
      allow_new_users: node['mozilla-firefox-sync']['allow_new_users']
  )
  notifies :reload, 'service[fx-sync-server]', :delayed
end

case node['platform']
when 'ubuntu'
  include_recipe 'mozilla-firefox-sync::init_ubuntu'
when 'debian'
  include_recipe 'mozilla-firefox-sync::init_debian'
end


text:
use std::io::Error;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;

use libc::{c_int, EINVAL};

use crate::{low_level, SigId};

/// Registers an action to set the flag to `true` whenever the given signal arrives.
///
/// # Panics
///
/// If the signal is one of the forbidden.
pub fn register(signal: c_int, flag: Arc<AtomicBool>) -> Result<SigId, Error> {
    // We use SeqCst for two reasons:
    // * Signals should not come very often, so the performance does not really matter.
    // * We promise the order of actions, but setting different atomics with Relaxed or similar
    //   would not guarantee the effective order.
    unsafe { low_level::register(signal, move || flag.store(true, Ordering::SeqCst)) }
}

/// Registers an action to set the flag to the given value whenever the signal arrives.
pub fn register_usize(signal: c_int, flag: Arc<AtomicUsize>, value: usize) -> Result<SigId, Error> {
    unsafe { low_level::register(signal, move || flag.store(value, Ordering::SeqCst)) }
}

/// Terminate the application on a signal if the given condition is true.
///
/// This can be used for different use cases. One of them (with the condition being always true) is
/// just unconditionally terminate on the given signal.
///
/// Another is being able to turn on and off the behaviour by the shared flag.
///
/// The last one is handling double CTRL+C ‒ if the user presses CTRL+C, we would like to start a
/// graceful shutdown. But if anything ever gets stuck in the shutdown, second CTRL+C (or other
/// such termination signal) should terminate the application without further delay.
///
/// To do that, one can combine this with [`register`]. On the first run, the flag is `false` and
/// this doesn't terminate. But then the flag is set to true during the first run and "arms" the
/// shutdown on the second run. Note that it matters in which order the actions are registered (the
/// shutdown must go first). And yes, this also allows asking the user "Do you want to terminate"
/// and disarming the abrupt shutdown if the user answers "No".
///
/// # Panics
///
/// If the signal is one of the forbidden.
pub fn register_conditional_shutdown(
    signal: c_int,
    status: c_int,
    condition: Arc<AtomicBool>,
) -> Result<SigId, Error> {
    let action = move || {
        if condition.load(Ordering::SeqCst) {
            low_level::exit(status);
        }
    };
    unsafe { low_level::register(signal, action) }
}

/// Conditionally runs an emulation of the default action on the given signal.
///
/// If the provided condition is true at the time of invoking the signal handler, the equivalent of
/// the default action of the given signal is run. It is a bit similar to
/// [`register_conditional_shutdown`], except that it doesn't terminate for non-termination
/// signals, it runs their default handler.
///
/// # Panics
///
/// If the signal is one of the forbidden
///
/// # Errors
///
/// Similarly to the [`emulate_default_handler`][low_level::emulate_default_handler] function, this
/// one looks the signal up in a table. If it is unknown, an error is returned.
///
/// Additionally to that, any errors that can be caused by a registration of a handler can happen
/// too.
pub fn register_conditional_default(
    signal: c_int,
    condition: Arc<AtomicBool>,
) -> Result<SigId, Error> {
    // Verify we know about this particular signal.
    low_level::signal_name(signal).ok_or_else(|| Error::from_raw_os_error(EINVAL))?;
    let action = move || {
        if condition.load(Ordering::SeqCst) {
            let _ = low_level::emulate_default_handler(signal);
        }
    };
    unsafe { low_level::register(signal, action) }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic;
    use std::time::{Duration, Instant};

    use super::*;
    use crate::consts::signal::*;

    fn self_signal() {
        #[cfg(not(windows))]
        const SIG: c_int = SIGUSR1;
        #[cfg(windows)]
        const SIG: c_int = SIGTERM;
        crate::low_level::raise(SIG).unwrap();
    }

    fn wait_flag(flag: &AtomicBool) -> bool {
        let start = Instant::now();
        while !flag.load(Ordering::Relaxed) {
            // Replaced by hint::spin_loop, but we want to support older compiler
            #[allow(deprecated)]
            atomic::spin_loop_hint();
            if Instant::now() - start > Duration::from_secs(1) {
                // We reached a timeout and nothing happened yet.
                // In theory, using timeouts for thread-synchronization tests is wrong, but a
                // second should be enough in practice.
                return false;
            }
        }
        true
    }

    #[test]
    fn register_unregister() {
        // When we register the action, it is active.
        let flag = Arc::new(AtomicBool::new(false));
        #[cfg(not(windows))]
        let signal = register(SIGUSR1, Arc::clone(&flag)).unwrap();
        #[cfg(windows)]
        let signal = register(crate::SIGTERM, Arc::clone(&flag)).unwrap();
        self_signal();
        assert!(wait_flag(&flag));
        // But stops working after it is unregistered.
        assert!(crate::low_level::unregister(signal));
        flag.store(false, Ordering::Relaxed);
        self_signal();
        assert!(!wait_flag(&flag));
        // And the unregistration actually dropped its copy of the Arc
        assert_eq!(1, Arc::strong_count(&flag));
    }

    // The shutdown is tested in tests/shutdown.rs
}


text:
using System;
using System.Collections.Generic;
using System.Text;

public static class Util
{
    public static int Hash(params object[] args)
    {
        int hash = 0;

        foreach (object arg in args)
        {
            hash = hash << 8 | ~hash >> 24;

            if (arg != null)
                hash ^= arg.GetHashCode();
        }

        return hash;
    }
}


text:
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;

using Microsoft.VisualStudio.TestTools.UnitTesting;
using MLifter.Generics;

namespace MLifterTest.Generics
{
    /// <summary>
    /// Summary Description for PasswordGeneratorTests
    /// </summary>
    [TestClass]
    public class PasswordGeneratorTests
    {
        public PasswordGeneratorTests()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Generate01()
        {
            string s;
            s = RandomPassword.Generate(0, 1);
        }
        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Generate02()
        {
            string s;
            s = RandomPassword.Generate(1, 0);
        }
        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Generate03()
        {
            string s;
            s = RandomPassword.Generate(2, 1);
        }
        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Generate04()
        {
            string s;
            s = RandomPassword.Generate(2, 1001);
        }
        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Generate05()
        {
            string s;
            s = RandomPassword.Generate(0);
        }
        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void Generate06()
        {
            string s;
            s = RandomPassword.Generate(1001);
        }
        [TestMethod]
        public void GenerateRandom01()
        {
            for (int i = 0; i < 100; i++)
            {
                int length = TestInfrastructure.RandomGen.Next(1, 1000);
                string s = RandomPassword.Generate(length);
                Assert.AreEqual<int>(length, s.Length);
            }
        }
        [TestMethod]
        public void GenerateRandom02()
        {
            for (int i = 0; i < 100; i++)
            {
                int lower = TestInfrastructure.RandomGen.Next(1, 1000);
                int upper = TestInfrastructure.RandomGen.Next(lower, 1000);
                string s = RandomPassword.Generate(lower, upper);
                Assert.IsTrue((s.Length >= lower) && (s.Length <= upper));
            }
        }
        [TestMethod]
        public void GenerateCharsetCheck()
        {
            // '-' must be escaped because it has a special meaning in a character class
            // the rest dont need to be escaped because they are in a character class
            string CHARS_SPECIAL = @"*$\-+?_&=!%.,#~/";
            Regex validChar = new Regex("^[A-Za-z0-9" + CHARS_SPECIAL + "]$");

            // test with 100 random strings of random length
            for (int i = 0; i < 100; i++)
            {
                int len = TestInfrastructure.RandomGen.Next(1, 1000);
                string s = RandomPassword.Generate(len);
                foreach (char c in s)
                {
                    Assert.IsTrue(validChar.IsMatch(c.ToString()));
                }
            }
        }
    }
}


text:
package main

import (
	"flag"
	"github.com/solo-io/cf-unik-buildpack/builder"
	"github.com/Sirupsen/logrus"
	"os"
	"github.com/solo-io/cf-unik-buildpack/runner"
)

func main() {
	build := flag.Bool("build", false, "run in staging mode (compile unikernel)")
	run := flag.Bool("run", false, "run in runner mode (proxy for unikernel)")
	buildDir := flag.String("build-dir", "", "directory containing sources")
	flag.Parse()
	host := os.Getenv("URL")
	if host == "" {
		logrus.Fatal("must provide UniK URL with URL env var")
	}
	if *build {
		logrus.Info("building unikernel")
		if *buildDir == "" {
			logrus.Fatal("-build-dir must be set")
		}
		if err := builder.BuildUnikernel(*buildDir, host); err != nil {
			logrus.Fatal("failed building unikernel", err)
		}
	} else if *run {
		logrus.Info("running unikernel")
		if err := runner.RunUnikernel(host); err != nil {
			logrus.Fatal("failed running unikernel", err)
		}
	} else {
		logrus.Fatal("must provide either -build or -run flag")
	}
}


text:
package controllers

import (
	"github.com/crockeo/cerekhillen/database"
	"github.com/crockeo/cerekhillen/models"
	"github.com/crockeo/cerekhillen/templater"
	"github.com/zenazn/goji/web"
	"net/http"
	"strconv"
)

// Getting a singular post
func GetPost(c web.C, w http.ResponseWriter, r *http.Request) {
	id, _ := strconv.ParseInt(c.URLParams["id"], 10, 64)

	db, _ := c.Env["db"].(database.DB)

	var posts []models.Post
	db.Where("id = ?", id).Find(&posts)

	if posts == nil || len(posts) == 0 {
		NotFound(c, w, r)
	} else {
		templater.SendPage(c, w, "blog/blog", []displayPost{toDisplayPost(posts[0])})
	}

}


text:
class NativeWindowSystem : public QObject{
	Q_OBJECT
private:
	QList<NativeWindowObject*> NWindows;
	QList<NativeWindowObject*> TWindows;

	//Now define a simple private_objects class so that each implementation
	//  has a storage container for defining/placing private objects as needed
	class p_objects;
	p_objects* obj;

	//Internal timers/variables for managing pings
	QTimer *pingTimer;
	QHash<WId, QDateTime> waitingForPong;

	void checkPings(){
	  QDateTime cur = QDateTime::currentDateTime();
	  QList<WId> waiting = waitingForPong.keys();
	  for(int i=0; i<waiting.length(); i++){
	    if(waitingForPong.value(waiting[i]) < cur){
	      waitingForPong.remove(waiting[i]); //Timeout on this window
	      if(waitingForPong.isEmpty() && pingTimer!=0){ pingTimer->stop(); }
	      NativeWindowObject *win = findWindow(waiting[i]);
	      if(win==0){ win = findTrayWindow(waiting[i]); }
	      if(win!=0){ win->emit WindowNotResponding(waiting[i]); }
	    }
	  }
	}

	//Generic private variables
	bool screenLocked;

public:
	//enum Property{ None, CurrentWorkspace, Workspaces, VirtualRoots, WorkAreas };
	enum MouseButton{NoButton, LeftButton, RightButton, MidButton, BackButton, ForwardButton, TaskButton, WheelUp, WheelDown, WheelLeft, WheelRight};

	//Simplifications to find an already-created window object
	NativeWindowObject* findWindow(WId id, bool checkRelated = true);

	NativeWindowObject* findTrayWindow(WId id);
	// Since some properties may be easier to update in bulk
	//   let the native system interaction do them in whatever logical groups are best
	void UpdateWindowProperties(NativeWindowObject* win, QList< NativeWindowObject::Property > props);
	void ChangeWindowProperties(NativeWindowObject* win, QList< NativeWindowObject::Property > props, QList<QVariant> vals);

	void SetupNewWindow(NativeWindowObject *win);
	QImage GetWindowImage(NativeWindowObject *win);
	QPixmap GetTrayWindowImage(NativeWindowObject *win);

	NativeWindowSystem();
	~NativeWindowSystem();

	//Overarching start/stop functions
	bool start();
	void stop();

	//General-purpose listing functions
	QList<NativeWindowObject*> currentWindows(){ return NWindows; }
	QList<NativeWindowObject*> currentTrayWindows(){ return TWindows; }

	//Small simplification functions
	static Qt::Key KeycodeToQt(int keycode);
	static NativeWindowSystem::MouseButton MouseToQt(int button);
	void RegisterEventShortcut(Qt::Key key, bool set);
	void RegisterEventShortcut(int keycode, bool set);

	void raiseWindow(NativeWindowObject *win);
	void lowerWindow(NativeWindowObject *win);

public slots:
	//These are the slots which are typically only used by the desktop system itself or the NativeWindowEventFilter

	//This is called by the lock screen to keep the NWS aware of the current status
	// it is **NOT** the function to call for the user to actually lock the session (that is in the screensaver/lockscreen class)
	 void ScreenLockChanged(bool lock){
	  screenLocked = lock;
	}

	//Root Window property registrations
	void RegisterVirtualRoot(WId);
	void setRoot_supportedActions();
	void setRoot_numberOfWorkspaces(QStringList names);
	void setRoot_currentWorkspace(int);
	void setRoot_clientList(QList<WId>, bool stackorder = false);
	void setRoot_desktopGeometry(QRect);
	void setRoot_desktopWorkarea(QList<QRect>);
	void setRoot_activeWindow(WId);

	//  - Workspaces
	int currentWorkspace();
	//void GoToWorkspace(int);

	//NativeWindowEventFilter interactions
	void NewWindowDetected(WId); //will automatically create the new NativeWindow object
	void NewTrayWindowDetected(WId); //will automatically create the new NativeWindow object
	void WindowCloseDetected(WId); //will update the lists and make changes if needed
	void WindowPropertyChanged(WId, NativeWindowObject::Property); //will rescan the window and update the object as needed
	void WindowPropertiesChanged(WId, QList<NativeWindowObject::Property>);
	void WindowPropertyChanged(WId, NativeWindowObject::Property, QVariant); //will save that property/value to the right object
	void WindowPropertiesChanged(WId, QList<NativeWindowObject::Property>, QList<QVariant>);
	void RequestPropertyChange(WId, NativeWindowObject::Property, QVariant);
	void RequestPropertiesChange(WId, QList<NativeWindowObject::Property>, QList<QVariant>);
	void GotPong(WId);

	void NewKeyPress(int keycode, WId win = 0);
	void NewKeyRelease(int keycode, WId win = 0);
	void NewMousePress(int buttoncode, WId win = 0);
	void NewMouseRelease(int buttoncode, WId win = 0);
	void CheckDamageID(WId);

	void RequestReparent(WId, WId, QPoint); //client, parent, relative origin point in parent

private slots:
	//These are the slots which are built-in and automatically connected when a new NativeWindow is created
	void RequestClose(WId);
	void RequestKill(WId);
	void RequestPing(WId);

	//Window-mgmt functions (see Window-mgmt.cpp for details)
	void ArrangeWindows(WId primary, QString type);
	void TileWindows(WId primary, QString type);
	void CheckWindowPosition(WId id, bool newwindow = false);
	void CheckWindowPosition(NativeWindowObject *win, bool newwindow = false);
	void arrangeWindows(NativeWindowObject *primary, QString type, bool primaryonly = false);

signals:
	void NewWindowAvailable(NativeWindowObject*);
	void WindowClosed();
	void NewTrayWindowAvailable(NativeWindowObject*);
	void TrayWindowClosed();
	void NewInputEvent(); //a mouse or keypress was detected (lock-state independent);
	void KeyPressDetected(WId, Qt::Key); //only emitted if lockstate = false
	void KeyReleaseDetected(WId, Qt::Key); //only emitted if lockstate = false
	void MousePressDetected(WId, NativeWindowSystem::MouseButton); //only emitted if lockstate = false
	void MouseReleaseDetected(WId, NativeWindowSystem::MouseButton); //only emitted if lockstate = false

};

#endif


text:
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width initial-scale=1" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>
        {% if page.title %}
            {{ page.title }} | {{ site.title }}
        {% else %}
            {{ site.title }}
        {% endif %}
    </title>
    <meta name="description" content="{{ site.description }}">

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
    <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">

    <script>
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-70403163-1', 'auto');
        ga('send', 'pageview');

    </script>
</head>


text:
package appeng.api.implementations.tiles;

import appeng.api.networking.IGridHost;
import appeng.api.storage.ICellContainer;
import appeng.api.util.IOrientable;

public interface IChestOrDrive extends ICellContainer, IGridHost, IOrientable {

    /**
     * @return how many slots are available. Chest has 1, Drive has 10.
     */
    int getCellCount();

    /**
     * 0 - cell is missing.
     *
     * 1 - green,
     *
     * 2 - orange,
     *
     * 3 - red
     *
     * @param slot
     * @return status of the slot, one of the above indices.
     */
    int getCellStatus(int slot);

    /**
     * @return if the device is online you should check this before providing any other information.
     */
    boolean isPowered();

    /**
     * @param slot
     * @return is the cell currently blinking to show activity.
     */
    boolean isCellBlinking(int slot);

}


text:
#ifndef VSE_SCENENODECOMP_HPP
#define VSE_SCENENODECOMP_HPP

#include <string>

#include "OgreSceneNode.h"
#include "OgreEntity.h"

#include "NRES.hpp"

#include "Vec3f.hpp"

namespace vse {

class SceneNodeComp : public nres::Component {
public:
    SceneNodeComp(const std::string& resname, const Vec3f& nodeOffset = Vec3f(0, 0, 0));
    ~SceneNodeComp();

    static const nres::ComponentID componentID;
    const nres::ComponentID& getID() const;

    // Populated by system
    Ogre::SceneNode* mSceneNode;
    Ogre::Entity* mOgreEntity;

    // Used to load resource
    std::string mResourceName;

    // Can translate scenenode by amount
    Vec3f mSceneNodeOffset;

    // Animation state
    Ogre::AnimationState* mAnimState;

};

}

#endif // VSE_SCENENODECOMP_HPP


text:
(function ($) {
  // register namespace
  $.extend(true, window, {
    Slick: {
      RowSelectionModel: RowSelectionModel
    }
  });

  function RowSelectionModel(options) {
    var _grid;
    var _ranges = [];
    var _rowIndexes = [];
    var _self = this;
    var _handler = new Slick.EventHandler();
    var _dragging;
    var _canvas;
    var _options;
    var _defaults = {
      selectActiveRow: true,
      dragToMultiSelect: false
    };

    function init(grid) {
      _options = $.extend(true, {}, _defaults, options);
      _grid = grid;
      _handler.subscribe(_grid.onActiveCellChanged, handleActiveCellChange);
      _handler.subscribe(_grid.onKeyDown, handleKeyDown);
      _handler.subscribe(_grid.onClick, handleClick);

      if (_options.dragToMultiSelect) {
        if (_grid.getOptions().multiSelect) {
          _handler.subscribe(_grid.onDragInit, handleDragInit)
            .subscribe(_grid.onDragStart, handleDragStart)
            .subscribe(_grid.onDrag, handleDrag)
            .subscribe(_grid.onDragEnd, handleDragEnd);
          _dragging = false;
          _canvas = _grid.getCanvasNode();
        } else {
          console.log("Can't do drag to Multi Select unless multiSelect is enabled for the grid");
        }
      }
    }

    function destroy() {
      _handler.unsubscribeAll();
    }

    function rangesToRows(ranges) {
      var rows = [];
      for (var i = 0; i < ranges.length; i++) {
        for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) {
          rows.push(j);
        }
      }
      return rows;
    }

    function rowsToRanges(rows) {
      var ranges = [];
      var lastCell = _grid.getColumns().length - 1;
      for (var i = 0; i < rows.length; i++) {
        ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell));
      }
      return ranges;
    }

    function getRowsRange(from, to) {
      var i, rows = [];
      for (i = from; i <= to; i++) {
        rows.push(i);
      }
      for (i = to; i <= from; i++) {
        rows.push(i);
      }
      return rows;
    }

    function unionArrays(x, y) {
      var i;
      var obj = {};
      for (i = x.length - 1; i >= 0; i--) {
        obj[x[i]] = x[i];
      }
      for (i = y.length - 1; i >= 0; i--) {
        obj[y[i]] = y[i];
      }
      var res = [];
      for (var k in obj) {
        if (obj.hasOwnProperty(k)) {
          res.push(obj[k]);
        }
      }
      return res;
    }

    function xorArrays(x, y) {
      var i;
      var obj = {};
      for (i = x.length - 1; i >= 0; i--) {
        obj[x[i]] = x[i];
      }
      for (i = y.length - 1; i >= 0; i--) {
        if (obj.hasOwnProperty(y[i])) {
          delete obj[y[i]];
        } else {
          obj[y[i]] = y[i];
        }
      }
      var res = [];
      for (var k in obj) {
        if (obj.hasOwnProperty(k)) {
          res.push(obj[k]);
        }
      }
      return res;
    }

    function getSelectedRows() {
      return rangesToRows(_ranges);
    }

    function setSelectedRows(rows) {
      setSelectedRanges(rowsToRanges(rows));
    }

    function setSelectedRanges(ranges) {
      var
        selectionIndexes = $.map(ranges, function(r) {
          return r.fromRow;
        }),
        deleteIndexes = _rowIndexes.filter(function(elem) {
          return selectionIndexes.indexOf(elem) === -1;
        });

      _rowIndexes = selectionIndexes;
      _ranges = ranges;
      _self.onSelectedRangesChanged.notify(_ranges);
      _self.onSelectionChanged.notify({
        deletes: deleteIndexes,
        selection: selectionIndexes
        //multiselect: multiselect === true
      });
    }

    function getSelectedRanges() {
      return _ranges;
    }

    function handleActiveCellChange(e, data) {
      if (_options.selectActiveRow && data.activeCell.row != null) {
        setSelectedRanges([new Slick.Range(data.activeCell.row, 0, data.activeCell.row, _grid.getColumns().length - 1)]);
      }
    }

    function handleKeyDown(e) {
      var activeRow = _grid.getActiveCell();
      if (activeRow && e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey && (e.which == 38 || e.which == 40)) {
        var selectedRows = getSelectedRows();
        selectedRows.sort(function (x, y) {
          return x - y;
        });

        if (!selectedRows.length) {
          selectedRows = [activeRow.row];
        }

        var top = selectedRows[0];
        var bottom = selectedRows[selectedRows.length - 1];
        var active;

        if (e.which == 40) {
          active = activeRow.row < bottom || top == bottom ? ++bottom : ++top;
        } else {
          active = activeRow.row < bottom ? --bottom : --top;
        }

        if (active >= 0 && active < _grid.getDataLength()) {
          _grid.scrollRowIntoView(active);
          _ranges = rowsToRanges(getRowsRange(top, bottom));
          setSelectedRanges(_ranges);
        }

        e.preventDefault();
        e.stopPropagation();
      }
    }

    function handleClick(e) {
      var cell = _grid.getCellFromEvent(e);
      if (!cell || !_grid.canCellBeActive(cell.row, cell.cell)) {
        return false;
      }

      if (!_grid.getOptions().multiSelect || (
          !e.ctrlKey && !e.shiftKey && !e.metaKey)) {
        return false;
      }

      var selection = rangesToRows(_ranges);
      var idx = $.inArray(cell.row, selection);

      if (idx === -1 && (e.ctrlKey || e.metaKey)) {
        selection.push(cell.row);
        _grid.setActiveCell(cell.row, cell.cell);
      } else if (idx !== -1 && (e.ctrlKey || e.metaKey)) {
        selection = $.grep(selection, function (o, i) {
          return (o !== cell.row);
        });
        _grid.setActiveCell(cell.row, cell.cell);
      } else if (selection.length && e.shiftKey) {
        var last = selection.pop();
        var from = Math.min(cell.row, last);
        var to = Math.max(cell.row, last);
        selection = [];
        for (var i = from; i <= to; i++) {
          if (i !== last) {
            selection.push(i);
          }
        }
        selection.push(last);
        _grid.setActiveCell(cell.row, cell.cell);
      }

      _ranges = rowsToRanges(selection);
      setSelectedRanges(_ranges);
      e.stopImmediatePropagation();

      return true;
    }

    function handleDragInit(e, dd) {
      // prevent the grid from cancelling drag'n'drop by default
      e.stopImmediatePropagation();
    }

    function handleDragStart(e, dd) {
      var cell = _grid.getCellFromEvent(e);

      if (_grid.canCellBeSelected(cell.row, cell.cell)) {
        _dragging = true;
        e.stopImmediatePropagation();
      }

      if (!_dragging) {
        return;
      }

      _grid.focus();

      var x, y, o;
      o = $(_canvas).offset();
      x = dd.pageX - o.left;
      y = dd.pageY - o.top;
      var start = _grid.getCellFromPoint(x, y, {
        clipToValidRange: true
      });
      assert(start);

      var combinationMode = 'replace';
      if (e.shiftKey) {
        combinationMode = 'union';
      }
      if (e.ctrlKey || e.metaKey) {
        combinationMode = 'xor';
      }

      dd.range = {
        start: start,
        end: {}
      };
      dd.alreadySelectedRows = rangesToRows(_ranges);
      dd.combinationMode = combinationMode;
    }

    function handleDrag(e, dd) {
      if (!_dragging) {
        return;
      }
      e.stopImmediatePropagation();

      var x, y, o;
      o = $(_canvas).offset();
      x = e.pageX - o.left;
      y = e.pageY - o.top;
      var end = _grid.getCellFromPoint(x, y, {
        clipToValidRange: true
      });
      assert(end);

      if (!_grid.canCellBeSelected(end.row, end.cell)) {
        return;
      }
      _grid.setActiveCell(end.row, end.cell);
      dd.range.end = end;
      var rows = getRowsRange(dd.range.start.row, dd.range.end.row);
      if (dd.combinationMode === 'union') {
        rows = unionArrays(rows, dd.alreadySelectedRows);
      } else if (dd.combinationMode === 'xor') {
        rows = xorArrays(rows, dd.alreadySelectedRows);
      }

      _ranges = rowsToRanges(rows);
      setSelectedRanges(_ranges);
      return true;
    }

    function handleDragEnd(e, dd) {
      if (!_dragging) {
        return;
      }

      _dragging = false;
      e.stopImmediatePropagation();
    }

    $.extend(this, {
      "getSelectedRows": getSelectedRows,
      "setSelectedRows": setSelectedRows,

      "getSelectedRanges": getSelectedRanges,
      "setSelectedRanges": setSelectedRanges,

      "init": init,
      "destroy": destroy,

      "onSelectedRangesChanged": new Slick.Event(),
      "onSelectionChanged": new Slick.Event()
    });
  }
})(jQuery);


text:
package org.kodejava.example.itextpdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class PDFChunkDemo {
    public static void main(String[] args) {
        Document document = new Document();
        try {
            PdfWriter.getInstance(document,
                    new FileOutputStream("Chunk.pdf"));
            document.open();

            // Add some chunks into the document object.
            document.add(new Chunk("The quick brown fox "));
            document.add(new Chunk("jumps over the lazy dog."));
            document.add(new Chunk("The quick brown fox "));
            document.add(new Chunk("jumps over the lazy dog."));
            document.add(new Chunk("The quick brown fox ",
                    FontFactory.getFont(FontFactory.HELVETICA, 20,
                            Font.ITALIC, new BaseColor(0, 128, 0))));
            document.add(new Chunk("jumps over the lazy dog."));
            document.close();
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>CV of Johnny Clueprint</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="assets/css/style.css" media="all">

Protecting your security and privacy since 1990. Based in Tiknadelsin, San Francisco.

            CV of Johnny Clueprint

                     Private Eye

                    74 Mission Rock Street

San Francisco

California

94158

United States

 Professional Experience

2005-2015 Dirmank Ltd.

Responsibilities

            Pellentesque pulvinar luctus finibus. Ut tristique felis massa, aliquam accumsan
            est tincidunt non. Vestibulum sollicitudin dui lectus, sed condimentum
            diam viverra eget. In eleifend aliquam mi sit amet volutpat. Pellentesque
            justo eros, consectetur at ligula ac, tincidunt imperdiet arcu. Quisque
            in purus urna. Aenean venenatis nisl placerat, pharetra ligula eget,
            vestibulum est. Cras volutpat orci vitae leo pulvinar, vitae tincidunt
            dolor ornare. Suspendisse non consequat leo. In ut pharetra massa.
            Donec blandit eros sed laoreet aliquet. Nullam aliquet volutpat tellus,
            sed laoreet augue. Proin id semper diam. Nullam ullamcorper, tellus
            ac luctus dapibus, purus odio tincidunt est, quis tempus urna elit
            sit amet nisl. In justo tortor, dignissim eget nulla vitae, mattis
            egestas nulla.

            Nulla sem felis, condimentum sed tellus nec, blandit eleifend nibh. Curabitur nec
            convallis libero. Mauris finibus a augue vel commodo. Nunc auctor metus
            quis mi interdum mollis. Nulla condimentum eget diam malesuada scelerisque.
            Etiam fringilla nisl cursus fringilla venenatis. Sed congue leo nec
            diam rutrum, id convallis nisl sollicitudin. In auctor aliquet luctus.
            Aliquam id est ac orci ullamcorper facilisis. Praesent vel ligula non
            diam tempor tristique. Vivamus euismod facilisis justo quis facilisis.
            Ut rhoncus ex in odio suscipit, sit amet condimentum est commodo.

            Aliquam ac vulputate orci. Sed vehicula euismod ultrices. Ut egestas felis vitae
            quam pharetra placerat vel ut elit. Pellentesque pharetra orci et ex
            imperdiet feugiat. Nulla viverra ipsum quam, sed fermentum nunc ullamcorper
            id. Nullam pretium diam urna, sit amet maximus mauris fringilla at.
            Etiam vitae nisi mi. Donec et lectus volutpat, pulvinar tellus ut,
            sollicitudin leo.

            Curabitur at mi vitae erat consectetur luctus. Morbi nec ipsum vitae magna convallis
            dignissim. Maecenas in lectus ut mi consectetur congue id efficitur
            ex. Morbi faucibus odio in maximus egestas. Cum sociis natoque penatibus
            et magnis dis parturient montes, nascetur ridiculus mus. Aenean consequat
            bibendum quam, at bibendum elit euismod quis. Aenean vitae urna dolor.
            Aenean nec dolor suscipit, porttitor felis vitae, vestibulum lectus.
            Suspendisse sit amet quam a leo porttitor tempus. Vivamus varius lacinia
            varius. Integer ut urna vitae diam vestibulum elementum vitae eget
            turpis.

2001-2004 Dupont Ltd.

Responsibilities

            Curabitur at mi vitae erat consectetur luctus. Morbi nec ipsum vitae magna convallis
            dignissim. Maecenas in lectus ut mi consectetur congue id efficitur
            ex. Morbi faucibus odio in maximus egestas. Cum sociis natoque penatibus
            et magnis dis parturient montes, nascetur ridiculus mus. Aenean consequat
            bibendum quam, at bibendum elit euismod quis. Aenean vitae urna dolor.
            Aenean nec dolor suscipit, porttitor felis vitae, vestibulum lectus.
            Suspendisse sit amet quam a leo porttitor tempus. Vivamus varius lacinia
            varius. Integer ut urna vitae diam vestibulum elementum vitae eget
            turpis.

            Curabitur at mi vitae erat consectetur luctus. Morbi nec ipsum vitae magna convallis
            dignissim. Maecenas in lectus ut mi consectetur congue id efficitur
            ex. Morbi faucibus odio in maximus egestas. Cum sociis natoque penatibus
            et magnis dis parturient montes, nascetur ridiculus mus. Aenean consequat
            bibendum quam, at bibendum elit euismod quis. Aenean vitae urna dolor.
            Aenean nec dolor suscipit, porttitor felis vitae, vestibulum lectus.
            Suspendisse sit amet quam a leo porttitor tempus. Vivamus varius lacinia
            varius. Integer ut urna vitae diam vestibulum elementum vitae eget
            turpis.

            Curabitur at mi vitae erat consectetur luctus. Morbi nec ipsum vitae magna convallis
            dignissim. Maecenas in lectus ut mi consectetur congue id efficitur
            ex. Morbi faucibus odio in maximus egestas. Cum sociis natoque penatibus
            et magnis dis parturient montes, nascetur ridiculus mus. Aenean consequat
            bibendum quam, at bibendum elit euismod quis. Aenean vitae urna dolor.
            Aenean nec dolor suscipit, porttitor felis vitae, vestibulum lectus.
            Suspendisse sit amet quam a leo porttitor tempus. Vivamus varius lacinia
            varius. Integer ut urna vitae diam vestibulum elementum vitae eget
            turpis.

1996-2000 Pharmaco Ltd.

Responsibilities

            Curabitur at mi vitae erat consectetur luctus. Morbi nec ipsum vitae magna convallis
            dignissim. Maecenas in lectus ut mi consectetur congue id efficitur
            ex. Morbi faucibus odio in maximus egestas. Cum sociis natoque penatibus
            et magnis dis parturient montes, nascetur ridiculus mus. Aenean consequat
            bibendum quam, at bibendum elit euismod quis. Aenean vitae urna dolor.
            Aenean nec dolor suscipit, porttitor felis vitae, vestibulum lectus.
            Suspendisse sit amet quam a leo porttitor tempus. Vivamus varius lacinia
            varius. Integer ut urna vitae diam vestibulum elementum vitae eget
            turpis.

            Curabitur at mi vitae erat consectetur luctus. Morbi nec ipsum vitae magna convallis
            dignissim. Maecenas in lectus ut mi consectetur congue id efficitur
            ex. Morbi faucibus odio in maximus egestas. Cum sociis natoque penatibus
            et magnis dis parturient montes, nascetur ridiculus mus. Aenean consequat
            bibendum quam, at bibendum elit euismod quis. Aenean vitae urna dolor.
            Aenean nec dolor suscipit, porttitor felis vitae, vestibulum lectus.
            Suspendisse sit amet quam a leo porttitor tempus. Vivamus varius lacinia
            varius. Integer ut urna vitae diam vestibulum elementum vitae eget
            turpis.

Abilities

Ability to read people

Good memory

Delegation

Ability to follow directions

Ability to use initiative

Communication

Wisdom

Listening

Knowledge

Knowledge of legal procedures

Knowledge of the law

Contacts

Literacy

Qualities

Integrity

Tenacity

Patience

Tolerance of frustration

Love of learning

        Contact: 34-555-6677 / johnny@clueprint.com


text:
{{lang 'products.top' }}

{{#each products}}

    {{>components/products/card settings=../settings theme_settings=../theme_settings customer=../customer event="list" position=(add @index 1)}}

{{/each}}


text:
package org.jivesoftware.openfire.spi;

import org.jivesoftware.openfire.net.SocketAcceptThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A connection acceptor that employs the legacy, pre-MINA/NIO socket implementation of Openfire.
 *
 * @author Guus der Kinderen, guus.der.kinderen@gmail.com
 * @deprecated Used only for S2S, which should be be ported to NIO.
 */
@Deprecated
public class LegacyConnectionAcceptor extends ConnectionAcceptor
{
    private final Logger Log = LoggerFactory.getLogger( LegacyConnectionAcceptor.class );

    private SocketAcceptThread socketAcceptThread;

    /**
     * Constructs a new instance which will accept new connections based on the provided configuration.
     *

     * The provided configuration is expected to be immutable. ConnectionAcceptor instances are not expected to handle
     * changes in configuration. When such changes are to be applied, an instance is expected to be replaced.
     *

     * Newly instantiated ConnectionAcceptors will not accept any connections before {@link #start()} is invoked.
     *
     * @param configuration The configuration for connections to be accepted (cannot be null).
     */
    public LegacyConnectionAcceptor( ConnectionConfiguration configuration )
    {
        super( configuration );
    }

    /**
     * Starts this acceptor by binding the socket acceptor. When the acceptor is already started, a warning will be
     * logged and the method invocation is otherwise ignored.
     */
    @Override
    public synchronized void start()
    {
        if ( socketAcceptThread != null )
        {
            Log.warn( "Unable to start acceptor (it is already started!)" );
            return;
        }

        if ( configuration.getMaxThreadPoolSize() > 1 ) {
            Log.warn( "Configuration allows for up to " + configuration.getMaxThreadPoolSize() + " threads, although implementation is limited to exactly one." );
        }

        try {
            socketAcceptThread = new SocketAcceptThread(configuration.getPort(), configuration.getBindAddress());
            socketAcceptThread.setDaemon(true);
            socketAcceptThread.setPriority(Thread.MAX_PRIORITY);
            socketAcceptThread.start();

        }
        catch (Exception e) {
            System.err.println( "Error starting " + configuration.getPort() + ": " + e.getMessage() );
            Log.error( "Error starting: " + configuration.getPort(), e );

            // Reset for future use.
            if (socketAcceptThread != null ) {
                try {
                    socketAcceptThread.shutdown();
                } finally {
                    socketAcceptThread = null;
                }
            }
        }
    }

    /**
     * Stops this acceptor by unbinding the socket acceptor. Does nothing when the instance is not started.
     */
    @Override
    public synchronized void stop()
    {
        if ( socketAcceptThread != null ) {
            try {
                socketAcceptThread.shutdown();
            } finally {
                socketAcceptThread = null;
            }
        }
    }

    @Override
    boolean isIdle()
    {
        return socketAcceptThread != null; // We're not tracking actual sessions. This is a best effort response.
    }
}


text:
@interface STDateVC : UIViewController

@end


text:
from defaults.constants_default import *

# The values you set in this file will overwrite those in
# defaults/constants_defaults.py

NEXUS = "#206"

IC_START = "#492"

EMAIL = False

MAIL_FROM = 'messages@wintersoasis.com'

MAX_MESSAGES = 10


text:
mrcrowbar.lib.audio.voc module
==============================

.. automodule:: mrcrowbar.lib.audio.voc
    :members:
    :undoc-members:
    :show-inheritance: