text:
#include "userprog/gdt.h"
#include <debug.h>
#include "userprog/tss.h"
#include "threads/palloc.h"
#include "threads/vaddr.h"

/* The Global Descriptor Table (GDT).

   The GDT, an x86-specific structure, defines segments that can
   potentially be used by all processes in a system, subject to
   their permissions.  There is also a per-process Local
   Descriptor Table (LDT) but that is not used by modern
   operating systems.

   Each entry in the GDT, which is known by its byte offset in
   the table, identifies a segment.  For our purposes only three
   types of segments are of interest: code, data, and TSS or
   Task-State Segment descriptors.  The former two types are
   exactly what they sound like.  The TSS is used primarily for
   stack switching on interrupts.

   For more information on the GDT as used here, refer to
   [IA32-v3a] 3.2 "Using Segments" through 3.5 "System Descriptor
   Types". */
static uint64_t gdt[SEL_CNT];

/* GDT helpers. */
static uint64_t make_code_desc (int dpl);
static uint64_t make_data_desc (int dpl);
static uint64_t make_tss_desc (void *laddr);
static uint64_t make_gdtr_operand (uint16_t limit, void *base);

/* Sets up a proper GDT.  The bootstrap loader's GDT didn't
   include user-mode selectors or a TSS, but we need both now. */
void
gdt_init (void)
{
  uint64_t gdtr_operand;

  /* Initialize GDT. */
  gdt[SEL_NULL / sizeof *gdt] = 0;
  gdt[SEL_KCSEG / sizeof *gdt] = make_code_desc (0);
  gdt[SEL_KDSEG / sizeof *gdt] = make_data_desc (0);
  gdt[SEL_UCSEG / sizeof *gdt] = make_code_desc (3);
  gdt[SEL_UDSEG / sizeof *gdt] = make_data_desc (3);
  gdt[SEL_TSS / sizeof *gdt] = make_tss_desc (tss_get_ ());

  /* Load GDTR, TR.  See [IA32-v3a] 2.4.1 "Global Descriptor
     Table Register (GDTR)", 2.4.4 "Task Register (TR)", and
     6.2.4 "Task Register".  */
  gdtr_operand = make_gdtr_operand (sizeof gdt - 1, gdt);
  asm volatile ("lgdt %0" : : "m" (gdtr_operand));
  asm volatile ("ltr %w0" : : "q" (SEL_TSS));
}

/* System segment or code/data segment? */
enum seg_class
  {
    CLS_SYSTEM = 0,             /* System segment. */
    CLS_CODE_DATA = 1           /* Code or data segment. */
  };

/* Limit has byte or 4 kB page granularity? */
enum seg_granularity
  {
    GRAN_BYTE = 0,              /* Limit has 1-byte granularity. */
    GRAN_PAGE = 1               /* Limit has 4 kB granularity. */
  };

/* Returns a segment descriptor with the given 32-bit BASE and
   20-bit LIMIT (whose interpretation depends on GRANULARITY).
   The descriptor represents a system or code/data segment
   according to CLASS, and TYPE is its type (whose interpretation
   depends on the class).

   The segment has descriptor privilege level DPL, meaning that
   it can be used in rings numbered DPL or lower.  In practice,
   DPL==3 means that user processes can use the segment and
   DPL==0 means that only the kernel can use the segment.  See
   [IA32-v3a] 4.5 "Privilege Levels" for further discussion. */
static uint64_t
make_seg_desc (uint32_t base,
               uint32_t limit,
               enum seg_class class,
               int type,
               int dpl,
               enum seg_granularity granularity)
{
  uint32_t e0, e1;

  ASSERT (limit <= 0xfffff);
  ASSERT (class == CLS_SYSTEM || class == CLS_CODE_DATA);
  ASSERT (type >= 0 && type <= 15);
  ASSERT (dpl >= 0 && dpl <= 3);
  ASSERT (granularity == GRAN_BYTE || granularity == GRAN_PAGE);

  e0 = ((limit & 0xffff)             /* Limit 15:0. */
        | (base << 16));             /* Base 15:0. */

  e1 = (((base >> 16) & 0xff)        /* Base 23:16. */
        | (type << 8)                /* Segment type. */
        | (class << 12)              /* 0=system, 1=code/data. */
        | (dpl << 13)                /* Descriptor privilege. */
        | (1 << 15)                  /* Present. */
        | (limit & 0xf0000)          /* Limit 16:19. */
        | (1 << 22)                  /* 32-bit segment. */
        | (granularity << 23)        /* Byte/page granularity. */
        | (base & 0xff000000));      /* Base 31:24. */

  return e0 | ((uint64_t) e1 << 32);
}

/* Returns a descriptor for a readable code segment with base at
   0, a limit of 4 GB, and the given DPL. */
static uint64_t
make_code_desc (int dpl)
{
  return make_seg_desc (0, 0xfffff, CLS_CODE_DATA, 10, dpl, GRAN_PAGE);
}

/* Returns a descriptor for a writable data segment with base at
   0, a limit of 4 GB, and the given DPL. */
static uint64_t
make_data_desc (int dpl)
{
  return make_seg_desc (0, 0xfffff, CLS_CODE_DATA, 2, dpl, GRAN_PAGE);
}

/* Returns a descriptor for an "available" 32-bit Task-State
   Segment with its base at the given linear address, a limit of
   0x67 bytes (the size of a 32-bit TSS), and a DPL of 0.
   See [IA32-v3a] 6.2.2 "TSS Descriptor". */
static uint64_t
make_tss_desc (void *laddr)
{
  return make_seg_desc ((uint32_t) laddr, 0x67, CLS_SYSTEM, 9, 0, GRAN_BYTE);
}

/* Returns a descriptor that yields the given LIMIT and BASE when
   used as an operand for the LGDT instruction. */
static uint64_t
make_gdtr_operand (uint16_t limit, void *base)
{
  return limit | ((uint64_t) (uint32_t) base << 16);
}


text: Wannabe implementation of https://storm.apache.org/

redpajama_set_name: RedPajamaGithub


text:
package porter

import (
	"bytes"

	"github.com/blevesearch/bleve/analysis"
	"github.com/blevesearch/bleve/registry"

	"github.com/blevesearch/go-porterstemmer"
)

const Name = "stemmer_porter"

type PorterStemmer struct {
}

func NewPorterStemmer() *PorterStemmer {
	return &PorterStemmer{}
}

func (s *PorterStemmer) Filter(input analysis.TokenStream) analysis.TokenStream {
	for _, token := range input {
		// if it is not a protected keyword, stem it
		if !token.KeyWord {
			termRunes := bytes.Runes(token.Term)
			stemmedRunes := porterstemmer.StemWithoutLowerCasing(termRunes)
			token.Term = analysis.BuildTermFromRunes(stemmedRunes)
		}
	}
	return input
}

func PorterStemmerConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) {
	return NewPorterStemmer(), nil
}

func init() {
	registry.RegisterTokenFilter(Name, PorterStemmerConstructor)
}


text:
<?php

//namespace Tetranz\Select2EntityBundle\Form\Type;

namespace UtilBundle\Form\Type;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Routing\RouterInterface;
use UtilBundle\Form\DataTransformer\EntitiesToPropertyTransformer;
use UtilBundle\Form\DataTransformer\EntityToPropertyTransformer;

/**
 *
 * Class Select2EntityType
 * @package Tetranz\Select2EntityBundle\Form\Type
 */
class Select2EntityType extends AbstractType {
	/** @var EntityManagerInterface */
	protected $em;
	/** @var RouterInterface */
	protected $router;
	/** @var  array */
	protected $config;

	/**
	 * @param EntityManagerInterface $em
	 * @param RouterInterface $router
	 * @param array $config
	 */
	public function __construct( EntityManagerInterface $em, RouterInterface $router, $config ) {
		$this->em     = $em;
		$this->router = $router;
		$this->config = $config;
	}

	public function buildForm( FormBuilderInterface $builder, array $options ) {
		// add custom data transformer
		if ( $options['transformer'] ) {
			if ( ! is_string( $options['transformer'] ) ) {
				throw new \Exception( 'The option transformer must be a string' );
			}
			if ( ! class_exists( $options['transformer'] ) ) {
				throw new \Exception( 'Unable to load class: ' . $options['transformer'] );
			}

			$transformer = new $options['transformer']( $this->em, $options['class'] );

			if ( ! $transformer instanceof DataTransformerInterface ) {
				throw new \Exception( sprintf( 'The custom transformer %s must implement "Symfony\Component\Form\DataTransformerInterface"',
					get_class( $transformer ) ) );
			}

			// add the default data transformer
		} else {

			if ( isset( $options['allow_add']['new_tag_prefix'] ) ) {
				$newTagPrefix = $options['allow_add']['new_tag_prefix'];
			} else {
				$newTagPrefix = $this->config['allow_add']['new_tag_prefix'];
			}

			$transformer = $options['multiple']
				? new EntitiesToPropertyTransformer( $this->em,
					$options['class'],
					$options['text_property'],
					$options['primary_key'],
					$newTagPrefix )
				: new EntityToPropertyTransformer( $this->em,
					$options['class'],
					$options['text_property'],
					$options['primary_key'] );
		}

		$builder->addViewTransformer( $transformer, true );
	}

	public function finishView( FormView $view, FormInterface $form, array $options ) {
		parent::finishView( $view, $form, $options );
		// make variables available to the view
		$view->vars['remote_path'] = $options['remote_path']
			?: $this->router->generate( $options['remote_route'],
				array_merge( $options['remote_params'], [ 'page_limit' => $options['page_limit'] ] ) );

		// merge variable names which are only set per instance with those from yml config
		$varNames = array_merge( array( 'multiple', 'placeholder', 'primary_key' ), array_keys( $this->config['tetranz_select2_entity'] ) );
		foreach ( $varNames as $varName ) {
			$view->vars[ $varName ] = $options[ $varName ];
		}

		//tags options
		$varNames = array_keys( $this->config['tetranz_select2_entity']['allow_add'] );
		foreach ( $varNames as $varName ) {
			if ( isset( $options['allow_add'][ $varName ] ) ) {
				$view->vars['allow_add'][ $varName ] = $options['allow_add'][ $varName ];
			} else {
				$view->vars['allow_add'][ $varName ] = $this->config['tetranz_select2_entity']['allow_add'][ $varName ];
			}
		}

		if ( $options['multiple'] ) {
			$view->vars['full_name'] .= '[]';
		}
	}

	/**
	 * Added for pre Symfony 2.7 compatibility
	 *
	 * @param OptionsResolverInterface $resolver
	 */
	public function setDefaultOptions( OptionsResolverInterface $resolver ) {
		$this->configureOptions( $resolver );
	}

	/**
	 * @param OptionsResolver $resolver
	 */
	public function configureOptions( OptionsResolver $resolver ) {
		$resolver->setDefaults(
			array(
				'class'                => null,
				'primary_key'          => 'id',
				'remote_path'          => null,
				'remote_route'         => null,
				'remote_params'        => array(),
				'multiple'             => false,
				'compound'             => false,
				'minimum_input_length' => $this->config['tetranz_select2_entity']['minimum_input_length'],
				'page_limit'           => $this->config['tetranz_select2_entity']['page_limit'],
				'scroll'               => $this->config['tetranz_select2_entity']['scroll'],
				'allow_clear'          => $this->config['tetranz_select2_entity']['allow_clear'],
				'allow_add'            => array(
					'enabled'        => $this->config['tetranz_select2_entity']['allow_add']['enabled'],
					'new_tag_text'   => $this->config['tetranz_select2_entity']['allow_add']['new_tag_text'],
					'new_tag_prefix' => $this->config['tetranz_select2_entity']['allow_add']['new_tag_prefix'],
					'tag_separators' => $this->config['tetranz_select2_entity']['allow_add']['tag_separators']
				),
				'delay'                => $this->config['tetranz_select2_entity']['delay'],
				'text_property'        => null,
				'placeholder'          => '',
				'language'             => $this->config['tetranz_select2_entity']['language'],
				'required'             => false,
				'cache'                => $this->config['tetranz_select2_entity']['cache'],
				'cache_timeout'        => $this->config['tetranz_select2_entity']['cache_timeout'],
				'transformer'          => null,
			)
		);
	}

	/**
	 * pre Symfony 3 compatibility
	 *
	 * @return string
	 */
	public function getName() {
		return $this->getBlockPrefix();
	}

	/**
	 * Symfony 2.8+
	 *
	 * @return string
	 */
	public function getBlockPrefix() {
		return 'tetranz_select2entity';
	}
}


text:
package org.umlgraph.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Collection of utility methods used by the test classes
 * @author wolf
 *
 */
public class TestUtils {

    /**
         * Simple text file diffing: will tell you if two text files are line by
         * line equals, and will stop at the first difference found.
         * @throws IOException
         */
    public static boolean textFilesEquals(PrintWriter pw, File refTextFile, File outTextFile)
	    throws IOException {
	BufferedReader refReader = null, outReader = null;
	String refLine = null, outFile = null;
	try {
	    pw.println("Performing diff:");
	    pw.println("out: " + outTextFile.getAbsolutePath());
	    pw.println("ref: " + refTextFile.getAbsolutePath());

	    refReader = new BufferedReader(new FileReader(refTextFile));
	    outReader = new BufferedReader(new FileReader(outTextFile));

	    /*
	     * Line by line scan, exit when one file ends or lines are not
	     * equal.
	     * Ignore the "Generated by javadoc ..." comments, and the
	     * "<META NAME="date"" tags
	     */
	    for (;;) {
		refLine = refReader.readLine();
		outFile = outReader.readLine();
		if (refLine == null || outFile == null) {
		    break;
		} else if (refLine.startsWith("<meta name=\"date\"")) {
		    if (!outFile.startsWith("<meta name=\"date\""))
			break;
		} else if (refLine.startsWith("<!-- Generated by javadoc ")) {
		    if (!outFile.startsWith("<!-- Generated by javadoc "))
			break;
		} else if (refLine.startsWith("<!-- UML diagram added by UMLGraph")) {
		    if (!outFile.startsWith("<!-- UML diagram added by UMLGraph"))
			break;
		} else if (!refLine.equals(outFile)) {
		    break;
		}

	    }
	} finally {
	    if (refReader != null)
		refReader.close();
	    if (outReader != null)
		outReader.close();
	}
	// they were equals if both files ended at the same time
	boolean equal = refLine == null && outFile == null;
	if (equal)
	    pw.print("File contents are equal");
	else
	    pw.println("Differences found\nref: " + refLine + "\nout: " + outFile);
	pw.println();
	pw.println();

	return equal;
    }

    public static boolean dotFilesEqual(PrintWriter pw, String dotPath, String refPath)
	    throws IOException {
	pw.println("Performing diff:\nout:" + dotPath + "\nref:" + refPath);
	DotDiff differ = new DotDiff(new File(dotPath), new File(refPath));
	boolean equal = differ.graphEquals();
	if (equal) {
	    pw.println("File contents are structurally equal");
	} else {
	    pw.println("File contents are structurally not equal");
	    printList(pw, "# Lines in out but not in ref", differ.getExtraLines1());
	    printList(pw, "# Lines in ref but not in out", differ.getExtraLines2());
	    printList(pw, "# Nodes in out but not in ref", differ.getNodes1());
	    printList(pw, "# Nodes in ref but not in out", differ.getNodes2());
	    printList(pw, "# Arcs in out but not in ref", differ.getArcs1());
	    printList(pw, "# Arcs in ref but not in out", differ.getArcs2());
	}
	pw.println("\n\n");
	return equal;
    }

    public static void printList(PrintWriter pw, String message, List<?> extraOut) {
	if (extraOut.size() > 0) {
	    pw.println(message);
	    for (Object o : extraOut) {
		pw.println(o);
	    }
	}
    }

    /**
         * Deletes the content of the folder, eventually in a recursive way (but
         * avoids deleting eventual .cvsignore files and CVS folders)
         */
    public static void cleanFolder(File folder, boolean recurse) {
	for (File f : folder.listFiles()) {
	    if (f.isDirectory() && !f.getName().equals("CVS")) {
		if (recurse) {
		    cleanFolder(f, true);
		    if (f.list().length == 0)
			f.delete();
		}
	    } else if (!f.getName().equals(".cvsignore")) {
		f.delete();
	    }

	}

    }

}


text:
package gendoc_test

import (
	"bytes"
	"fmt"
	"github.com/pseudomuto/protoc-gen-doc"
	"github.com/stretchr/testify/suite"
	"testing"
)

type FlagsTest struct {
	suite.Suite
}

func TestFlags(t *testing.T) {
	suite.Run(t, new(FlagsTest))
}

func (assert *FlagsTest) TestCode() {
	f := gendoc.ParseFlags(nil, []string{"app", "-help"})
	assert.Equal(0, f.Code())

	f = gendoc.ParseFlags(nil, []string{"app", "-whoawhoawhoa"})
	assert.Equal(1, f.Code())
}

func (assert *FlagsTest) TestHasMatch() {
	f := gendoc.ParseFlags(nil, []string{"app", "-help"})
	assert.True(f.HasMatch())

	f = gendoc.ParseFlags(nil, []string{"app", "-version"})
	assert.True(f.HasMatch())

	f = gendoc.ParseFlags(nil, []string{"app", "-watthewhat"})
	assert.True(f.HasMatch())

	f = gendoc.ParseFlags(nil, []string{"app"})
	assert.False(f.HasMatch())
}

func (assert *FlagsTest) TestShowHelp() {
	f := gendoc.ParseFlags(nil, []string{"app", "-help"})
	assert.True(f.ShowHelp())

	f = gendoc.ParseFlags(nil, []string{"app", "-version"})
	assert.False(f.ShowHelp())
}

func (assert *FlagsTest) TestShowVersion() {
	f := gendoc.ParseFlags(nil, []string{"app", "-version"})
	assert.True(f.ShowVersion())

	f = gendoc.ParseFlags(nil, []string{"app", "-help"})
	assert.False(f.ShowVersion())
}

func (assert *FlagsTest) TestPrintHelp() {
	buf := new(bytes.Buffer)

	f := gendoc.ParseFlags(buf, []string{"app"})
	f.PrintHelp()

	result := buf.String()
	assert.Contains(result, "Usage of app:\n\n")
	assert.Contains(result, "FLAGS\n")
	assert.Contains(result, "-help")
	assert.Contains(result, "-version")
}

func (assert *FlagsTest) TestPrintVersion() {
	buf := new(bytes.Buffer)

	f := gendoc.ParseFlags(buf, []string{"app"})
	f.PrintVersion()

	// Normally, I'm not a fan of using constants like this in tests. However, having this break everytime the version
	// changes is kinda poop, so I've used VERSION here.
	assert.Equal(fmt.Sprintf("app version %s\n", gendoc.VERSION), buf.String())
}

func (assert *FlagsTest) TestInvalidFlags() {
	buf := new(bytes.Buffer)

	f := gendoc.ParseFlags(buf, []string{"app", "-wat"})
	assert.Contains(buf.String(), "flag provided but not defined: -wat\n")
	assert.True(f.HasMatch())
	assert.True(f.ShowHelp())
}


text:
using SpiceSharp.Attributes;

namespace SpiceSharp.Components.SwitchBehaviors
{
    /// <summary>
    /// Base parameters for a switch.
    /// </summary>
    /// <seealso cref="SpiceSharp.ParameterSet" />
    public class BaseParameters : ParameterSet
    {
        /// <summary>
        /// Sets the switch initially to conducting.
        /// </summary>
        [ParameterName("on"), ParameterInfo("Initially closed")]
        public void SetZeroStateOn() { ZeroState = true; }

        /// <summary>
        /// Set the switch initially to non-conducting.
        /// </summary>
        [ParameterName("off"), ParameterInfo("Initially open")]
        public void SetZeroStateOff() { ZeroState = false; }

        /// <summary>
        /// Gets or sets initial state.
        /// </summary>
        public bool ZeroState { get; set; }
    }
}


text:
typedef void(^slideBlock)(CGFloat value);
typedef NS_ENUM(NSUInteger, sliderControlStyle) {
    sliderControlStyleFontSize,
    sliderControlStyleSpeed,
    sliderControlStyleOpacity
};

@interface SliderControlCell : NSView
- (void)setWithBlock:(slideBlock)block sliderControlStyle:(sliderControlStyle)style;
@end


text:
#include "tensorflow/lite/delegates/gpu/gl/kernels/max_unpooling.h"

#include <algorithm>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>

#include "absl/memory/memory.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/types.h"
#include "tensorflow/lite/delegates/gpu/gl/variable.h"

namespace tflite {
namespace gpu {
namespace gl {
namespace {

class MaxUnpooling : public NodeShader {
 public:
  absl::Status GenerateCode(const GenerationContext& ctx,
                            GeneratedCode* generated_code) const final {
    const auto& attr =
        absl::any_cast<const MaxUnpooling2DAttributes&>(ctx.op_attr);
    std::vector<Variable> parameters = {
        {"stride", int2(attr.strides.w, attr.strides.h)},
        {"offset", int2(attr.padding.prepended.w, attr.padding.prepended.h)},
        {"window_h", attr.kernel.h},
        {"window_w", attr.kernel.w},
    };

    std::string source = R"(
      ivec2 coord = (gid.xy + $offset$) / $stride$;
      ivec4 indices = $input_data_1[coord.x, coord.y, gid.z]$;
      vec4 input_ = $input_data_0[coord.x, coord.y, gid.z]$;
      coord = coord * $stride$ - $offset$;
      for (int i = 0; i < 4; ++i) {
        ivec2 t = coord + ivec2(indices[i] % $window_w$, indices[i] / $window_w$);
        if (t.x == gid.x && t.y == gid.y) {
          value_0[i] = input_[i];
        }
      }
    )";
    *generated_code = {
        /*parameters=*/std::move(parameters),
        /*objects=*/{},
        /*shared_variables=*/{},
        /*workload=*/uint3(),
        /*workgroup=*/uint3(),
        /*source_code=*/std::move(source),
        /*input=*/IOStructure::ONLY_DEFINITIONS,
        /*output=*/IOStructure::AUTO,
    };
    return absl::OkStatus();
  }
};

}  // namespace

std::unique_ptr<NodeShader> NewMaxUnpoolingNodeShader() {
  return absl::make_unique<MaxUnpooling>();
}

}  // namespace gl
}  // namespace gpu
}  // namespace tflite


text:
ZXing.Net.Mobile for Forms is meant to be used in your Xamarin.Forms apps.  It comes with Forms controls and pages for scanning and displaying barcodes.

If you are looking for barcode scanning functionality in your non-Forms Xamarin / Windows apps, check out the original [ZXing.Net.Mobile Component](https://components.xamarin.com/view/zxing.net.mobile).

# Usage

The easiest way to use scanner is to create an instance of the `ZXingScannerPage`:

```csharp
var scanPage = new ZXingScannerPage ();

scanPage.OnScanResult += (result) => {
	// Stop scanning
    scanPage.IsScanning = false;

	// Pop the page and show the result
    Device.BeginInvokeOnMainThread (() => {
        Navigation.PopAsync ();
        DisplayAlert("Scanned Barcode", result.Text, "OK");
    });
};

// Navigate to our scanner page
await Navigation.PushAsync (scanPage);
```

If you need more customization, you can also use the `ZXingScannerView` in your own custom page:

```csharp
using Xamarin.Forms;
using ZXing.Net.Mobile.Forms;

namespace FormsSample
{
    public class CustomScanPage : ContentPage
    {
        ZXingScannerView zxing;
        ZXingDefaultOverlay overlay;

        public CustomScanPage () : base ()
        {
            zxing = new ZXingScannerView
            {
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions = LayoutOptions.FillAndExpand
            };
            zxing.OnScanResult += (result) =>
                Device.BeginInvokeOnMainThread (async () => {

                    // Stop analysis until we navigate away so we don't keep reading barcodes
                    zxing.IsAnalyzing = false;

                    // Show an alert
                    await DisplayAlert ("Scanned Barcode", result.Text, "OK");

                    // Navigate away
                    await Navigation.PopAsync ();
                });

            overlay = new ZXingDefaultOverlay
            {
                TopText = "Hold your phone up to the barcode",
                BottomText = "Scanning will happen automatically",
                ShowFlashButton = zxing.HasTorch,
            };
            overlay.FlashButtonClicked += (sender, e) => {
                zxing.IsTorchOn = !zxing.IsTorchOn;
            };
            var grid = new Grid
            {
                VerticalOptions = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand,
            };
            grid.Children.Add(zxing);
            grid.Children.Add(overlay);

            // The root page of your application
            Content = grid;
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();

            zxing.IsScanning = true;
        }

        protected override void OnDisappearing()
        {
            zxing.IsScanning = false;

            base.OnDisappearing();
        }
    }
}
```

##Custom Overlays

It's very simple to use a custom overlay.  If you are using the `ZXingScannerPage` you can pass in any `View` for the `customOverlay` parameter in the constructor.

```csharp
// Create our custom overlay
var customOverlay = new StackLayout {
    HorizontalOptions = LayoutOptions.FillAndExpand,
    VerticalOptions = LayoutOptions.FillAndExpand
};
var torch = new Button {
    Text = "Toggle Torch"
};
torch.Clicked += delegate {
    scanPage.ToggleTorch ();
};
customOverlay.Children.Add (torch);

// Pass in the custom overlay
scanPage = new ZXingScannerPage (customOverlay: customOverlay);
scanPage.OnScanResult += (result) => {
    scanPage.IsScanning = false;

    Device.BeginInvokeOnMainThread(() =>
    {
        Navigation.PopAsync();
        DisplayAlert("Scanned Barcode", result.Text, "OK");
    });
};
await Navigation.PushAsync (scanPage);
```

If you are using `ZXingScannerView` on your own page, of course you are responsible for adding your own overlay.

## Barcode Formats

By default, all barcode formats are monitored while scanning.  You can change which formats to check for by passing a `MobileBarcodeScanningOptions` instance into the `ZXingScannerPage`'s constructor.

```csharp
var options = new ZXing.Mobile.MobileBarcodeScanningOptions();
options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
  ZXing.BarcodeFormat.Ean8, ZXing.BarcodeFormat.Ean13
};

var scanPage = new ZXingScannerPage (options);

// ...
```

You can also set the `Options` property if you are using the `ZXingScannerView` control directly.

## Displaying / Generating Barcodes

There is also a `ZXingBarcodeImageView` control available that can be used within any Xamarin.Forms page:

```csharp
public class BarcodePage : ContentPage
{
    ZXingBarcodeImageView barcode;

    public BarcodePage ()
    {
        barcode = new ZXingBarcodeImageView {
            HorizontalOptions = LayoutOptions.FillAndExpand,
            VerticalOptions = LayoutOptions.FillAndExpand,
        };
        barcode.BarcodeFormat = ZXing.BarcodeFormat.QR_CODE;
        barcode.BarcodeOptions.Width = 300;
        barcode.BarcodeOptions.Height = 300;
        barcode.BarcodeOptions.Margin = 10;
        barcode.BarcodeValue = "ZXing.Net.Mobile";

        Content = barcode;
    }
}
```


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.uff.ic.oceano.core.dao.impl;

import br.uff.ic.oceano.core.dao.SoftwareProjectDao;
import br.uff.ic.oceano.core.dao.controle.anotations.MetodoRecuperaLista;
import br.uff.ic.oceano.core.dao.controle.anotations.MetodoRecuperaUnico;
import br.uff.ic.oceano.core.dao.generics.JPADaoGenerico;
import br.uff.ic.oceano.core.exception.MetodoInterceptadoException;
import br.uff.ic.oceano.core.exception.ObjetoNaoEncontradoException;
import br.uff.ic.oceano.core.model.OceanoUser;
import br.uff.ic.oceano.core.model.SoftwareProject;
import br.uff.ic.oceano.ostra.model.Item;
import java.util.List;

/**
 *
 * @author Heliomar
 */
public class SoftwareProjectDaoImpl extends JPADaoGenerico<SoftwareProject, Long> implements SoftwareProjectDao {

    public SoftwareProjectDaoImpl() {
        super(SoftwareProject.class);
    }

    @MetodoRecuperaUnico
    public SoftwareProject getProjectToDetailById(Long id) throws ObjetoNaoEncontradoException {
        throw new MetodoInterceptadoException();
    }

    @MetodoRecuperaUnico
    public SoftwareProject getByRepositoryUrl(String repositoryUrl) throws ObjetoNaoEncontradoException {
        throw new MetodoInterceptadoException();
    }

    @MetodoRecuperaUnico
    public SoftwareProject getByItem(Item item) throws ObjetoNaoEncontradoException {
        throw new MetodoInterceptadoException();
    }

    @MetodoRecuperaLista
    public List<SoftwareProject> getProjectsByOceanoUser(OceanoUser oceanoUser) {
        throw new MetodoInterceptadoException();
    }

    @MetodoRecuperaLista
    public List<SoftwareProject> getMavenProjectsByUser(OceanoUser oceanoUser) {
        throw new MetodoInterceptadoException();
    }

}


text:
package io.minestack.doublechest.model.node;

import io.minestack.doublechest.model.Model;
import io.minestack.doublechest.model.network.Network;
import lombok.Getter;
import lombok.Setter;
import org.bson.types.ObjectId;

import java.util.Date;

public class NetworkNode extends Model {

    @Getter
    @Setter
    private Node node;

    @Getter
    @Setter
    private Network network;

    public NetworkNode(ObjectId id, Date created_at) {
        super(id, created_at);
    }

}


text:
package org.domeos.framework.api.mapper.portal;

import org.apache.ibatis.annotations.*;
import org.domeos.framework.api.model.alarm.falcon.portal.Mockcfg;

/**
 * Created by baokangwang on 2016/4/14.
 */
@Mapper
public interface PortalMockcfgMapper {

    @Select("SELECT * FROM mockcfg WHERE name=#{name}")
    Mockcfg getMockcfgByName(@Param("name") String name);

    @Insert("INSERT INTO mockcfg (name, obj, obj_type, metric, tags, dstype, step, mock, creator, t_create, t_modify) " +
            "VALUES (#{name}, #{obj}, #{obj_type}, #{metric}, #{tags}, #{dstype}, #{step}, #{mock}, #{creator}, #{t_create}, #{t_modify})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int insertMockcfg(Mockcfg mockcfg);

    @Update("UPDATE mockcfg SET obj=#{obj} WHERE name=#{name}")
    int updateObjByName(@Param("name") String name, @Param("obj") String obj);
}


text:
@interface DemoSliderRadioButtonsDataSourceViewController : UIViewController {

}
@property (nonatomic, weak) IBOutlet CJRadioButtons *sliderRadioButtons;

@end


text:
<META http-equiv="content-type" content="text/html;charset=iso-8859-9"/><meta name="viewport" content="width=device-width, initial-scale=1"><title>ac</title> <link rel="stylesheet"  href="css/jquery.mobile-1.2.0.css" />

MAKSUD DEDE

Geri

Halveti yolu büyüklerinden. Ýsmi Maksud Dede'dir. Tokat'ta doðdu. Doðum tarihi
bilinmemektedir. 1562 (H.970) tarihinde Serez'de vefat etti. Oradaki müslümanlarýn
kabristanlýðýna defnedildi.

Maksud Dede, Sünbül Sinan hazretlerinin sohbetlerinde kemale gelip, olgunlaþtý. Ümmi idi,
lakin gönlü manevi ilimlerle dolmuþtu. Hocasý onu hak yolun bilgilerini öðretmesi için
Rumeli'ne gönderdi. Maksud Dede sonradan Serez'e yerleþti.

Yakub Efendi anlatýr: "Hocamýz Sünbül Efendi hazretleri bize zaman zaman Maksud
Dede'nin hallerini anlatýrdý. Bir zaman hocamýz Hakkýn rahmetine kavuþtu. Yerine
MerkezEfendi hazretleri geçti.Bana izin verip Rumellerine gönderdi. Ben de yola revan
oldum. Serez'e uðradým. Maksud Dede'yi ziyaret niyetiyle onun bulunduðu þehre gittim.
Þehre vardýðýmda karþýmdan nur yüzlü ihtiyar bir zat bana doðru geldi ve; "Oðlum!
Maksadýn Maksud'u görmek ise, iþte o benim." buyurup keramet gösterdiler. Mübarek
ellerini öptüm. Bir zaman misafiri oldum. Sohbetlerini dinledim. Maksud Dede bir gün bana
hak yola giriþini þöyle anlattý:

"Oðlum, bir zamanlar ben Tokat'ta sanatla uðraþan birisiydim. Bir Cuma günü halkýn güruh
güruh camiye koþtuklarýný gördüm. Bunun üzerine abdestimi alýp camiye gittim. Camide
nurani yüzlü birinin vaz ettiðini gördüm. Velilik hallerinden bahsediyordu. Dinledim, o
sýrada içimde derviþlik arzusu doðdu.Namazdan sonra o zatýn ellerini öpmek için yanýna
gittim ve talebesi olmak istediðimi bildirdim. Meðer o zat Molla Habib hazretleriymiþ. Bana
tebessüm edip müjde vererek; "Seni yetiþtirecek zat henüz irþada baþlamadý. Zamaný geldikte
inþaallah o zatý bulursun." dedi. Aradan on beþ sene geçti. Kalbim bir türlü huzur bulmadý.
Sonra Ýstanbul'a geldim. Ayasofya Camiine Cuma namazýna gittim. Bir zat vaz etmeye

baþladý. Benim halimi söyleyip izah etti. Sözleri kalbime iþledi. Yanýmda oturan birine; "Bu
zatýn kim olduðunu sordum. O da; "Sünbül Efendi derler. KocaMustafa PaþaDergahýnda
bulunur" dedi. Sonra yanýna gidip, elini öpmek istediðimde bana; "Maksud Dede! Tokat
þehrinde Molla Habib'in sana yaptýðý vasiyet hatýrýnda mýdýr?" diye sordu. Aklým gidip
hayretler içinde kaldým ve hemen ayaklarýný öpmek istedim. O zaman beni dergaha davet
edip, talebeliðe kabul ettiler ve nefsimin terbiye yollarýný öðretip beni yetiþtirdiler.
Elhamdülillah kýsa zamanda yükselmek nasib imiþ. Ýcazet, diploma verip Hayrabolu'ya hak
yolun bilgilerini öðretmek için gönderdiler. Hayrabolu'ya gelince, o þehrin camiine girip, iki
rekat tahiyyet-ül-mescid kýldým. Sonra orada bir delikanlýnýn oturduðunu gördüm. Genç
yanýma gelip selam verince, selamýný aldým. Bana; "Hoþ geldiniz Maksud Dede!" dedi. Ona;
"Beni nasýl bildin?" dediðimde; "Ben bir salih kiþinin oðluyum. Ýçime, gönlüme evliyalýk
yolunda olanlarla birlikte olmak arzusu düþtü. Birkaç Hak aþýðý kiþiyle seyahat yapmak
istedim. Birisi bana istihare namazýný kýlmamý söyledi. Ben de o gece kýldým. Sonra dualar
edip uyudum. Rüyamda nur yüzlü bir zat göründü ve bana; "Adým Sünbül Sinan Efendidir.
Falan gün camiye bir talebem gelir. Adý Maksud Dede'dir." buyurdu. Buraya geldiðimde de
siz çýka geldiniz." dedi.Ben de o genci yetiþtirip icazet, diploma verdim. O beldenin irþadýný
ona býrakýp Serez'e geldim ve buraya yerleþtim." buyurdu."

Maksud Dede'nin hak yolun bilgilerini öðrettiði devir, Sultan Süleyman Han devriydi.

1) Lemezat, Süleymaniye Kütüphanesi, No: 4536, v.149


text:
// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Javascript client implementation for ProtoRpc services.
 * @author joetyson@gmail.com (Joe Tyson)
 */

goog.provide('ProtoRpc.RPC');
goog.provide('ProtoRpc.RPC.State');
goog.provide('ProtoRpc.ServiceStub');

goog.require('ProtoRpc.EnumDescriptor');
goog.require('ProtoRpc.Message');

goog.require('goog.json');
goog.require('goog.net.XmlHttp');

/**
 * Represents a client side RPC.
 *
 * @export
 * @param {string} service_path Relative URI where service lives.
 * @param {string} method_name Name of method being invoked.
 * @param {Object} request The request.
 * @param {Function} success Function to call when RPC completes.
 * @param {Function=} error Function to call when RPC has an error.
 * @constructor
 */
ProtoRpc.RPC = function(service_path, method_name, request, success, error) {
  this.successCallback_ = success;
  this.errorCallback_ = error || null;

  this.request_ = request;

  var xhr = new goog.net.XmlHttp();

  /**
   * Try to open an XMLHttpRequest. If an error occurs, it's generally
   *  due to a permission issue.
   * @preserveTry
   */
  try {
    xhr.open('POST', service_path + '.' + method_name, true);
  } catch (err) {
    this.setState_(ProtoRpc.RPC.State.REQUEST_ERROR);
  }

  xhr.setRequestHeader('Content-Type', ProtoRpc.RPC.CONTENT_TYPE);

  /**
   * Send request or catch error.
   * @preserveTry
   */
  try {
    xhr.onreadystatechange = goog.bind(this.onReadyStateChange_, this);
    // TODO: What if serialization fails?
    xhr.send(goog.json.serialize(request));
  } catch (err) {
    this.setState_(ProtoRpc.RPC.State.REQUEST_ERROR);
  }

  this.xhr_ = xhr;
};

/**
 * Rpc States.
 * @enum {string}
 */
ProtoRpc.RPC.State = {
  OK: 'OK',
  RUNNING: 'RUNNING',
  REQUEST_ERROR: 'REQUEST_ERROR',
  SERVER_ERROR: 'SERVER_ERROR',
  NETWORK_ERROR: 'NETWORK_ERROR',
  APPLICATION_ERROR: 'APPLICATION_ERROR'
};

/**
 * Content-Type to use when making remote calls.
 * @const
 */
ProtoRpc.RPC.CONTENT_TYPE = 'application/json;charset=utf-8';

/**
 * Reference to an XMLHttpRequest object being used for RPC.
 * @type {XMLHttpRequest}
 * @private
 */
ProtoRpc.RPC.prototype.xhr_ = null;

/**
 * Functon to call when RPC completes successfully.
 * @type {Function}
 * @private
 */
ProtoRpc.RPC.prototype.successCallback_ = null;

/**
 * Function to call when an error happens.
 * @type {Function}
 * @private
 */
ProtoRpc.RPC.prototype.errorCallback_ = null;

/**
 * The Rpc's request message.
 * @type {Object}
 * @private
 */
ProtoRpc.RPC.prototype.request_ = null;

/**
 * The Rpc's response from the server.
 * @type {Object}
 * @private
 */
ProtoRpc.RPC.prototype.response_ = null;

/**
 * The current state of the Rpc.
 * @type {ProtoRpc.RPC.State}
 * @private
 */
ProtoRpc.RPC.prototype.state_ = ProtoRpc.RPC.State.RUNNING;

/**
 * The Rpc's Error Message, if error.
 * @type {string}
 * @private
 */
ProtoRpc.RPC.prototype.errorMessage_ = '';

/**
 * The Rpc's Error Name, if error.
 * @type {string}
 * @private
 */
ProtoRpc.RPC.prototype.errorName_ = '';

/**
 * Method invoked when RPC's xhr readyState is changed.
 * @private
 */
ProtoRpc.RPC.prototype.onReadyStateChange_ = function() {
  if (this.state_ != ProtoRpc.RPC.State.RUNNING) {
    return;
  }

  if (this.xhr_.readyState != goog.net.XmlHttp.ReadyState.COMPLETE) {
    return;
  }

  var status = this.xhr_.status;
  var statusText = this.xhr_.statusText;
  var content = this.xhr_.responseText;

  if (status >= 400) {
    /**
     * Try to parse RpcStatus from message.
     * @preserveTry
     */
    try {
      var rpcStatus = goog.json.parse(content);
      this.errorName_ = rpcStatus['error_name'] || null;
      this.errorMessage_ = rpcStatus['error_message'] || null;
      // TODO(joe): More robust RpcStatus handling...
      this.setState_(rpcStatus['state']);
    } catch (err) {
      this.errorName_ = 'Unknown Error.';
      this.setState_(ProtoRpc.RPC.State.REQUEST_ERROR);
    }
    return;
  }

  // TODO: validation
  // TODO: What if parsing fails?
  this.response_ = goog.json.parse(content);
  this.setState_(ProtoRpc.RPC.State.OK);
};

/**
 * Set the Rpc's state.
 * @param {ProtoRpc.RPC.State} state The Rpc State to set.
 * @private
 */
ProtoRpc.RPC.prototype.setState_ = function(state) {
  // TODO: Bitmask "allowed" transitions?
  this.state_ = state;
  if (state != ProtoRpc.RPC.State.OK) {
    this.callErrorHandler_();
    return;
  }
  this.callSuccessHandler_();
};

/** @private */
ProtoRpc.RPC.prototype.callErrorHandler_ = function() {
  // TODO: optional context/this?
  this.errorCallback_(this);
};

/** @private */
ProtoRpc.RPC.prototype.callSuccessHandler_ = function() {
  // TODO: optional context/this?
  this.successCallback_(this);
};

/**
 * Get the response from a completed RPC.
 * Throws {@code ProtoRpc.RpcError} if an error occured while
 *  running the RPC.
 * @return {Object} The response message from RPC.
 * @export
 */
ProtoRpc.RPC.prototype.getResponse = function() {
  if (this.state_ != ProtoRpc.RPC.State.OK) {
    throw this.getError();
  }
  return this.response_;
};

/**
 * Get the error from a failed RPC. This may be any of the appropriate
 * error types which can be associated with an RPC.
 * @export
 * @return {Error} The Error associated with RPC.
 */
ProtoRpc.RPC.prototype.getError = function() {
  // TODO: if not in error, do something.
  var error = new Error(this.errorName_);
  error.message = this.errorMessage_;
  error.type = this.state_;
  return error;
};

/**
 * Represents a Service Stub for a given service name, path, and set
 * of methods.
 * @param {string} path The path where the service accepts method calls.
 * @param {Array.<ProtoRpc.MethodDescriptor>} methods An array of method
 *     descriptors.
 * @constructor
 */
ProtoRpc.ServiceStub = function(path, methods) {
  this.path_ = path;
  var l = methods.length;
  for (var i = 0; i < l; i++) {
    this.addMethod_(methods[i]);
  }
};

/**
 * Add a method to the service.
 * @param {ProtoRpc.MethodDescriptor} method_descriptor The method descriptor.
 * @private
 */
ProtoRpc.ServiceStub.prototype.addMethod_ = function(method_descriptor) {
  var method_name = method_descriptor.name;
  this[method_name] = this.makeMethod_(method_name, this.path_);
};

/**
 * Helper to make methods.
 * @param {string} name Method name.
 * @param {string} path Service path.
 * @return {function({request: Object,
 *                    success: function(ProtoRpc.RPC),
 *                    error: function(ProtoRpc.RPC)})}
 * @private
 */
ProtoRpc.ServiceStub.prototype.makeMethod_ = function(name, path) {
  return function(kwargs) {
    var request = kwargs['request'] || {};
    var success = kwargs['success'];
    var error = kwargs['error'] || null;

    if (!goog.isFunction(success)) {
      throw Error('Success callback needs to be a function!');
    }

    if (error && !goog.isFunction(error)) {
      throw Error('Error callback needs to be a function!');
    }

    return new ProtoRpc.RPC(path, name, request, success, error);
  };
};

/**
 * Protojson Specific Serializer.
 * @constructor
 */
ProtoRpc.Serializer = function() {
  // TODO: Have option for using key's as field number vs. field name.
};

ProtoRpc.Serializer.prototype.serialize = function(message) {
  var descriptor = message.getDescriptor();
  var fields = descriptor['fields'];

  var obj = {};

  for (var i = 0; i < fields.length; i++) {
    var field = fields[i];

    if (message.has(field)) {
      if (field['label'] == 'REPEATED') {
        var arr = [];
        obj[field.toString()] = arr;

        var repeatedValues = message.get(field);
        for (var j = 0; j < repeatedValues.length; j++) {
          arr.push(this.serialize_(field, repeatedValues[j]));
        }
      } else {
        obj[field.toString()] = message.get(field);
      }
    } else {
      // Default values
    }
  }
};

/**
 * @param {ProtoRpc.FieldDescriptor} field Field Descriptor of value.
 * @param {*} value Field's unserialized value.
 */
ProtoRpc.Serializer.prototype.serialize_ = function(field, value) {
  switch (field['variant']) {
    case ProtoRpc.Variant.MESSAGE:
      return this.serializeMessage_(value);
      break;
    case ProtoRpc.Variant.ENUM:
      return this.serializeEnum_(value);
      break;
    default:
      return value;
  }
};


text:
// Copyright 2011 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.apache.tapestry5.services.pageload;

import org.apache.tapestry5.ioc.services.ThreadLocale;

/**
 * Determines the {@link ComponentResourceSelector} for the current request. This is often based on cookies, query
 * parameters, or other details available in the {@link org.apache.tapestry5.http.services.Request}. The default implementation simply wraps the
 * {@linkplain ThreadLocale current locale} as a ComponentResourceSelector. A custom implementation may
 * {@linkplain ComponentResourceSelector#withAxis(Class, Object) add additional axes} to the selector.
 *
 * @since 5.3
 */
public interface ComponentRequestSelectorAnalyzer
{
    /**
     * Constructs a selector for locating or loading pages in the current request.
     */
    ComponentResourceSelector buildSelectorForRequest();
}


text:
require 'casting'

def log(message)
  puts('Transaction log: ' + message)
end

# What it is
Account = Struct.new(:name, :balance)
class Account
  include Casting::Client
  delegate_missing_methods

  alias_method :to_s, :name
end

checking = Account.new(':checking:', 500)
savings = Account.new('~savings~', 2)

# What it does
Transfer = Struct.new(:amount, :source, :destination)
class Transfer
  def execute
    Casting.delegating(source => Source) do
      source.transfer(amount, destination)
    end
  end

  module Source
    def transfer(amount, destination)
      log("#{self} transferring #{amount} to #{destination}")

      Funding.new(self,       -amount).enter &&
      Funding.new(destination, amount).enter

      log("#{self} successfully transferred #{amount} to #{destination}")
    rescue Funding::InsufficientFunds
      log("#{self} unable to transfer #{amount} to #{destination}")
    end
  end
end

Funding = Struct.new(:account, :amount)
class Funding
  def enter
    Casting.delegating(account => Sink) do
      account.add_funds(amount)
    end
  end

  class InsufficientFunds < StandardError; end

  module Sink

    def add_funds(amount)
      log_total
      log("Adding #{amount} to #{self}")

      self.balance += amount

      if self.balance > 0
        log("Funded #{self} with #{amount}")
      else
        self.balance -= amount
        log("#{self} has insufficient funds for #{amount}")
        raise Funding::InsufficientFunds.new
      end
    ensure
      log_total
    end

    def log_total
      log("#{self} ==total== is #{balance}")
    end
  end
end

puts "Transferring..."
Transfer.new(30, checking, savings).execute
Transfer.new(50, savings, checking).execute


text:
#include <luabind/luabind.hpp>
#include <string>

static const std::string obj_name(const luabind::object& o)
{
    lua_State* L = o.interpreter();
    std::string name;

    o.push(L);
    luabind::detail::object_rep* obj = luabind::detail::get_instance(L, -1);
    if (!obj)
    {
        name = lua_typename(L, lua_type(L, -1));
        lua_pop(L, 1);
        return name;
    }

    lua_pop(L, 1);
    name = obj->crep()->name();
    return name;
}

static const var toVar(lua_State* L, int index)
{
    var v;
    luabind::object obj(luabind::from_stack(L,index));

	switch(luabind::type(obj))
	{
		case LUA_TSTRING:
			v = luabind::object_cast<String>(obj);
            return v;

		case LUA_TNUMBER:
			v = luabind::object_cast<double>(obj);
            return v;
    }

    return v;
}

static void fromVar (lua_State* L, var const& v)
{
	if(v.isString())
	{
		lua_pushstring(L, v.toString().toUTF8());
        return;
    }
	else if(v.isInt())
	{
        lua_pushnumber(L, (int)v);
        return;
    }
	else if(v.isDouble())
	{
        lua_pushnumber(L, (double)v);
        return;
    }
    lua_pushnil(L);
}

namespace luabind
{
    /* var converter */
	template <> struct default_converter<var> : native_converter_base<var>
	{
		static int compute_score(lua_State* L, int index)
		{
			lua_type(L, index);
			return 0;
		}

		var from(lua_State* L, int index)
		{
			return toVar(L,index);
		}

		void to(lua_State* L, var const& v)
		{
			fromVar (L,v);
		}
	};

	template <> struct default_converter<var const&> : default_converter<var>
	{};

    /* String converter */
	template <> struct default_converter<String> : native_converter_base<String>
	{
		static int compute_score(lua_State* L, int index)
		{
			object obj(luabind::from_stack(L,index));
			std::string name = obj_name(obj);

			if(name == "String")
			{
				return (0);
			}
			return (lua_type(L, index) == LUA_TSTRING) ? 0 : -1;
		}

		String from(lua_State* L, int index)
		{
			object obj(luabind::from_stack(L,index));
			std::string name = obj_name(obj);

			if(name == "String")
			{
                String* wp = object_cast<String*>(obj);
                return String(*wp);
            }
			return String(lua_tostring(L, index));
		}

		void to(lua_State* L, String const &value)
		{
			lua_pushlstring(L, value.toUTF8(), value.length());
		}
	};

	template <> struct default_converter<String const&> : default_converter<String>
	{
	};

    /* StringRef converter */
    template <> struct default_converter<StringRef> : native_converter_base<StringRef>
	{
		static int compute_score(lua_State* L, int index)
		{
			object obj(luabind::from_stack(L,index));
			std::string name = obj_name(obj);

			if(name == "StringRef")
			{
				return (0);
			}
			return (lua_type(L, index) == LUA_TSTRING) ? 0 : -1;
		}

		StringRef from(lua_State* L, int index)
		{
			object obj(luabind::from_stack(L,index));
			std::string name = obj_name(obj);

			if(name == "StringRef")
			{
                StringRef* wp = object_cast<StringRef*>(obj);
                return StringRef(*wp);
            }
			return StringRef(lua_tostring(L, index));
		}

		void to(lua_State* L, StringRef const &value)
		{
			lua_pushlstring(L, value, value.length());
		}
	};

	template <> struct default_converter<StringRef const&> : default_converter<StringRef>
	{
	};

    /* Identifier converter */
	template <> struct default_converter<Identifier> : native_converter_base<Identifier>
	{
		static int compute_score(lua_State* L, int index)
		{
			object obj(luabind::from_stack(L,index));
			std::string name = obj_name(obj);

			if(name == "Identifier")
			{
				return (0);
			}
			return (lua_type(L, index) == LUA_TSTRING) ? 0 : -1;
		}

		Identifier from(lua_State* L, int index)
		{
			object obj(luabind::from_stack(L,index));
			std::string name = obj_name(obj);

			if(name == "Identifier")
			{
                Identifier* wp = object_cast<Identifier*>(obj);
                return Identifier(*wp);
            }
			return Identifier(lua_tostring(L, index));
		}

		void to(lua_State* L, Identifier const &value)
		{
			lua_pushlstring(L, value.toString().toUTF8(), strlen(value.toString().toUTF8()));
		}
	};

	template <> struct default_converter<Identifier const&> : default_converter<Identifier>
	{
	};
}


text:
<?php
header('Content-Type: text/plain');
include 'common.php';

$nodeName = $_GET["node"];
$instanceId = $_GET["instance"];
$tierNodeName = $_GET["tierNode"];
$tierInstanceId = $_GET["tierInstance"];
$operation = $_GET["operation"];
$envLog = file_get_contents('php://input');

$nodeLogPath = "$logPath/$nodeName";
if (!file_exists($nodeLogPath)) {
  mkdir($nodeLogPath, 0700, true);
}

$instanceIdx = getIntanceIdx($nodeName, $instanceId, $registryPath);
$tierInstanceIdx = getIntanceIdx($tierNodeName, $tierInstanceId, $registryPath);

$operationIdx = getOperationIdx($opLogPath);
file_put_contents("$opLogPath/$operationIdx.env", "$envLog");

$instanceLogFile = "$nodeLogPath/$instanceIdx";
file_put_contents($instanceLogFile, "#$operationIdx - $operation/$tierNodeName/$tierInstanceIdx/$tierInstanceId\n", FILE_APPEND | LOCK_EX);
file_put_contents("$allLogFile", "$operationIdx;" . date("Y-m-d H:i:s").";$nodeName;$instanceIdx;$instanceId;$operation;$tierNodeName;$tierInstanceIdx;$tierInstanceId\n", FILE_APPEND | LOCK_EX);
?>


text:
import { Component, Input } from '@angular/core';

import { Video } from './../entities/video';

@Component({
  selector: 'app-videos-sidebar',
  templateUrl: 'videos-sidebar.component.html'
})

export class VideosSidebarComponent {
  @Input() public currentVideo: Video;
  @Input() public videos: Array<Video>;
}


text:
<?php

	namespace Uneak\AssetsBundle\Process\Npm;

	use Symfony\Component\EventDispatcher\EventDispatcherInterface;
	use Symfony\Component\Process\ProcessBuilder;
	use Uneak\AssetsBundle\Event\NpmCommandEvent;
	use Uneak\AssetsBundle\Event\NpmEvent;
	use Uneak\AssetsBundle\Event\NpmEvents;
	use Uneak\AssetsBundle\Event\NpmProcessEvent;
	use Uneak\AssetsBundle\Event\NpmResultEvent;
	use Uneak\AssetsBundle\Exception\CommandException;
	use Uneak\AssetsBundle\Npm\NpmPackageInterface;

	class NpmProcess {

		/**
		 * @var EventDispatcherInterface
		 */
		protected $eventDispatcher;
		/**
		 * @var string
		 */
		private $bin;

		public function __construct(EventDispatcherInterface $eventDispatcher, array $config) {
			$this->eventDispatcher = $eventDispatcher;
			$this->bin = $config['bin'];

		}

		/**
		 * @return string
		 */
		public function getBin() {
			return $this->bin;
		}

		public function install(NpmPackageInterface $npmPackage, $callback = null) {
			$event = new NpmEvent($npmPackage);
			$this->eventDispatcher->dispatch(NpmEvents::PRE_INSTALL, $event);
			$npmPackage = $event->getNpmPackage();

			$result = $this->process($npmPackage, array('install', '--json'), $callback);

			$event = new NpmResultEvent($result);
			$this->eventDispatcher->dispatch(NpmEvents::POST_INSTALL, $event);
			$result = $event->getNpmResult();

			return $result->getProcess()->getExitCode();
		}

		/**
		 * @param NpmPackageInterface $npmPackage
		 * @param array               $commands
		 * @param null                $callback
		 *
		 * @return NpmResult
		 */
		private function process(NpmPackageInterface $npmPackage, $commands, $callback = null) {

			$event = new NpmCommandEvent($npmPackage, $commands);
			$this->eventDispatcher->dispatch(NpmEvents::PRE_EXEC, $event);
			$npmPackage = $event->getNpmPackage();
			$commands = $event->getCommands();

			$processBuilder = new ProcessBuilder();
			$processBuilder->setWorkingDirectory($npmPackage->getPath());
			$processBuilder->setTimeout(600);
			$processBuilder->add($this->getBin());
			$processBuilder->add("--prefix \"" . $npmPackage->getModulesPath() . "\"");

			foreach ($commands as $command) {
				$processBuilder->add($command);
			}

			$process = $processBuilder->getProcess();
			$process->run($callback);

			if (!$process->isSuccessful()) {
				throw new CommandException($process->getCommandLine(), trim($process->getErrorOutput()));
			}

			$event = new NpmProcessEvent($npmPackage, $commands, $process);
			$this->eventDispatcher->dispatch(NpmEvents::POST_EXEC, $event);
			$commands = $event->getCommands();
			$npmPackage = $event->getNpmPackage();
			$process = $event->getProcess();

			return new NpmResult($process, $npmPackage, $commands);
		}

	}


text:
<?php

/**
 * This is the model class for table "kegiatan".
 *
 * The followings are the available columns in table 'kegiatan':
 * @property integer $id
 * @property string $kode_kegiatan
 * @property integer $id_layanan
 * @property string $nama_kegiatan
 * @property integer $target
 * @property integer $volume
 * @property integer $harga_satuan
 * @property string $satuan
 * @property string $sumber_dana
 * @property string $penanggung_jawab
 * @property integer $id_rekaman
 * @property string $versi
 * @property integer $status
 * @property integer $bulan
 * @property integer $recoverable
 */
class Kegiatan extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Kegiatan the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'kegiatan';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('kode_kegiatan, id_layanan, nama_kegiatan, target, volume, harga_satuan, satuan, sumber_dana, penanggung_jawab, id_rekaman, versi', 'required'),
			array('id_layanan, target, volume, harga_satuan, id_rekaman, status, bulan, recoverable', 'numerical', 'integerOnly'=>true),
			array('kode_kegiatan', 'length', 'max'=>10),
			array('nama_kegiatan', 'length', 'max'=>200),
			array('satuan, sumber_dana, versi', 'length', 'max'=>20),
			array('penanggung_jawab', 'length', 'max'=>70),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, kode_kegiatan, id_layanan, nama_kegiatan, target, volume, harga_satuan, satuan, sumber_dana, penanggung_jawab, id_rekaman, versi, status, bulan, recoverable', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'realisasi'=>array(self::HAS_MANY,'Realisasi','id_kegiatan'),
			'layanan'=>array(self::BELONGS_TO,'Layanan','id_layanan'),
			'SumberDana'=>array(self::BELONGS_TO,'SumberDana','sumber_dana'),
			'PenanggungJawab'=>array(self::BELONGS_TO,'PenanggungJawab','penanggung_jawab'),
			'Satuan'=>array(self::BELONGS_TO,'Satuan','satuan'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'kode_kegiatan' => 'Kode Kegiatan',
			'id_layanan' => 'Id Layanan',
			'nama_kegiatan' => 'Nama Kegiatan',
			'target' => 'Target',
			'volume' => 'Volume',
			'harga_satuan' => 'Harga Satuan',
			'satuan' => 'Satuan',
			'sumber_dana' => 'Sumber Dana',
			'penanggung_jawab' => 'Penanggung Jawab',
			'id_rekaman' => 'Id Rekaman',
			'versi' => 'Versi',
			'status' => 'Status',
			'bulan' => 'Bulan',
			'recoverable' => 'Recoverable',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('kode_kegiatan',$this->kode_kegiatan,true);
		$criteria->compare('id_layanan',$this->id_layanan);
		$criteria->compare('nama_kegiatan',$this->nama_kegiatan,true);
		$criteria->compare('target',$this->target);
		$criteria->compare('volume',$this->volume);
		$criteria->compare('harga_satuan',$this->harga_satuan);
		$criteria->compare('satuan',$this->satuan,true);
		$criteria->compare('sumber_dana',$this->sumber_dana,true);
		$criteria->compare('penanggung_jawab',$this->penanggung_jawab,true);
		$criteria->compare('id_rekaman',$this->id_rekaman);
		$criteria->compare('versi',$this->versi,true);
		$criteria->compare('status',$this->status);
		$criteria->compare('bulan',$this->bulan);
		$criteria->compare('recoverable',$this->recoverable);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}


text:
package us.kbase.kidl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Class represents group of modules with the same service name
 * (first optional part of module name before colon). If module
 * name defined by one keyword without colon then service name
 * is supposed to be equal to module name.
 */
public class KbService {
	private String name;
	private List<KbModule> modules;

	public KbService(String name) {
		this.name = name;
	}

	public void loadFromList(List<?> data) throws KidlParseException {
		List<KbModule> modules = new ArrayList<KbModule>();
		for (Object item : data) {
			KbModule mod = new KbModule();
			mod.loadFromList((List<?>)item);
			modules.add(mod);
		}
		this.modules = Collections.unmodifiableList(modules);
	}

	public static List<KbService> loadFromMap(Map<?,?> data) throws KidlParseException {
		List<KbService> ret = new ArrayList<KbService>();
		for (Map.Entry<?,?> entry : data.entrySet()) {
			KbService srv = new KbService("" + entry.getKey());
			srv.loadFromList((List<?>)entry.getValue());
			ret.add(srv);
		}
		return ret;
	}

	public String getName() {
		return name;
	}

	public List<KbModule> getModules() {
		return modules;
	}
}


text:
CREATE TABLE PERSISTENT_LOGINS (
    USERNAME  VARCHAR(64) NOT NULL,
    SERIES    VARCHAR(64) NOT NULL PRIMARY KEY,
    TOKEN     VARCHAR(64) NOT NULL,
    LAST_USED TIMESTAMP   NOT NULL
);


text:
namespace {

// This variable must be able to be found and parsed by the upload script.
const int kMinimumSupportedXwalkVersion[] = {29, 0, 1545, 0};

}  // namespace

const int kMinimumSupportedXwalkBuildNo = kMinimumSupportedXwalkVersion[2];

std::string GetMinimumSupportedXwalkVersion() {
  return base::StringPrintf(
      "%d.%d.%d.%d",
      kMinimumSupportedXwalkVersion[0],
      kMinimumSupportedXwalkVersion[1],
      kMinimumSupportedXwalkVersion[2],
      kMinimumSupportedXwalkVersion[3]);
}


text:
import collections
import os
import subprocess
from mlperf_logging.mllog import constants as mlperf_constants

os.environ['PYTHONPATH'] += os.path.join(os.getcwd(),'minigo')
from minigo.ml_perf.logger import log_event, mpiwrapper

def all_reduce(v):
    return mpiwrapper.allreduce(v)

def mlperf_submission_log(benchmark):

    num_nodes = os.environ.get('SLURM_JOB_NUM_NODES', 1)

    log_event(
        key=mlperf_constants.SUBMISSION_BENCHMARK,
        value=benchmark,
        )

    log_event(
        key=mlperf_constants.SUBMISSION_ORG,
        value='NVIDIA')

    log_event(
        key=mlperf_constants.SUBMISSION_DIVISION,
        value='closed')

    log_event(
        key=mlperf_constants.SUBMISSION_STATUS,
        value='onprem')

    log_event(
        key=mlperf_constants.SUBMISSION_PLATFORM,
        value='{}xSUBMISSION_PLATFORM_PLACEHOLDER'.format(num_nodes))


text:
import {
  getFormattedDuration,
  getFormattedTimestamp,
} from './timestamp_formatters';

describe('Test timestamp tools', () => {
  const start = '2022-09-06T07:13:12.435231Z';
  const end = '2022-09-06T07:13:16.893998Z';

  test('if duration formatting is correct', () => {
    expect(getFormattedDuration(start, end)).toBe('00:00:04');
  });

  test('if calculating duration is skipped appropriately', () => {
    expect(getFormattedDuration(end, start)).toBe('');
    expect(getFormattedDuration(start, '')).toBe('');
    expect(getFormattedDuration('', end)).toBe('');
  });

  test('if timestamp formatting skips empty strings', () => {
    expect(getFormattedTimestamp('')).toBe('');
  });
});


text:
"Introduction to IndexedDB"
===============================

* [Slides](https://github.com/fragphace/talk_introduction_to_indexed_db/blob/master/idb.pdf?raw=true)
* [Demo application](http://fragphace.github.io/talk_introduction_to_indexed_db/)
* [Video](http://www.youtube.com/watch?v=wOv_R5XyTgA&list=PLB422C495A0971BEE)

## Build

```
$ sudo apt-get install texlive-latex-base latex-beamer texlive-xetex
$ xelatex idb.tex
```


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>A Tribute Page - Project @ FreeCodeCamp</title>
    <link href="../css/bootstrap.min.css" rel="stylesheet">

Barack Obama

The 44th President of the United States

President Obama smiles while speaking on the phone in the Oval Office (Source: White House)

Here's a time line of President Barack Obama's life:

1961 - Barack Obama was born in Hawaii on August 4, 1961. His father was African and his mother was American.

1967 - When Barack was 6 years old, his mother moved him to Indonesia where she worked as an English teacher. They were surrounded by the poor, and they had no stable electricity.

1971 - At the age of 10, Barack's mother sent him back to Hawaii to live with his grandparents. He attended a prep school, and he was the only black child there."

1979 - Barack attended Occidental College in Los Angeles, but later moved to Columbia University in New York.

1982 - He begins his career as a community planner

1990 - Barack Obama became the first African-American president of the Harvard Law Review.

1991 - Barack Obama graduated from Harvard in 1991. He moved back to Chicago.

1992 - Barack Obama married his girlfriend, Michelle, in October.

1996 - Barack tried out for the Illinois state senate. He won the election.

1999 - Barack Obama ran for congress, but he was beat 2 to 1 by Representative Bobby Rush.

2003 - Mr. Obama ran for the US Senate, and he won the election.

2007 - Barack Obama announced that he intended to run for President of the United States.

June 2008 - The Democratic preliminary election was held, and Barack Obama beat Senator Hilary Clinton for the nomination.

November 2008 - In 2008, Barack Obama won the presidential election. He became the first African-American president, and he won his second term in 2012. President Obama is an inspiration for the story of his life as a normal kid who grew up to be president.

                    "I'm here tonight, not as a Republican, not as a Democrat, but as an optimistic American who understands that we must come together behind the one man who can lead the way forward in these challenging times: my president, our president, Barack Obama!"

                    Charlie Crist

If you have time, you should read more about President Barack Obama on his Wikipedia Entry


text:
package centreon::common::adic::tape::snmp::mode::hardware;

use base qw(centreon::plugins::templates::hardware);

use strict;
use warnings;

sub set_system {
    my ($self, %options) = @_;

    $self->{regexp_threshold_overload_check_section_option} = '^(global|physicaldrive|subsystem)$';

    $self->{cb_hook2} = 'snmp_execute';

    $self->{thresholds} = {
        default => [
            ['good', 'OK'],
            ['failed', 'CRITICAL'],
            ['degraded', 'WARNING'],
            ['warning', 'WARNING'],
            ['informational', 'OK'],
            ['unknown', 'UNKNOWN'],
            ['invalid', 'CRITICAL'],
        ],
    };

    $self->{components_path} = 'centreon::common::adic::tape::snmp::mode::components';
    $self->{components_module} = ['global', 'physicaldrive', 'subsystem'];
}

sub snmp_execute {
    my ($self, %options) = @_;

    $self->{snmp} = $options{snmp};
    $self->{results} = $self->{snmp}->get_multiple_table(oids => $self->{request});
}

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options, no_performance => 1, no_absent => 1);
    bless $self, $class;

    $self->{version} = '1.0';
    $options{options}->add_options(arguments =>
                                {
                                });

    return $self;
}

1;

__END__

=head1 MODE

Check Hardware.

=over 8

=item B<--component>

Which component to check (Default: '.*').
Can be: 'global', 'physicaldrive', 'subsystem'.

=item B<--filter>

Exclude some parts (comma seperated list) (Example: --filter=subsystem)
Can also exclude specific instance: --filter=physicaldrive,1

=item B<--no-component>

Return an error if no compenents are checked.
If total (with skipped) is 0. (Default: 'critical' returns).

=item B<--threshold-overload>

Set to overload default threshold values (syntax: section,[instance,]status,regexp)
It used before default thresholds (order stays).
Example: --threshold-overload='physicaldrive,OK,invalid'

=back

=cut


text:
-- MySQL dump 10.13  Distrib 5.5.37, for Linux (x86_64)
--
-- Host: localhost    Database: evanonli_furyspace
-- ------------------------------------------------------
-- Server version	5.5.37-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `codes`
--

DROP TABLE IF EXISTS `codes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `codes` (
  `code` varchar(16) NOT NULL,
  PRIMARY KEY (`code`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `games`
--

DROP TABLE IF EXISTS `games`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `games` (
  `gid` int(11) NOT NULL,
  `game` longtext NOT NULL,
  `version` varchar(16) DEFAULT NULL,
  PRIMARY KEY (`gid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `history`
--

DROP TABLE IF EXISTS `history`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `history` (
  `gid` int(11) NOT NULL,
  `turn` int(11) NOT NULL,
  `version` varchar(16) DEFAULT NULL,
  `game` longtext NOT NULL,
  PRIMARY KEY (`gid`,`turn`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `plays`
--

DROP TABLE IF EXISTS `plays`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `plays` (
  `email` varchar(64) NOT NULL,
  `gid` int(11) NOT NULL,
  KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `users`
--

DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `users` (
  `email` varchar(64) NOT NULL,
  `password` varchar(64) NOT NULL,
  PRIMARY KEY (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed


text:
import os,sys
sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python')
import BGF
import metrics

def refs(n,g):
	nts = []
	for p in g.prods:
		for nt in p.expr.wrapped.getXml().findall('.//nonterminal'):
			if nt.text == n:
				nts.append(p.nt)
	return nts

def chain(n,g):
	ps = g.getProdsOfN(n)
	if len(ps)>1:
		return None
	if ps[0].expr.wrapped.__class__.__name__ == 'Nonterminal':
		return ps[0].expr.wrapped.data
	print '--->', ps[0].expr.wrapped.__class__.__name__
	return None

if __name__ == "__main__":
	if len(sys.argv) != 3:
		print 'This generator proposes to remove all chain productions and inline all once-used nonterminal symbols.'
		print 'Usage:'
		print '      '+sys.argv[0]+' <bgf-input> <xbgf-output>'
		sys.exit(1)
	bgf = BGF.Grammar()
	bgf.parse(sys.argv[1])
	xbgf = open(sys.argv[2],'w')
	xbgf.write('<?xml version="1.0" encoding="UTF-8"?><xbgf:sequence xmlns:xbgf="http://planet-sl.org/xbgf" xmlns:bgf="http://planet-sl.org/bgf">\n')
	chains = {}
	nts = metrics.var(bgf)
	for n in nts:
		ps = bgf.getProdsOfN(n)
		if len(ps) == 1 and ps[0].expr.wrapped.__class__.__name__ == 'Nonterminal':
			chains[ps[0].expr.wrapped.data] = n
	refers1 = {}
	refers2 = {}
	for p in bgf.prods:
		for n in p.expr.wrapped.getXml().findall('.//nonterminal'):
			if n.text not in refers1.keys():
				refers1[n.text] = [p.nt]
			else:
				refers1[n.text].append(p.nt)
			if p.nt not in refers2.keys():
				refers2[p.nt] = [n.text]
			else:
				refers2[p.nt].append(n.text)
	for n in nts:
		c = refs(n,bgf)
		if len(c)==0:
			if n in bgf.roots:
				print 'Nonterminal',n,'confirmed as root.'
			else:
				print 'Unused non-root found:',n
		elif len(c)==1:
			d = len(bgf.getProdsOfN(n))
			if d==1:
				if n in chains.keys():
					print 'Nonterminal',n,'is advised to be unchained.'
					xbgf.write('<xbgf:unchain><bgf:production><nonterminal>'+chains[n]+'</nonterminal><bgf:expression><nonterminal>'+n+'</nonterminal></bgf:expression></bgf:production></xbgf:unchain>\n')
				elif n in bgf.roots:
					print 'We never inline the root.'
				elif n in refers1.keys() and n in refers2.keys() and refers1[n]==refers2[n]:
					print 'Nonterminal',n,'is co-recursive, cannot be inlined with XBGF.'
				else:
					print 'Nonterminal',n,'is advised to be inlined.'
					#if n in refers1.keys():
					#	print 'REFERS(1):',refers1[n]
					#if n in refers2.keys():
					#	print 'REFERS(2):',refers2[n]
					xbgf.write('<xbgf:inline>'+n+'</xbgf:inline>\n')
			else:
				pass
				#print 'Nonterminal',n,'can be inlined with',d,'productions.'
		else:
			pass
			#print 'Nonterminal',n,'is used',len(c),'times by',c
	xbgf.write('</xbgf:sequence>')
	xbgf.close()
	sys.exit(0)


text:
<?php

return [
    'Create Task'                   => 'Crear Tarea',
    'Create New Post'               => 'Crear Nueva Publicación',
    'Currently in room'             => 'Actualmente en habitación',
    'write your message here'       => 'escribe tu mensaje aquí',
    'Upload Files'                  => 'Cargar Archivos',
    'Project has been made public'  => 'Proyecto hecho público',
    'Project has been made private' => 'Proyecto hecho privado',
    'Office has been made public'   => 'Oficina hecha pública',
    'Office has been made private'  => 'Oficina hecha privada',
    'Team has been made public'     => 'Equipo hecho público',
    'Team has been made private'    => 'Equipo hecho privado',
    'Add New Step'                  => 'Agregar Nuevo Paso',
    'Save'                          => 'Salvar',
    'Tools'                         => 'Herramientas',
    'Tags'                          => 'Etiquetas',
    'Status'                        => 'Estado',
    'Tasks'                         => 'Tareas',
    'Discussions'                   => 'Discusiones',
    'Messages'                      => 'Mensajes',
    'Events'                        => 'Eventos',
    'Files'                         => 'Archivos',
    'Activities'                    => 'Actividades',
    'Filters'                       => 'Filtros',
    'Select a User'                 => 'Seleccionar un Usuario',
    'Select a Tag'                  => 'Seleccionar una Etiqueta',
];


text:
from unittest.mock import Mock

import pytest

from airflow.models import DAG
from airflow.models.baseoperator import BaseOperator
from airflow.ti_deps.dep_context import DepContext
from airflow.ti_deps.deps.prev_dagrun_dep import PrevDagrunDep
from airflow.utils.state import State
from airflow.utils.timezone import convert_to_utc, datetime
from airflow.utils.types import DagRunType
from tests.test_utils.db import clear_db_runs

class TestPrevDagrunDep:
    def teardown_method(self):
        clear_db_runs()

    def test_first_task_run_of_new_task(self):
        """
        The first task run of a new task in an old DAG should pass if the task has
        ignore_first_depends_on_past set to True.
        """
        dag = DAG('test_dag')
        old_task = BaseOperator(
            task_id='test_task',
            dag=dag,
            depends_on_past=True,
            start_date=convert_to_utc(datetime(2016, 1, 1)),
            wait_for_downstream=False,
        )
        # Old DAG run will include only TaskInstance of old_task
        dag.create_dagrun(
            run_id='old_run',
            state=State.SUCCESS,
            execution_date=old_task.start_date,
            run_type=DagRunType.SCHEDULED,
        )

        new_task = BaseOperator(
            task_id='new_task',
            dag=dag,
            depends_on_past=True,
            ignore_first_depends_on_past=True,
            start_date=old_task.start_date,
        )

        # New DAG run will include 1st TaskInstance of new_task
        dr = dag.create_dagrun(
            run_id='new_run',
            state=State.RUNNING,
            execution_date=convert_to_utc(datetime(2016, 1, 2)),
            run_type=DagRunType.SCHEDULED,
        )

        ti = dr.get_task_instance(new_task.task_id)
        ti.task = new_task

        # this is important, we need to assert there is no previous_ti of this ti
        assert ti.previous_ti is None

        dep_context = DepContext(ignore_depends_on_past=False)
        assert PrevDagrunDep().is_met(ti=ti, dep_context=dep_context)

@pytest.mark.parametrize(
    "depends_on_past, wait_for_downstream, prev_ti, context_ignore_depends_on_past, dep_met",
    [
        # If the task does not set depends_on_past, the previous dagrun should
        # be ignored, even though previous_ti would otherwise fail the dep.
        pytest.param(
            False,
            False,  # wait_for_downstream=True overrides depends_on_past=False.
            Mock(
                state=State.NONE,
                **{"are_dependents_done.return_value": False},
            ),
            False,
            True,
            id="not_depends_on_past",
        ),
        # If the context overrides depends_on_past, the dep should be met even
        # though there is no previous_ti which would normally fail the dep.
        pytest.param(
            True,
            False,
            Mock(
                state=State.SUCCESS,
                **{"are_dependents_done.return_value": True},
            ),
            True,
            True,
            id="context_ignore_depends_on_past",
        ),
        # The first task run should pass since it has no previous dagrun.
        pytest.param(True, False, None, False, True, id="first_task_run"),
        # Previous TI did not complete execution. This dep should fail.
        pytest.param(
            True,
            False,
            Mock(
                state=State.NONE,
                **{"are_dependents_done.return_value": True},
            ),
            False,
            False,
            id="prev_ti_bad_state",
        ),
        # Previous TI specified to wait for the downstream tasks of the previous
        # dagrun. It should fail this dep if the previous TI's downstream TIs
        # are not done.
        pytest.param(
            True,
            True,
            Mock(
                state=State.SUCCESS,
                **{"are_dependents_done.return_value": False},
            ),
            False,
            False,
            id="failed_wait_for_downstream",
        ),
        # All the conditions for the dep are met.
        pytest.param(
            True,
            True,
            Mock(
                state=State.SUCCESS,
                **{"are_dependents_done.return_value": True},
            ),
            False,
            True,
            id="all_met",
        ),
    ],
)
def test_dagrun_dep(
    depends_on_past,
    wait_for_downstream,
    prev_ti,
    context_ignore_depends_on_past,
    dep_met,
):
    task = BaseOperator(
        task_id="test_task",
        dag=DAG("test_dag"),
        depends_on_past=depends_on_past,
        start_date=datetime(2016, 1, 1),
        wait_for_downstream=wait_for_downstream,
    )
    if prev_ti:
        prev_dagrun = Mock(
            execution_date=datetime(2016, 1, 2),
            **{"get_task_instance.return_value": prev_ti},
        )
    else:
        prev_dagrun = None
    dagrun = Mock(
        **{
            "get_previous_scheduled_dagrun.return_value": prev_dagrun,
            "get_previous_dagrun.return_value": prev_dagrun,
        },
    )
    ti = Mock(task=task, **{"get_dagrun.return_value": dagrun})
    dep_context = DepContext(ignore_depends_on_past=context_ignore_depends_on_past)

    assert PrevDagrunDep().is_met(ti=ti, dep_context=dep_context) == dep_met


text:
import { expect } from 'chai';
import { getHighlightEditStyle } from '../src/utils/index.native-and-web';

describe('index.native-and-web', () => {
  describe('getHighlightEditStyle', () => {
    const color = '#ffffff';
    it('isEditable, isValid, !isTypingHighlight should contain passed color', () => expect(
      getHighlightEditStyle(true, true, false, color).replace(/\s/g, '')
    ).to.equal(`
      border-bottom-color: ${color};
      border-bottom-width: 1px;
      border-left-width: 0;
      border-right-width: 0;
      border-top-width: 0;
      border-style: solid;
    `.replace(/\s/g, '')));
  });
});


text:
<?php

use Auryn\ReflectionPool;

class ReflectionPoolTest extends PHPUnit_Framework_TestCase {

    /**
     * @covers Auryn\ReflectionPool::getClass
     * @covers Auryn\ReflectionPool::storeInCache
     */
    public function testGetClassRetrievesNewReflectionIfNotCached() {
        $rc   = new ReflectionPool;
        $refl = $rc->getClass('Test');
        $this->assertInstanceOf('ReflectionClass', $refl);
        return $rc;
    }

    /**
     * @depends testGetClassRetrievesNewReflectionIfNotCached
     * @covers Auryn\ReflectionPool::getClass
     * @covers Auryn\ReflectionPool::fetchFromCache
     * @covers Auryn\ReflectionPool::storeInCache
     */
    public function testGetClassRetrievesCachedReflectionIfAvailable($rc) {
        $cached = $rc->getClass('Test');
        $new = new ReflectionPool;

        $this->assertFalse($new === $cached);
        $this->assertTrue($rc->getClass('Test') === $cached);
        return $rc;
    }

    /**
     * @depends testGetClassRetrievesCachedReflectionIfAvailable
     * @covers Auryn\ReflectionPool::getConstructor
     */
    public function testGetConstructorRetrievesNewReflectionIfNotCached($rc) {
        $ctor = $rc->getConstructor('Test');
        $this->assertInstanceOf('ReflectionMethod', $ctor);
        return $rc;
    }

    /**
     * @depends testGetConstructorRetrievesNewReflectionIfNotCached
     * @covers Auryn\ReflectionPool::getConstructor
     */
    public function testGetConstructorCachesReflectionIfAvailable($rc) {
        $cached = $rc->getConstructor('Test');
        $new    = $rc->getClass('Test')->getConstructor();

        $this->assertFalse($cached === $new);
        $this->assertTrue($rc->getConstructor('Test') === $cached);

        return $rc;
    }

    /**
     * @depends testGetConstructorCachesReflectionIfAvailable
     * @covers Auryn\ReflectionPool::getConstructorParameters
     */
    public function testGetCtorParamsRetrievesNewReflectionIfNotCached($rc) {
        $params = $rc->getConstructorParameters('Test');
        $this->assertTrue(is_array($params));
        $this->assertInstanceOf('ReflectionParameter', $params[0]);

        return $rc;
    }

    /**
     * @depends testGetCtorParamsRetrievesNewReflectionIfNotCached
     * @covers Auryn\ReflectionPool::getConstructorParameters
     */
    public function testGetCtorParamsReturnsNullIfNoConstructorExists($rc) {
        $params = $rc->getConstructorParameters('Param');
        $this->assertNull($params);

        return $rc;
    }

    /**
     * @depends testGetCtorParamsReturnsNullIfNoConstructorExists
     * @covers Auryn\ReflectionPool::getConstructorParameters
     */
    public function testGetCtorParamsRetrievesCachedReflectionIfAvailable($rc) {
        $params = $rc->getConstructorParameters('Test');
        $p1 = $rc->getConstructor('Test')->getParameters();
        $this->assertTrue(is_array($p1));
        $this->assertEquals($p1[0], $params[0]);

        return $rc;
    }

    /**
     * @depends testGetCtorParamsRetrievesCachedReflectionIfAvailable
     * @covers Auryn\ReflectionPool::getParamTypeHint
     */
    public function testGetTypeHintRetrievesNewClassNameIfNotStoredForParam($rc) {
        $method = $rc->getConstructor('Test');
        $param = $rc->getConstructorParameters('Test');
        $typeHint = $rc->getParamTypeHint($method, $param[0]);
        $this->assertEquals('Param', $typeHint);

        return $rc;
    }

    /**
     * @depends testGetTypeHintRetrievesNewClassNameIfNotStoredForParam
     * @covers Auryn\ReflectionPool::getParamTypeHint
     */
    public function testGetTypeHintFetchesCachedParamTypeHintIfAvailable($rc) {
        $method = $rc->getConstructor('Test');
        $param = $rc->getConstructorParameters('Test');
        $typeHint = $rc->getParamTypeHint($method, $param[0]);
        $this->assertEquals('Param', $typeHint);

        return $rc;
    }

    /**
     * @depends testGetTypeHintFetchesCachedParamTypeHintIfAvailable
     * @covers Auryn\ReflectionPool::getParamTypeHint
     */
    public function testGetTypeHintStoresNewReflectionClassIfFound($rc) {
        $method = new ReflectionMethod('TypeHintTester', 'myMethod');
        $params = $method->getParameters();

        $typeHint = $rc->getParamTypeHint($method, $params[0]);
        $this->assertEquals('TypeHint', $typeHint);

        return $rc;
    }

    /**
     * @depends testGetTypeHintStoresNewReflectionClassIfFound
     * @covers Auryn\ReflectionPool::getParamTypeHint
     */
    public function testGetTypeHintReturnsNullIfParamHasNoTypeHint($rc) {
        $method = new ReflectionMethod('TypeHintTester', 'myMethod');
        $params = $method->getParameters();

        $typeHint = $rc->getParamTypeHint($method, $params[1]);
        $this->assertEquals(NULL, $typeHint);

        return $rc;
    }
}

class Param {}

class Test
{
    public function __construct(Param $param) {}
}

class TypeHint {}

class TypeHintTester
{
    public function myMethod(TypeHint $arg, $noHint){}
}


text:
#ifndef QMITKXNATOBJECTEDITORINPUT_H_
#define QMITKXNATOBJECTEDITORINPUT_H_

#include "berryIEditorInput.h"
#include "ctkXnatObject.h"

class QmitkXnatObjectEditorInput : public berry::IEditorInput {

public:
  berryObjectMacro(QmitkXnatObjectEditorInput);
  berryNewMacro1Param(QmitkXnatObjectEditorInput, ctkXnatObject*);

  ~QmitkXnatObjectEditorInput();

  /// \brief Returns the kept ctkXnatObject.
  ctkXnatObject* GetXnatObject() const;

  virtual bool Exists() const;
  virtual std::string GetName() const;
  virtual std::string GetToolTipText() const;
  virtual bool operator==(const berry::Object* o) const;

private:
  QmitkXnatObjectEditorInput(ctkXnatObject* object);

  ctkXnatObject* m_Object;
};

#endif /*QMITKXNATOBJECTEDITORINPUT_H_*/


text:
package org.ovirt.mobile.movirt.model;

import android.content.ContentValues;
import android.net.Uri;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import org.ovirt.mobile.movirt.R;
import org.ovirt.mobile.movirt.provider.OVirtContract;
import org.ovirt.mobile.movirt.util.CursorHelper;
import org.ovirt.mobile.movirt.util.ObjectUtils;

import static org.ovirt.mobile.movirt.provider.OVirtContract.StorageDomain.TABLE;

@DatabaseTable(tableName = TABLE)
public class StorageDomain extends OVirtEntity implements OVirtContract.StorageDomain {

    @Override
    public Uri getBaseUri() {
        return CONTENT_URI;
    }

    public enum Type {
        DATA,
        ISO,
        IMAGE,
        EXPORT
    }

    public enum Status {
        ACTIVE(R.drawable.up),
        INACTIVE(R.drawable.down),
        LOCKED(R.drawable.unconfigured),
        MIXED(R.drawable.unconfigured),
        UNATTACHED(R.drawable.unconfigured),
        MAINTENANCE(R.drawable.unconfigured),
        PREPARING_FOR_MAINTENANCE(R.drawable.unconfigured),
        DETACHING(R.drawable.unconfigured),
        ACTIVATING(R.drawable.unconfigured),
        UNKNOWN(R.drawable.unconfigured);

        Status(int resource) {
            this.resource = resource;
        }

        private final int resource;

        public int getResource() {
            return resource;
        }
    }

    @DatabaseField(columnName = TYPE)
    private Type type;

    @DatabaseField(columnName = AVAILABLE_SIZE_MB)
    private long availableSizeMb;

    @DatabaseField(columnName = USED_SIZE_MB)
    private long usedSizeMb;

    @DatabaseField(columnName = STATUS)
    private Status status;

    @DatabaseField(columnName = STORAGE_ADDRESS)
    private String storageAddress;

    @DatabaseField(columnName = STORAGE_TYPE)
    private String storageType;

    @DatabaseField(columnName = STORAGE_PATH)
    private String storagePath;

    @DatabaseField(columnName = STORAGE_FORMAT)
    private String storageFormat;

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public long getAvailableSizeMb() {
        return availableSizeMb;
    }

    public void setAvailableSizeMb(long availableSizeMb) {
        this.availableSizeMb = availableSizeMb;
    }

    public long getUsedSizeMb() {
        return usedSizeMb;
    }

    public void setUsedSizeMb(long usedSizeMb) {
        this.usedSizeMb = usedSizeMb;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public String getStorageAddress() {
        return storageAddress;
    }

    public void setStorageAddress(String storageAddress) {
        this.storageAddress = storageAddress;
    }

    public String getStorageType() {
        return storageType;
    }

    public void setStorageType(String storageType) {
        this.storageType = storageType;
    }

    public String getStoragePath() {
        return storagePath;
    }

    public void setStoragePath(String storagePath) {
        this.storagePath = storagePath;
    }

    public String getStorageFormat() {
        return storageFormat;
    }

    public void setStorageFormat(String storageFormat) {
        this.storageFormat = storageFormat;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;

        StorageDomain storageDomain = (StorageDomain) o;

        if (type != storageDomain.type) return false;
        if (availableSizeMb != storageDomain.availableSizeMb) return false;
        if (usedSizeMb != storageDomain.usedSizeMb) return false;
        if (status != storageDomain.status) return false;
        if (!ObjectUtils.equals(storageAddress, storageDomain.storageAddress)) return false;
        if (!ObjectUtils.equals(storageType, storageDomain.storageType)) return false;
        if (!ObjectUtils.equals(storagePath, storageDomain.storagePath)) return false;
        if (!ObjectUtils.equals(storageFormat, storageDomain.storageFormat)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (type != null ? type.hashCode() : 0);
        result = 31 * result + (int) (availableSizeMb ^ (availableSizeMb >>> 32));
        result = 31 * result + (int) (usedSizeMb ^ (usedSizeMb >>> 32));
        result = 31 * result + (status != null ? status.hashCode() : 0);
        result = 31 * result + (storageAddress != null ? storageAddress.hashCode() : 0);
        result = 31 * result + (storageType != null ? storageType.hashCode() : 0);
        result = 31 * result + (storagePath != null ? storagePath.hashCode() : 0);
        result = 31 * result + (storageFormat != null ? storageFormat.hashCode() : 0);

        return result;
    }

    @Override
    public ContentValues toValues() {
        ContentValues values = super.toValues();
        values.put(TYPE, getType().toString());
        values.put(AVAILABLE_SIZE_MB, getAvailableSizeMb());
        values.put(USED_SIZE_MB, getUsedSizeMb());
        values.put(STATUS, getStatus().toString());
        values.put(STORAGE_ADDRESS, getStorageAddress());
        values.put(STORAGE_TYPE, getStorageType());
        values.put(STORAGE_PATH, getStoragePath());
        values.put(STORAGE_FORMAT, getStorageFormat());

        return values;
    }

    @Override
    public void initFromCursorHelper(CursorHelper cursorHelper) {
        super.initFromCursorHelper(cursorHelper);

        setType(cursorHelper.getEnum(TYPE, StorageDomain.Type.class));
        setAvailableSizeMb(cursorHelper.getLong(AVAILABLE_SIZE_MB));
        setUsedSizeMb(cursorHelper.getLong(USED_SIZE_MB));
        setStatus(cursorHelper.getEnum(STATUS, StorageDomain.Status.class));
        setStorageAddress(cursorHelper.getString(STORAGE_ADDRESS));
        setStorageType(cursorHelper.getString(STORAGE_TYPE));
        setStoragePath(cursorHelper.getString(STORAGE_PATH));
        setStorageFormat(cursorHelper.getString(STORAGE_FORMAT));
    }

}


text:
require 'test_helper'

class <%= class_name %>DecoratorTest < ActiveSupport::TestCase
  def setup
    @<%= singular_name %> = <%= class_name %>.new.extend <%= class_name %>Decorator
  end

  # test "the truth" do
  #   assert true
  # end
end