text:
namespace Cards.Extensions.Tfs.Core.Migrations
{
    using System.Data.Entity.Migrations;

    public partial class Add_Cards_To_Areas : DbMigration
    {
        public override void Up()
        {
            CreateIndex("dbo.Cards", "AreaID");
            AddForeignKey("dbo.Cards", "AreaID", "dbo.Areas", "ID", cascadeDelete: true);
        }

        public override void Down()
        {
            DropForeignKey("dbo.Cards", "AreaID", "dbo.Areas");
            DropIndex("dbo.Cards", new[] { "AreaID" });
        }
    }
}


text:
{{hashname}}.insert_lookup_iter_{{side}}<&{{global_syncname}}>({{keyval}}, {{keyname}}, [=]({{other_tuple_type}} {{valname}}) {
  join_coarse_result_count++;
  {{out_tuple_type}} {{out_tuple_name}} = {{append_func_name}}({{left_name}}, {{right_name}});
  {{inner_plan_compiled}}
});

redpajama_set_name: RedPajamaGithub


text:
import { INSTALLED } from './autoDetectResource';
import { ArrayResource } from './ArrayResource';
import { BufferResource } from './BufferResource';
import { CanvasResource } from './CanvasResource';
import { CubeResource } from './CubeResource';
import { ImageResource } from './ImageResource';
import { SVGResource } from './SVGResource';
import { VideoResource } from './VideoResource';
import { ImageBitmapResource } from './ImageBitmapResource';

export * from './Resource';
export * from './BaseImageResource';

INSTALLED.push(
    ImageResource,
    ImageBitmapResource,
    CanvasResource,
    VideoResource,
    SVGResource,
    BufferResource,
    CubeResource,
    ArrayResource
);

export * from './autoDetectResource';
export * from './AbstractMultiResource';
export * from './ArrayResource';
export * from './BufferResource';
export * from './CanvasResource';
export * from './CubeResource';
export * from './ImageResource';
export * from './SVGResource';
export * from './VideoResource';
export * from './ImageBitmapResource';


text:
using System;
using GeoAPI.Geometries;
using NetTopologySuite.Geometries;

namespace DotSpatial.NTSExtension
{
    public static class LineStringExt
    {

        /// <summary>
        /// Gets the value of the angle between the StartPoint and the EndPoint in Radian.
        /// </summary>
        /// <remarks>added by JLeiss</remarks>
        public static double RadAngle(this ILineString self)
        {
            double deltaX = self.EndPoint.X - self.StartPoint.X;
            double deltaY = self.EndPoint.Y - self.StartPoint.Y;
            double winkel = Math.Atan(deltaY / deltaX);

            if (deltaX < 0)
            {
                if (deltaY <= 0) winkel += Math.PI;
                if (deltaY > 0) winkel -= Math.PI;
            }
            return winkel;
        }

        /// <summary>
        /// Given the specified test point, this checks each segment, and will
        /// return the closest point on the specified segment.
        /// </summary>
        /// <param name="testPoint">The point to test.</param>
        public static Coordinate ClosestPoint(this ILineString self, Coordinate testPoint)
        {
            Coordinate closest = self.GetCoordinateN(0);
            double dist = double.MaxValue;
            for (int i = 0; i < self.NumPoints - 1; i++)
            {
                LineSegment s = new LineSegment(self.GetCoordinateN(i), self.GetCoordinateN(i + 1));
                Coordinate temp = s.ClosestPoint(testPoint);
                double tempDist = testPoint.Distance(temp);
                if (tempDist < dist)
                {
                    dist = tempDist;
                    closest = temp;
                }
            }
            return closest;
        }

    }
}


text:
package com.zobot.client.packet.definitions.clientbound.login

import com.zobot.client.packet.Packet

case class SetCompression(threshold: Int) extends Packet {
  override lazy val packetId = 0x03

  override lazy val packetData: Array[Byte] =
    fromVarInt(threshold)
}


text:
<?xml version="1.0" ?>
<config>
    <modules>
        <Genmato_UnCancel>
            <active>true</active>
            <codePool>community</codePool>
            <depends>
                <Genmato_Core/>
            </depends>
        </Genmato_UnCancel>
    </modules>
</config>


text:
package config

import (
	"io/ioutil"
	"sort"
	"strings"

	"gopkg.in/yaml.v3"

	"github.com/daixiang0/gci/pkg/section"
)

var defaultOrder = map[string]int{
	section.StandardType: 0,
	section.DefaultType:  1,
	section.CustomType:   2,
	section.BlankType:    3,
	section.DotType:      4,
}

type BoolConfig struct {
	NoInlineComments bool `yaml:"no-inlineComments"`
	NoPrefixComments bool `yaml:"no-prefixComments"`
	Debug            bool `yaml:"-"`
	SkipGenerated    bool `yaml:"skipGenerated"`
	CustomOrder      bool `yaml:"customOrder"`
}

type Config struct {
	BoolConfig
	Sections          section.SectionList
	SectionSeparators section.SectionList
}

type YamlConfig struct {
	Cfg                     BoolConfig `yaml:",inline"`
	SectionStrings          []string   `yaml:"sections"`
	SectionSeparatorStrings []string   `yaml:"sectionseparators"`
}

func (g YamlConfig) Parse() (*Config, error) {
	var err error

	sections, err := section.Parse(g.SectionStrings)
	if err != nil {
		return nil, err
	}
	if sections == nil {
		sections = section.DefaultSections()
	}

	// if default order sorted sections
	if !g.Cfg.CustomOrder {
		sort.Slice(sections, func(i, j int) bool {
			sectionI, sectionJ := sections[i].Type(), sections[j].Type()

			if strings.Compare(sectionI, sectionJ) == 0 {
				return strings.Compare(sections[i].String(), sections[j].String()) < 0
			}
			return defaultOrder[sectionI] < defaultOrder[sectionJ]
		})
	}

	sectionSeparators, err := section.Parse(g.SectionSeparatorStrings)
	if err != nil {
		return nil, err
	}
	if sectionSeparators == nil {
		sectionSeparators = section.DefaultSectionSeparators()
	}

	return &Config{g.Cfg, sections, sectionSeparators}, nil
}

func InitializeGciConfigFromYAML(filePath string) (*Config, error) {
	config := YamlConfig{}
	yamlData, err := ioutil.ReadFile(filePath)
	if err != nil {
		return nil, err
	}
	err = yaml.Unmarshal(yamlData, &config)
	if err != nil {
		return nil, err
	}
	gciCfg, err := config.Parse()
	if err != nil {
		return nil, err
	}
	return gciCfg, nil
}


text:
package org.sparkcommerce.openadmin.web.compatibility;

import org.sparkcommerce.openadmin.dto.Entity;
import org.sparkcommerce.openadmin.dto.Property;
import org.sparkcommerce.openadmin.server.service.JSCompatibilityHelper;
import org.sparkcommerce.openadmin.web.form.component.RuleBuilderField;
import org.sparkcommerce.openadmin.web.form.entity.EntityForm;
import org.sparkcommerce.openadmin.web.form.entity.Field;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Jeff Fischer
 */
public class JSFieldNameCompatibilityInterceptor extends HandlerInterceptorAdapter {

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
            modelAndView) throws Exception {
        if (modelAndView != null) {
            Entity entity = (Entity) modelAndView.getModelMap().get("entity");
            EntityForm entityForm = (EntityForm) modelAndView.getModelMap().get("entityForm");

            if (entity != null) {
                for (Property property : entity.getProperties()) {
                    if (property.getName().contains(".")) {
                        property.setName(JSCompatibilityHelper.encode(property.getName()));
                    }
                }
            }

            if (entityForm != null) {
                entityForm.clearFieldsMap();
                for (Map.Entry<String, Field> field : entityForm.getFields().entrySet()) {
                    if (field.getKey().contains(".")) {
                        field.getValue().setName(JSCompatibilityHelper.encode(field.getValue().getName()));
                        if (field.getValue() instanceof RuleBuilderField) {
                            ((RuleBuilderField) field.getValue()).setJsonFieldName(JSCompatibilityHelper.encode((
                                    (RuleBuilderField) field.getValue()).getJsonFieldName()));
                        }
                    }
                }
                entityForm.clearFieldsMap();
            }
        }
    }
}


text:
module GraphMatching
  # Converts the vertices of a graph to integers.  Many graph
  # matching algorithms require integer vertexes.
  module IntegerVertexes
    # Converts the vertices of `graph` to positive nonzero integers.
    # For example, given a graph (a=b), returns a new graph (1=2).
    # It also returns a legend, which maps the integers to the
    # original vertexes.
    #
    def self.to_integers(graph)
      raise ArgumentError unless graph.is_a?(RGL::MutableGraph)
      legend = {}
      reverse_legend = {}
      new_graph = graph.class.new
      graph.vertices.each_with_index do |vertex, ix|
        legend[ix + 1] = vertex
        reverse_legend[vertex] = ix + 1
      end
      graph.edges.each do |edge|
        source = reverse_legend[edge.source]
        target = reverse_legend[edge.target]
        new_graph.add_edge(source, target)
      end
      [new_graph, legend]
    end
  end
end


text:
[Click here](https://erics-tic-tac-toe.herokuapp.com) to play!

## To play game locally:

+ Clone this repository
+ In the root directory:
```
npm install
npm install -g beefy
npm install -g browserify
browserify src/index.js -o bundle.js
beefy --browserify bundle.js
```
+ Open `http://localhost:9966` in your browser.

## To run tests:

+ In the root directory:
```
npm install testem -g
browserify spec/test.js -o test_bundle.js
testem
```


text:
package org.jbehave.core.io.rest.redmine;

import static java.text.MessageFormat.format;

import org.jbehave.core.io.rest.RESTClient.Type;
import org.jbehave.core.io.rest.Resource;
import org.jbehave.core.io.rest.UploadToREST;

import com.google.gson.Gson;

/**
 * Uploads resource to Redmine wiki pages using the REST API
 */
public class UploadToRedmine extends UploadToREST {

	private static final String REDMINE_URI = "{0}.{1}";

	public UploadToRedmine(Type type) {
		this(type, null, null);
	}

	public UploadToRedmine(Type type, String username, String password) {
		super(type, username, password);
	}

	protected String uri(String resourcePath, Type type) {
		return format(REDMINE_URI, resourcePath, type.name().toLowerCase());
	}

	protected String entity(Resource resource, Type type) {
		Page page = new Page();
		page.title = resource.getName();
		page.text = resource.getContent();
		Entity entity = new Entity();
		entity.wiki_page = page;
		switch (type) {
		case JSON:
			Gson gson = new Gson();
			return gson.toJson(entity);
		case XML:
		default:
			return resource.getContent();
		}
	}

	private static class Entity {
		private Page wiki_page;
	}

	private static class Page {
		private String title;
		private String text;
	}

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading;
using FluentFTP;
using log4net;
using SS.FTPDownloader.FTP;
using SS.FTPDownloader.Objects;
using SS.FTPDownloader.Utilities;

namespace SS.FTPDownloader
{
	public class FtpEvents
	{
		public EventHandler<ProgressEventArgs> UpdatedProgressHandler { get; set; }
		public EventHandler<DownloadedEventArgs> DownloadStartedHandler { get; set; }
		public EventHandler<DownloadedEventArgs> DownloadErrorHandler { get; set; }
		public EventHandler<DownloadedEventArgs> DownloadCompletedHandler { get; set; }
		public EventHandler<FileCleanupEventArgs> CleanupStartedHandler { get; set; }
		public EventHandler<FileCleanupEventArgs> CleanupCompletedHandler { get; set; }
	}

	public class FtpDownloader
	{
		private readonly Settings _settings;
		private readonly BackgroundWorker _checkWorker = new BackgroundWorker();
		private readonly IFileCleanup _cleanup;
		private readonly IFtpWrapper _ftpWrapper;
		private readonly BackgroundWorker _processWorker = new BackgroundWorker();

		private List<DownloadedEventArgs> _downloadedFiles;
		private bool _isProcessing;

		// ReSharper disable once NotAccessedField.Local
		private Timer _timer;
		private readonly FtpEvents _events;

		private static readonly ILog Log = LogManager.GetLogger(typeof(FtpDownloader));

		public FtpDownloader(Settings settings, FtpEvents events = null)
		{
			_events = events ?? new FtpEvents();
			_settings = settings;
			TvRenamer.SetRemapFile(settings.RemapFile);
			_ftpWrapper = GenerateFtpWrapper(_settings, _events);
			_cleanup = GenerateFileCleanup(_settings, _events);
		}

		public void BeginProcess()
		{
			_processWorker.WorkerReportsProgress = true;
			_processWorker.DoWork += DownloadFiles;

			_checkWorker.WorkerReportsProgress = true;
			_checkWorker.ProgressChanged += BeginDownloading;
			_checkWorker.DoWork += CheckServer;

			Log.Info($"FTP AutoDownloader v{typeof(FtpDownloader).Assembly.GetName().Version}\n");

			_timer = new Timer(BeginCheck, 1, new TimeSpan(0, 0, 5),
				new TimeSpan(0, _settings.NormalRecheckTime, 0));
		}

		private void BeginCheck(object o)
		{
			if (_checkWorker.IsBusy) return;

			_checkWorker.RunWorkerAsync(o);
		}

		private void BeginDownloading(object sender, ProgressChangedEventArgs args)
		{
			if (_processWorker.IsBusy) return;

			_processWorker.RunWorkerAsync();
		}

		private static FtpWrapper GenerateFtpWrapper(Settings settings, FtpEvents events)
		{
			var ftp = new FtpWrapper(settings);

			if (events == null)
			{
				return ftp;
			}

			ftp.OnProgressUpdated += events.UpdatedProgressHandler;
			ftp.OnDownloadStarted += events.DownloadStartedHandler;
			ftp.OnDownloadError += events.DownloadErrorHandler;
			ftp.OnDownloadComplete += events.DownloadCompletedHandler;

			return ftp;
		}

		private static FileCleanup GenerateFileCleanup(Settings settings, FtpEvents events)
		{
			var cleanup = new FileCleanup(settings.EnableOrganization, settings.VideoRootPath);

			cleanup.CleanupStarted += events.CleanupStartedHandler;
			cleanup.CleanupFinished += events.CleanupCompletedHandler;

			return cleanup;
		}

		private void DownloadFiles(object sender, DoWorkEventArgs doWorkEventArgs)
		{
			while (FtpWrapper.DownloadList.Any())
			{
				if (_isProcessing)
				{
					return;
				}

				using (var ftp = GenerateFtpWrapper(_settings, _events))
				{
					if (_settings.EnableProcessing)
					{
						if (_settings.BatchDownloads)
						{
							ftp.OnDownloadComplete += RecordBatchDownload;
						}
						else
						{
							ftp.OnDownloadComplete += _cleanup.CleanupFile;
						}
					}

					ftp.Connect();
					ftp.DownloadFiles(_settings.BatchDownloads ? _settings.BatchDownloadSize : 0);
					ftp.Disconnect();
				}

				if (!_settings.BatchDownloads)
				{
					continue;
				}

				ProcessBatchDownloads();
			}
		}

		private void ProcessBatchDownloads()
		{
			if (_isProcessing || !_settings.EnableProcessing) return;

			_isProcessing = true;

			foreach (var file in _downloadedFiles.ToList())
			{
				_cleanup.CleanupFile(this, file);
				_downloadedFiles.Remove(file);
			}

			_isProcessing = false;
		}

		private void RecordBatchDownload(object sender, DownloadedEventArgs downloadedEventArgs)
		{
			if (_downloadedFiles == null)
			{
				_downloadedFiles = new List<DownloadedEventArgs>();
			}

			_downloadedFiles.Add(downloadedEventArgs);
		}

		private void CheckServer(object sender, DoWorkEventArgs e)
		{
			var tryCount = e.Argument as int? ?? 1;

			if (tryCount > 3)
			{
				return;
			}

			try
			{
				_ftpWrapper.Connect();
				var allFiles = GetAllFilesOnServer();
				_ftpWrapper.Disconnect();

				if (!allFiles.Any()) return;

				Log.Info($"{allFiles.Count} files found. Determining eligability.");

				Thread.Sleep(new TimeSpan(0, 0, 5));

				_ftpWrapper.Connect();
				var checkList = GetAllFilesOnServer();
				_ftpWrapper.Disconnect();

				var toDownload = 0;

				foreach (var file in allFiles)
				{
					Log.Debug($"Found {file.FullName}.");
				}

				foreach (var file in allFiles)
				{
					var check = checkList.SingleOrDefault(x => x.FullName == file.FullName);

					if (check?.FullName == FtpWrapper.CurrentItem?.FullName ||
						check?.Modified != file.Modified ||
						FtpWrapper.DownloadList.Contains(check))
					{
						continue;
					}

					var isPriority = Path.GetDirectoryName(check.FullName) == "\\" + _settings.FtpRootCheckDir;

					Log.Debug($"{file.FullName} added to queue ({(!isPriority ? "not " : "")}priority).");
					FtpWrapper.DownloadList.Enqueue(check, isPriority);
					toDownload++;
				}

				if (toDownload <= 0) return;

				Log.Info($"Found {toDownload} new files eligable for download.");
				_checkWorker.ReportProgress(toDownload);
			}
			catch (FtpException ex)
			{
				Log.Error("An FTP connection error has occured.");
				Log.Error(ex.Message);

				CheckServer(sender, new DoWorkEventArgs(++tryCount));
			}
			catch (Exception ex)
			{
				Log.Error("An unknown error occured checking the server:");
				Log.Error(ex.Message);
			}
		}

		private List<FtpListItem> GetAllFilesOnServer()
		{
			return _ftpWrapper.GetAllFiles("").ToList();
		}
	}
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Sys_movimientos extends CI_Controller {

  function __construct()
  {
    parent::__construct();
    $this->load->helper(array('url','form','security','verphp','getrol','getacount','regen_pago','paginate','dates','querymysql'));//helpers primordiales
    $this->load->library(array('session','form_validation'));
    $this->load->model('sys_inventario/Movimientos_model','movimientos_model');
    $this->load->model('sys_caja/Maincaja_model','maincaja_model');

  }

	public function index()
  {
    if ($this->session->userdata('habit')==false || $this->session->userdata('habit')=='')
    {
      $data['token'] = $this->get_token();
      $this->load->view('log_usr',$data);
    }
    else {
        $this->load->view('main/head');

        $movi = $this->movimientos_model->getpMov();

        $data = ['movimientos' => $movi];

        $this->load->view('sys_inventario/sys_movimientos',$data,false);

        }
	}

// --------------------

public function guardar_movimiento()
{
    $data = json_decode($this->input->post('data'));
    $fila = $data->myRows;//array de filas

    $arti=array();$lote=array();$vence=array();$costo=array();
    $b_ini=array();$b_fin=array();$cant=array();$move=array(); $nom=array();
    foreach ($fila as $value)
    {
      $nom[]=$value->nom_art;
      $arti[]=$value->nom_art;
      $lote[]=$value->lote;
      $vence[]=$value->vence;
      $cant[]=$value->cant;
      $costo[]=$value->costo;
      $b_ini[]=$value->entra;
      $b_fin[]=$value->sale;
      $venta[]=$value->venta;
      $move[]=$value->tipomov;
      $cliente[]=$value->cliente;
      $res[]='directo';
      $idreserva[]='';
      $calendario[]='';
      $totable[]=$value->total;
      $tcosto[]=$value->tcosto;

    }
    $data=array('tipomove' => $move,'articulo' => $arti,
    'lote' => $lote ,'vence' => $vence,
    'cantidad' => $cant,'costo' => $costo,
    'bodega_ini' => $b_ini,'prosel' => $cliente,
    'res' => $res,'idreserva' => $idreserva,
    'calendario' => $calendario , 'total_articulo' => $totable,
    'venta' => $venta, 'bodega_fin'=>$b_fin, 'nom_art' => $nom, 'tcosto' => $tcosto  );

    $rta = $this->movimientos_model->saveMovi($data);
    echo $rta;

}

public function buscaArticulos()
{

  $data=array('id' => $this->input->post('id'));
  echo $this->movimientos_model->articulos_activos($data);

}

public function gen_info()
{
  $data = array('articulo' => $this->input->post('sel_articulos'),
  'bodega' => $this->input->post('sel_bodegas'),
  'fini' => $this->input->post('fini_'),
  'ffin' => $this->input->post('ffin_'));
  $rta=$this->movimientos_model->gen_info($data);
  return $rta;
}

public function getMov()
{
  return $this->movimientos_model->getpMov();
}

public function getMovSal()
{
  return $this->movimientos_model->getpMovSal();
}

public function getBodega()
{
  return $this->movimientos_model->getBodega();
}

public function pideLote()
{
  $data=$this->input->post('arti');
  return $this->movimientos_model->pideLote($data);
}

public function movsFiltro()
{
  $data=array('arti' => $this->input->post('arti'),
              'bode' => $this->input->post('bode'));
  return $this->movimientos_model->movsFiltro($data);
}

public function getdataMovs()
{
  $data=array('arti' => $this->input->post('arti'),'bode' => $this->input->post('bode'),'pag' => $this->input->post('pag'));
  return $this->movimientos_model->getMovs($data);
}

public function getArticulos()
{
  return $this->movimientos_model->getArticulos();
}

public function gArti()
{
  $data=array('id' => $this->input->post('id'));
  return $this->movimientos_model->gArti($data);
}

public function getCant()
{
  $data=array('arti' => $this->input->post('arti'),
              'lote' => $this->input->post('lote'),
              'cant' => $this->input->post('cant'),
              'bode' => $this->input->post('bode'));
  return $this->movimientos_model->getCant($data);
}

public function getLotes()
{
  $data=array('arti' => $this->input->post('arti'),
              'bode' => $this->input->post('bode'));
  return $this->movimientos_model->getLotes($data);
}

public function gPro()
{
  $data=array('id' => $this->input->post('id'),
        'tipo' => $this->input->post('tipo'));
  return $this->movimientos_model->gPro($data);
}

/*public function saveMovi()
{
  $data=array('tipomove' => $this->input->post('tipomove'),'articulo' => $this->input->post('articulo'),
  'lote' => strtoupper($this->input->post('lote')),'vence' => $this->input->post('vence'),
  'cantidad' => $this->input->post('cantidad'),'costo' => $this->input->post('costo'),
  'bodega_ini' => $this->input->post('bodega_ini'),'bodega_fin' => $this->input->post('bodega_fin'),
  'tipoper' => $this->input->post('tipoper'),'prosel' => $this->input->post('prosel'));
  return $this->movimientos_model->saveMovi($data);
}*/

public function saveMovi()
{
    $data = json_decode($this->input->post('data'));
    $fila = $data->myRows;//array de filas
    $arti=array();$lote=array();$vence=array();$costo=array();
    $b_ini=array();$b_fin=array();$cant=array();$move=array();
    $prosel=array();
    foreach ($fila as $value)
    {
      $arti[]=$value->Artículo;
      $lote[]=$value->Lote;
      $vence[]=$value->Vence;
      $cant[]=$value->Cantidad;
      $costo[]=$value->Costo;
      $b_ini[]=$value->Binicio;
      $b_fin[]=$value->Bfinal;
      $move[]=$value->tipomov;
      $prosel[]=$value->prosel;
    }
    $data=array('tipomove' => $move,'articulo' => $arti,
    'lote' => $lote ,'vence' => $vence,
    'cantidad' => $cant,'costo' => $costo,
    'bodega_ini' => $b_ini,'bodega_fin' => $b_fin,
    'prosel' => $prosel);
    return $this->movimientos_model->saveMovi($data);

}

// ----------------------

  public function verificar()
  {
    return $this->movimientos_model->consultaId($data);
  }

  public function log_out()
  {
    $this->session->sess_destroy();
    $this->index();
  }

  public function get_token()
  {
    $token= md5(uniqid(rand(),true));
    $this->session->set_userdata('token',$token);
    return $token;
  }
}

?>


text:
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE TypeFamilies  #-}

-- | Provides spherical harmonic models of scalar-valued functions.
module Math.SphericalHarmonics
(
  SphericalHarmonicModel
, sphericalHarmonicModel
, scaledSphericalHarmonicModel
, evaluateModel
, evaluateModelCartesian
, evaluateModelGradient
, evaluateModelGradientCartesian
, evaluateModelGradientInLocalTangentPlane
)
where

import Data.Complex
import Data.VectorSpace hiding (magnitude)
import Math.SphericalHarmonics.AssociatedLegendre
import Numeric.AD

-- | Represents a spherical harmonic model of a scalar-valued function.
data SphericalHarmonicModel a = SphericalHarmonicModel [[(a, a)]]
  deriving (Functor)

-- | Creates a spherical harmonic model.
-- Result in an error if the length of the list is not a triangular number.
sphericalHarmonicModel :: (Fractional a) => [[(a, a)]] -- ^ A list of g and h coefficients for the model
                       -> SphericalHarmonicModel a -- ^ The spherical harmonic model
sphericalHarmonicModel cs | valid = SphericalHarmonicModel cs
                          | otherwise = error "The number of coefficients is not a triangular number."
  where
    valid = and $ zipWith (==) (fmap length cs) [1..length cs]

-- | Creates a spherical harmonic model, scaling coefficients for the supplied reference radius.
-- Result in an error if the length of the list is not a triangular number.
scaledSphericalHarmonicModel :: (Fractional a) => a -- ^ The reference radius
                       -> [[(a, a)]] -- ^ A list of g and h coefficients for the model
                       -> SphericalHarmonicModel a -- ^ The spherical harmonic model
scaledSphericalHarmonicModel r cs = sphericalHarmonicModel cs'
  where
    cs' = normalizeReferenceRadius r cs

instance(Fractional a, Eq a) => AdditiveGroup (SphericalHarmonicModel a) where
  zeroV = SphericalHarmonicModel [[(0,0)]]
  negateV = fmap negate
  (SphericalHarmonicModel m1) ^+^ (SphericalHarmonicModel m2) = SphericalHarmonicModel (combineCoefficients m1 m2)
    where
      combineCoefficients [] cs = cs
      combineCoefficients cs [] = cs
      combineCoefficients (c1:cs1) (c2:cs2) = zipWith addPairs c1 c2 : combineCoefficients cs1 cs2
      addPairs (g1, h1) (g2, h2) = (g1 + g2, h1 + h2)

instance (Fractional a, Eq a) => VectorSpace (SphericalHarmonicModel a) where
  type Scalar (SphericalHarmonicModel a) = a
  x *^ m = fmap (* x) m

normalizeReferenceRadius :: (Fractional a) => a -> [[(a, a)]] -> [[(a, a)]]
normalizeReferenceRadius r = zipWith (fmap . mapWholePair . transform) [0 :: Int ..]
  where
    transform n = (* (r ^ (2 + n)))

-- | Computes the scalar value of the spherical harmonic model at a specified spherical position.
evaluateModel :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model
              -> a -- ^ Spherical radius
              -> a -- ^ Spherical colatitude (radian)
              -> a -- ^ Spherical longitude (radian)
              -> a -- ^ Model value
evaluateModel m r colat lon = evaluateModel' m r (cos colat) (cis lon)

-- | Computes the scalar value of the spherical harmonic model at a specified Cartesian position.
evaluateModelCartesian :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model
                       -> a -- ^ X position
                       -> a -- ^ Y position
                       -> a -- ^ Z position
                       -> a -- ^ Model value
evaluateModelCartesian m x y z = evaluateModel' m r cosColat cisLon
  where
    r = sqrt $ (x*x) + (y*y) + (z*z)
    cosColat = z / r
    cisLon = normalize $ mkPolar x y

evaluateModel' :: (RealFloat a, Ord a) => SphericalHarmonicModel a
               -> a -- r
               -> a -- cosColat
               -> Complex a -- cisLon
               -> a
evaluateModel' (SphericalHarmonicModel cs) r cosColat cisLon = sum $ zipWith (*) (iterate (/ r) (recip r)) (zipWith evaluateDegree [0..] cs)
  where
    sines = 1 : iterate (* cisLon) cisLon
    evaluateDegree n cs' = sum $ zipWith3 evaluateOrder (fmap (schmidtSemiNormalizedAssociatedLegendreFunction n) [0..n]) cs' sines
    evaluateOrder p (g, h) cisMLon = ((g * realPart cisMLon) + (h * imagPart cisMLon)) * (p (cosColat))

-- | Computes the gradient of the scalar value of the spherical harmonic model, in spherical coordinates, at a specified location.
evaluateModelGradient :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model
                      -> a -- ^ Spherical radius
                      -> a -- ^ Spherical colatitude (radian)
                      -> a -- ^ Spherical longitude (radian)
                      -> (a, a, a) -- ^ Radial, colatitudinal, and longitudinal components of gradient
evaluateModelGradient model r colat lon = makeTuple . fmap negate $ modelGrad [r, colat, lon]
  where
    modelGrad = grad (\[r', c', l'] -> evaluateModel (fmap auto model) r' c' l')

-- | Computes the gradient of the scalar value of the spherical harmonic model at a specified location, in Cartesian coordinates.
-- The result is expressed in right-handed coordinates centered at the origin of the sphere, with the positive Z-axis piercing the
-- north pole and the positive x-axis piercing the reference meridian.
evaluateModelGradientCartesian :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model
                               -> a -- ^ X position
                               -> a -- ^ Y position
                               -> a -- ^ Z position
                               -> (a, a, a) -- X, Y, and Z components of gradient
evaluateModelGradientCartesian model x y z = makeTuple . fmap negate $ modelGrad [x, y, z]
  where
    modelGrad = grad (\[x', y', z'] -> evaluateModelCartesian (fmap auto model) x' y' z')

-- | Computes the gradient of the scalar value of the spherical harmonic model at a specified location, in Cartesian coordinates.
-- The result is expressed in a reference frame locally tangent to the sphere at the specified location.
evaluateModelGradientInLocalTangentPlane :: (RealFloat a, Ord a) => SphericalHarmonicModel a -- ^ Spherical harmonic model
                                         -> a -- ^ Spherical radius
                                         -> a -- ^ Spherical colatitude (radian)
                                         -> a -- ^ Spherical longitude (radian)
                                         -> (a, a, a) -- ^ East, North, and up components of gradient
evaluateModelGradientInLocalTangentPlane model r colat lon = (e, n, u)
  where
    (r', colat', lon') = evaluateModelGradient model r colat lon
    e = lon' / (r * sin colat)
    n = -colat' / r -- negated because the colatitude increase southward
    u = r'

normalize :: (RealFloat a) => Complex a -> Complex a
normalize r@(x :+ y) | isInfinite m' = 0
                     | otherwise = (x * m') :+ (y * m')
  where
    m' = recip . magnitude $ r

mapWholePair :: (a -> b) -> (a, a) -> (b, b)
mapWholePair f (a, b) = (f a, f b)

makeTuple :: [a] -> (a, a, a)
makeTuple [x, y, z] = (x, y, z)


text:
'use strict';

var app = angular.module('TaNo',
[
    'ngMaterial',
    'ngMessages',

    // application modules
    'app.controller.navigation',

    // Main Pages
    'app.controller.timeline', // show event timeline
    'app.controller.editor', // customize animation and translation sequences
    'app.controller.manualcontrol', // control shape-changing display manually
    //'app.controller.dashboard', // current stats
    'app.controller.apibrowser', // API Browser shows different API versions

    // Sub Pages
    'app.controller.devices',
    //'app.controller.settings',
    //'app.controller.help',
    //'app.controller.share',

    // Utils

]);

app.filter('cut', function () {
    return function (value, wordwise, max, tail) {

        if (!value) return '';

        max = parseInt(max, 10);
        if (!max) return value;
        if (value.length <= max) return value;

        value = value.substr(0, max);
        if (wordwise) {
            var lastspace = value.lastIndexOf(' ');
            if (lastspace != -1) {
              //Also remove . and , so its gives a cleaner result.
              if (value.charAt(lastspace-1) == '.' || value.charAt(lastspace-1) == ',') {
                lastspace = lastspace - 1;
              }
              value = value.substr(0, lastspace);
            }
        }

        return value + (tail || ' …');
    };
});


text:
module Spark
  module Serializer
    class MessagePack < Base

      def dump(data)
        ::MessagePack.dump(data)
      end

      def load(data)
        ::MessagePack.load(data)
      end

    end
  end
end

begin
  # TODO: require only if it is necessary
  require 'msgpack'

  Spark::Serializer.register('messagepack', 'message_pack', 'msgpack', 'msg_pack', Spark::Serializer::MessagePack)
rescue LoadError
end


text:
gdb-heapanalyzer
================


text:
package com.slack.api.methods.response.oauth;

import com.slack.api.methods.SlackApiResponse;
import lombok.Data;

/**
 * https://api.slack.com/methods/oauth.v2.access
 */
@Data
public class OAuthV2AccessResponse implements SlackApiResponse {

    private boolean ok;
    private String warning;
    private String error;
    private String needed;
    private String provided;

    private String appId;
    private AuthedUser authedUser;
    private String scope;
    private String tokenType; // "bot"
    private String accessToken; // xoxb-xxx-yyy
    private String botUserId;
    private Team team;
    private Enterprise enterprise;
    private IncomingWebhook incomingWebhook;

    @Data
    public static class AuthedUser {
        private String id;
        private String scope;
        private String tokenType; // "user"
        private String accessToken; // xoxp-xxx-yyy
    }

    @Data
    public static class Team {
        private String id;
        private String name;
    }

    @Data
    public static class Enterprise {
        private String id;
        private String name;
    }

    @Data
    public static class IncomingWebhook {
        private String url;
        private String channel;
        private String channelId;
        private String configurationUrl;
    }
}


text:
package com.intellij.lang.ant.segments;

import com.intellij.openapi.util.NlsSafe;
import com.intellij.rt.ant.execution.PoolOfDelimiters;
import com.intellij.util.ArrayUtilRt;
import org.jetbrains.annotations.NonNls;

import java.util.ArrayList;

public class SegmentReader {
  private final @NonNls String myString;
  private final char[] myChars;
  private int myPosition = 0;

  public SegmentReader(final @NonNls String packet) {
    myString = packet;
    myChars = packet.toCharArray();
  }

  public String upTo(final char symbol) {
    int position = myPosition;
    while (position < myChars.length && myChars[position] != symbol) position++;
    final String result = advanceTo(position);
    skip(1);
    return result;
  }

  public void skip(final int count) {
    myPosition = Math.min(myChars.length, myPosition + count);
  }

  public String upToEnd() {
    return advanceTo(myChars.length);
  }

  private String advanceTo(final int position) {
    final String result = myString.substring(myPosition, position);
    myPosition = position;
    return result;
  }

  public @NlsSafe String readLimitedString() {
    final int symbolCount = readInt();
    return advanceTo(myPosition + symbolCount);
  }

  public int readInt() {
    final String intString = upTo(PoolOfDelimiters.INTEGER_DELIMITER);
    return Integer.parseInt(intString);
  }

  public long readLong() {
    final String longString = upTo(PoolOfDelimiters.INTEGER_DELIMITER);
    return Long.parseLong(longString);
  }

  public char readChar() {
    myPosition++;
    return myChars[myPosition - 1];
  }

  public boolean isAtEnd() {
    return myPosition == myChars.length;
  }

  public String[] readStringArray() {
    final int count = readInt();
    if (count == 0) return ArrayUtilRt.EMPTY_STRING_ARRAY;
    final ArrayList<String> strings = new ArrayList<>(count);
    for (int i = 0; i < count; i++) {
      strings.add(readLimitedString());
    }
    return strings.toArray(new String[count]);
  }
}


text:
package org.apereo.cas.support.saml.web.idp.profile.slo;

import org.apereo.cas.logout.LogoutRedirectionStrategy;
import org.apereo.cas.support.saml.SamlIdPUtils;
import org.apereo.cas.support.saml.SamlProtocolConstants;
import org.apereo.cas.support.saml.SamlUtils;
import org.apereo.cas.support.saml.services.SamlRegisteredService;
import org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade;
import org.apereo.cas.support.saml.web.idp.profile.SamlProfileHandlerConfigurationContext;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.EncodingUtils;
import org.apereo.cas.util.HttpUtils;
import org.apereo.cas.util.RandomUtils;
import org.apereo.cas.web.support.WebUtils;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import net.shibboleth.utilities.java.support.xml.SerializeSupport;
import org.apache.commons.lang3.StringUtils;
import org.opensaml.core.xml.util.XMLObjectSupport;
import org.opensaml.saml.common.xml.SAMLConstants;
import org.opensaml.saml.saml2.core.LogoutRequest;
import org.opensaml.saml.saml2.core.LogoutResponse;
import org.opensaml.saml.saml2.core.StatusCode;
import org.opensaml.saml.saml2.metadata.SingleLogoutService;
import org.springframework.http.MediaType;
import org.springframework.webflow.execution.RequestContext;

/**
 * This is {@link SamlIdPSingleLogoutRedirectionStrategy}.
 *
 * @author Misagh Moayyed
 * @since 6.3.0
 */
@RequiredArgsConstructor
@Slf4j
public class SamlIdPSingleLogoutRedirectionStrategy implements LogoutRedirectionStrategy {
    private final SamlProfileHandlerConfigurationContext configurationContext;

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public boolean supports(final RequestContext context) {
        val logout = configurationContext.getCasProperties().getAuthn().getSamlIdp().getLogout();
        val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
        return logout.isSendLogoutResponse() && WebUtils.getRegisteredService(request) != null
            && WebUtils.getSingleLogoutRequest(request) != null;
    }

    @Override
    public void handle(final RequestContext context) {
        val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
        val decodedRequest = EncodingUtils.decodeBase64(WebUtils.getSingleLogoutRequest(request));
        val samlLogoutRequest = SamlUtils.transformSamlObject(configurationContext.getOpenSamlConfigBean(),
            decodedRequest, LogoutRequest.class);

        val logoutRequestIssuer = SamlIdPUtils.getIssuerFromSamlObject(samlLogoutRequest);
        val samlRegisteredService = (SamlRegisteredService) WebUtils.getRegisteredService(request);
        val adaptorRes = SamlRegisteredServiceServiceProviderMetadataFacade.get(
            configurationContext.getSamlRegisteredServiceCachingMetadataResolver(),
            samlRegisteredService, logoutRequestIssuer);

        if (adaptorRes.isEmpty()) {
            LOGGER.warn("Cannot find service provider metadata entity linked to [{}]", logoutRequestIssuer);
        } else {
            val adaptor = adaptorRes.get();
            val binding = determineLogoutResponseBindingType(samlRegisteredService);
            LOGGER.debug("Logout response binding type is determined as [{}]", binding);

            switch (StringUtils.defaultString(binding)) {
                case SAMLConstants.SAML2_POST_BINDING_URI:
                    handleSingleLogoutForPostBinding(context, samlLogoutRequest, samlRegisteredService, adaptor);
                    break;
                case SAMLConstants.SAML2_REDIRECT_BINDING_URI:
                    handleSingleLogoutForRedirectBinding(context, samlLogoutRequest, samlRegisteredService, adaptor);
                    break;
                default:
                    handleSingleLogoutForPostBinding(context, samlLogoutRequest, samlRegisteredService, adaptor);
                    handleSingleLogoutForRedirectBinding(context, samlLogoutRequest, samlRegisteredService, adaptor);
                    break;
            }
        }
    }

    /**
     * Determine logout response binding type string.
     *
     * @param samlRegisteredService the saml registered service
     * @return the string
     */
    protected String determineLogoutResponseBindingType(final SamlRegisteredService samlRegisteredService) {
        val logout = configurationContext.getCasProperties().getAuthn().getSamlIdp().getLogout();
        return StringUtils.defaultIfBlank(samlRegisteredService.getLogoutResponseBinding(), logout.getLogoutResponseBinding());
    }

    /**
     * Handle single logout for redirect binding.
     *
     * @param context               the context
     * @param samlLogoutRequest     the saml logout request
     * @param samlRegisteredService the saml registered service
     * @param adaptor               the adaptor
     */
    protected void handleSingleLogoutForRedirectBinding(final RequestContext context, final LogoutRequest samlLogoutRequest,
                                                        final SamlRegisteredService samlRegisteredService,
                                                        final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) {
        val sloService = adaptor.getSingleLogoutService(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
        if (sloService != null) {
            produceSamlLogoutResponseRedirect(adaptor, sloService, context, samlRegisteredService, samlLogoutRequest);
        }
    }

    /**
     * Handle single logout for post binding.
     *
     * @param context               the context
     * @param samlLogoutRequest     the saml logout request
     * @param samlRegisteredService the saml registered service
     * @param adaptor               the adaptor
     */
    protected void handleSingleLogoutForPostBinding(final RequestContext context, final LogoutRequest samlLogoutRequest,
                                                    final SamlRegisteredService samlRegisteredService,
                                                    final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) {
        var sloService = adaptor.getSingleLogoutService(SAMLConstants.SAML2_POST_BINDING_URI);
        if (sloService != null) {
            val logoutResponse = buildSamlLogoutResponse(adaptor, sloService, context, samlRegisteredService, samlLogoutRequest);
            postSamlLogoutResponse(sloService, logoutResponse, context);
        }
    }

    /**
     * Produce saml logout response redirect.
     *
     * @param adaptor           the adaptor
     * @param sloService        the slo service
     * @param context           the context
     * @param registeredService the registered service
     * @param logoutRequest     the logout request
     */
    @SneakyThrows
    protected void produceSamlLogoutResponseRedirect(final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
                                                     final SingleLogoutService sloService,
                                                     final RequestContext context,
                                                     final SamlRegisteredService registeredService,
                                                     final LogoutRequest logoutRequest) {
        val logoutResponse = buildSamlLogoutResponse(adaptor, sloService, context, registeredService, logoutRequest);
        val location = StringUtils.isBlank(sloService.getResponseLocation())
            ? sloService.getLocation()
            : sloService.getResponseLocation();
        LOGGER.trace("Encoding logout response given endpoint [{}] for binding [{}]", location, sloService.getBinding());
        val encoder = new SamlIdPHttpRedirectDeflateEncoder(location, logoutResponse);
        encoder.doEncode();
        val redirectUrl = encoder.getRedirectUrl();
        LOGGER.debug("Final logout redirect URL is [{}]", redirectUrl);

        val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
        WebUtils.putLogoutRedirectUrl(request, redirectUrl);
    }

    /**
     * Post saml logout response.
     *
     * @param sloService     the slo service
     * @param logoutResponse the logout response
     * @param requestContext the context
     */
    @SneakyThrows
    protected void postSamlLogoutResponse(final SingleLogoutService sloService, final LogoutResponse logoutResponse,
                                          final RequestContext requestContext) {
        val payload = SerializeSupport.nodeToString(XMLObjectSupport.marshall(logoutResponse));
        LOGGER.trace("Logout request payload is [{}]", payload);

        val message = EncodingUtils.encodeBase64(payload);
        LOGGER.trace("Logout message encoded in base64 is [{}]", message);

        val location = StringUtils.isBlank(sloService.getResponseLocation())
            ? sloService.getLocation()
            : sloService.getResponseLocation();
        LOGGER.debug("Sending logout response using [{}] binding to [{}]", sloService.getBinding(), location);
        HttpUtils.executePost(location,
            CollectionUtils.wrap(SamlProtocolConstants.PARAMETER_SAML_RESPONSE, message),
            CollectionUtils.wrap("Content-Type", MediaType.APPLICATION_XML_VALUE));
    }

    /**
     * Build saml logout response.
     *
     * @param adaptor           the adaptor
     * @param sloService        the slo service
     * @param requestContext    the context
     * @param registeredService the registered service
     * @param logoutRequest     the logout request
     * @return the logout response
     */
    protected LogoutResponse buildSamlLogoutResponse(final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
                                                     final SingleLogoutService sloService,
                                                     final RequestContext requestContext,
                                                     final SamlRegisteredService registeredService,
                                                     final LogoutRequest logoutRequest) {
        val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext);
        val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(requestContext);

        val id = '_' + String.valueOf(RandomUtils.nextLong());
        val builder = configurationContext.getLogoutResponseBuilder();
        val status = builder.newStatus(StatusCode.SUCCESS, "Success");
        val issuer = builder.newIssuer(configurationContext.getCasProperties().getAuthn().getSamlIdp().getEntityId());

        val location = StringUtils.isBlank(sloService.getResponseLocation())
            ? sloService.getLocation()
            : sloService.getResponseLocation();
        LOGGER.trace("Creating logout response for binding [{}] with issuer [{}], location [{}] and service provider [{}]",
            sloService.getBinding(), issuer, location, adaptor.getEntityId());
        val logoutResponse = builder.newLogoutResponse(id, location, issuer, status, adaptor.getEntityId());

        if (configurationContext.getCasProperties().getAuthn().getSamlIdp().getLogout().isSignLogoutResponse()) {
            LOGGER.trace("Signing logout request for service provider [{}]", adaptor.getEntityId());
            val logoutResponseSigned = configurationContext.getSamlObjectSigner()
                .encode(logoutResponse, registeredService, adaptor, response, request, sloService.getBinding(), logoutRequest);
            SamlUtils.logSamlObject(configurationContext.getOpenSamlConfigBean(), logoutResponseSigned);
            return logoutResponseSigned;
        }
        return logoutResponse;
    }
}


text:
<?php

class Google_Service_Dataflow_ShellTask extends Google_Model
{
  public $command;
  public $exitCode;

  public function setCommand($command)
  {
    $this->command = $command;
  }
  public function getCommand()
  {
    return $this->command;
  }
  public function setExitCode($exitCode)
  {
    $this->exitCode = $exitCode;
  }
  public function getExitCode()
  {
    return $this->exitCode;
  }
}


text:
module cql

####################################################################
# CQLConnection
####################################################################

type CQLConnection
  socket  :: Base.TcpSocket
  buffer  :: IOBuffer
  msg_id  :: Uint8
  replies :: Dict
  pending :: Int
end

####################################################################
# Connect & Disconnect
####################################################################

function connect(server::String = "localhost", port::Int = 9042)
  con = CQLConnection(Base.connect(server, port),
                      IOBuffer(), 1, Dict(), 0);
  sendMessage(con, 0x01, {"CQL_VERSION" => "3.0.0"});
  version, id, opcode, len = readServerMessage(con.socket);
  con.pending = 0;
  @assert version == 0x82
  @assert opcode  == 0x02
  @async handleServerMessages(con);
  con
end

function disconnect(con::CQLConnection)
  while 0 < con.pending
    yield();
  end
  close(con.socket);
  con.socket  = Base.TcpSocket();
  con.buffer  = IOBuffer();
  con.msg_id  = 1;
  con.replies = Dict();
  con.pending = 0;
  con
end

####################################################################
# Handle Server Messages
####################################################################

function readServerMessage(socket::Base.TcpSocket)
  version = read(socket, Uint8);
  flags   = read(socket, Uint8);
  id      = read(socket, Uint8);
  opcode  = read(socket, Uint8);
  len     = ntoh(read(socket, Uint32));
  (version, id, opcode, len)
end

function handleServerMessage(con::CQLConnection)
  version, id, opcode, len = readServerMessage(con.socket);
  if id > 0 then
    put!(pop!(con.replies, id),
         (opcode, readbytes(con.socket, len)));
  elseif opcode == 0x00 then
    kind   = ntoh(read(con.socket, Int32));
    strlen = ntoh(read(con.socket, Int16));
    println("ERROR [$kind] : ",
            bytestring(readbytes(con.socket, strlen)));
  else
    for _ in 1:len
      read(con.socket, Uint8);
    end
  end
  con.pending -= 1;
  nothing
end

function handleServerMessages(con::CQLConnection)
  while !eof(con.socket)
    try
      handleServerMessage(con);
    catch err
      isa(err, EOFError) ? nothing : throw(err);
    end
  end
  nothing
end

####################################################################
# UUID
####################################################################

type UUID
  val::Uint128
end

function UUID(str::String)
  UUID(parseint(Uint128, replace(str, '-', ""), 16))
end

function Base.print(io::IO, uuid::UUID)
  h = hex(uuid.val,32);
  print(io, "uuid\"");
  print(io, h[1:8]);
  print(io, "-");
  print(io, h[9:12]);
  print(io, "-");
  print(io, h[13:16]);
  print(io, "-");
  print(io, h[17:20]);
  print(io, "-");
  print(io, h[21:32]);
  print(io, "\"");
  nothing
end

Base.show (io::IO, uuid::UUID) = print(io, uuid);

macro uuid_str(p)
  UUID(p)
end

####################################################################
# Timestamp
####################################################################

type Timestamp
  milliseconds::Int64
end

const timeOffset = time(strptime("%F %T %z %Z",
                                 "1970-01-01 00:00:00 +0000 UTC"));

function Timestamp(str::String)
  Timestamp(1000 * int64(time(strptime("%F %T", str)) + timeOffset))
end

function Base.print(io::IO, t::Timestamp)
  print(io, "ts\"");
  print(io, strftime("%F %T", div(t.milliseconds, 1000)
                              - timeOffset));
  print(io, "\"");
  nothing
end

Base.show (io::IO, t::Timestamp) = print(io, t);

macro ts_str(p)
  Timestamp(p)
end

####################################################################
# Decoding
####################################################################

function decodeString(s::IO)
  strlen = ntoh(read(s, Int16));
  bytestring(readbytes(s, strlen));
end

function decodeResultSubColumn(s::IO, typ)
  nrOfBytes = ntoh(read(s, Int16));
  decodeValue(s, nrOfBytes, (typ, nothing, nothing))
end

function decodeList(s::IO, typ)
  nrOfElements = ntoh(read(s, Uint16));
  ar = Array(Any, nrOfElements);
  for ix in 1:nrOfElements
    ar[ix] = decodeResultSubColumn(s, typ);
  end
  ar
end

function decodeMap(s::IO, val_type)
  Set(decodeList(s, val_type))
end

function decodeDict(s::IO, key_type, val_type)
  d = Dict();
  nrOfElements = int(ntoh(read(s, Uint16)));
  for i in 1:nrOfElements
    key = decodeResultSubColumn(s, key_type);
    val = decodeResultSubColumn(s, val_type);
    d[key] = val;
  end
  d
end

function decodeValue(s::IO, nrOfBytes::Integer, types)
  type_kind, val_type, key_type = types;
  nrOfBytes < 0     ? nothing :
  type_kind == 0x02 ? ntoh(read(s, Uint64)) :
  type_kind == 0x09 ? int(ntoh(read(s, Uint32))) :
  type_kind == 0x0B ? (Timestamp(ntoh(read(s, Uint64)))) :
  type_kind == 0x0C ? (UUID(ntoh(read(s, Uint128)))) :
  type_kind == 0x0D ? bytestring(readbytes(s, nrOfBytes)) :
  type_kind == 0x20 ? decodeList(s, val_type) :
  type_kind == 0x21 ? decodeDict(s, key_type, val_type) :
  type_kind == 0x22 ? decodeMap(s, val_type) :
            ("*NYI*", type_kind, readbytes(s, nrOfBytes))
end

function decodeResultRowTypes(s::IOBuffer)
  flags   = ntoh(read(s, Uint32));
  colcnt  = ntoh(read(s, Uint32));
  gl_spec = (flags & 0x0001) != 0;

  if gl_spec then
    gl_ksname = decodeString(s);
    gl_tablename = decodeString(s);
  end
  if (flags & 0x0002) != 0 then
    println("d >> ");
  end
  if (flags & 0x0004) != 0 then
    println("e >> ");
  end
  types = Array((Int16,Any,Any), colcnt);
  for col in 1:colcnt
    ksname     = gl_spec ? gl_ksname : decodeString(s);
    tablename  = gl_spec ? gl_tablename : decodeString(s);
    name       = decodeString(s);
    kind       = ntoh(read(s, Uint16));
    key_type   = kind == 0x21 ?  ntoh(read(s, Uint16)) : nothing;
    sub_type   = kind in {0x20, 0x21, 0x22} ? ntoh(read(s, Uint16))
                                            : nothing;
    types[col] = (kind, sub_type, key_type);
  end
  types
end

function decodeResultColumn(s::IO, typ)
  nrOfBytes = ntoh(read(s, Int32));
  decodeValue(s, nrOfBytes, typ)
end

function decodeResultRows(s::IOBuffer)
  types = decodeResultRowTypes(s);
  nrOfColumns = length(types);
  nrOfRows = ntoh(read(s, Uint32));
  rows = Array(Array{Any}, nrOfRows)
  for rix = 1:nrOfRows
    rows[rix] = Array(Any, nrOfColumns);
    for cix in 1:nrOfColumns
      row[rix][cix] = decodeResultColumn(s, types[cix])
    end
  end
  rows
end

function decodeResultMessage(buffer::Array{Uint8})
  s = IOBuffer(buffer);
  kind = ntoh(read(s, Uint32));
  kind == 0x01 ? {"void"} :
  kind == 0x02 ? decodeResultRows(s) :
  kind == 0x03 ? {"set keyspace", decodeString(s)} :
  kind == 0x04 ? {"prepared"} :
  kind == 0x05 ? {"schema change", decodeString(s),
                  decodeString(s), decodeString(s)} :
       {"???"}
end

function decodeErrorMessage(buffer::Array{Uint8})
  s = IOBuffer(buffer);
  kind = ntoh(read(s, Uint32));
  errmsg = decodeString(s);
  println("ERROR [$kind]: ", errmsg);
  {"ERROR", kind, errmsg}
end

function decodeMessage(opcode::Uint8, buffer::Array{Uint8})
  opcode == 0x08 ? decodeResultMessage(buffer) :
  opcode == 0x00 ? decodeErrorMessage(buffer) :
         {opcode, buffer};
end

####################################################################
# Encoding
####################################################################

function cql_encode_string(buf::IOBuffer, str::String)
  encStr = bytestring(is_valid_utf8(str) ? str : utf8(str));
  write(buf, hton(uint16(sizeof(encStr))));
  write(buf, encStr);
  nothing
end

function cql_encode_long_string(buf::IOBuffer, str::String)
  encStr = bytestring(is_valid_utf8(str) ? str : utf8(str));
  write(buf, hton(uint32(sizeof(encStr))));
  write(buf, encStr);
  nothing
end

function cql_encode(buf::IOBuffer, dict::Dict)
  write(buf, hton(uint16(length(dict))));
  for (k,v) in dict
    cql_encode_string(buf, k);
    cql_encode_string(buf, v);
  end
  nothing
end

function cql_encode(buf::IOBuffer, query::String)
  cql_encode_long_string(buf, query);
  write(buf, 0x00);
  write(buf, 0x04);
  write(buf, 0x00);
  nothing
end

####################################################################
# Sending Message to the server
####################################################################

function sendMessageBody(con::CQLConnection, msg)
  buf = con.buffer;
  truncate(buf, 0);
  cql_encode(buf, msg);
  write(con.socket, hton(uint32(buf.size)));
  write(con.socket, takebuf_array(buf));
end

function sendMessage(con::CQLConnection, kind::Uint8, msg,
                     id::Uint8 = 0x00)
  con.pending += 1;
  write(con.socket, 0x02);
  write(con.socket, 0x00);
  write(con.socket, id);
  write(con.socket, kind);
  sendMessageBody(con, msg);

  flush(con.socket);
  yield();
  nothing
end

function nextReplyID(con::CQLConnection)
  id::Uint8 = con.msg_id;
  con.msg_id = 1 + (id + 1) % 99;
  while haskey(con.replies, id)
    yield();
  end
  reply = RemoteRef();
  con.replies[id] = reply;
  (id, reply)
end

####################################################################
# Queries
####################################################################

function query(con::CQLConnection, msg::String)
  sync(con);
  getResult(asyncQuery(con, msg))
end

function command(con::CQLConnection, msg::String)
  sync(con);
  asyncCommand(con, msg)
  sync(con);
  nothing
end

function asyncQuery(con::CQLConnection, msg::String)
  id, reply = nextReplyID(con);
  sendMessage(con, 0x07, msg, id);
  reply
end

function asyncCommand(con::CQLConnection, msg::String)
  sendMessage(con, 0x07, msg);
  nothing
end

function getResult(reply::RemoteRef)
  decodeMessage(take!(reply) ...)
end

function sync(con::CQLConnection)
  while 0 < con.pending
    yield();
  end
end

####################################################################

end


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29261_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans489.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">DRILTECH MWD SURVEY REPORT

Company: EOG RESOURCES Inc. Job Number: 2014-470-IDDT—ND Well: Parshall 88-3029H Vertical Section Plane: 133.01 Location: Mountrail County, North Dakota WELL API #: 33-061—03272 Rig: H&P 316 Tie Into: Gyro Survey's (MultiShot) Calculation Method Minimum Curvature Survey Survey lnclina- Course True Vertical Vertical Coordinates Closure Dogleg Build Tool Depth tion Section N/S ENV Distance Angle Severity Rate # Type (ft) (deg) (deg) (ft) (ft) (ft) (ft) (ft) (ft) (deg) (d/100') (d/100')

MWD HE148 MWD 151 MWD 154 MWD
MWD
m-
m166 167 MWD 170 MWD 173 MWD
m
"m
--—---————--——
-----——————_—_


text:
<?php

namespace Stratadox\Di\Test\Stub;

interface FooInterface
{
    public function doSomething();
}


text:
LG JS Frame
===============================

A chainable JS library filled with useful functions (including events, animations, dom and more).
It writes similar to jQuery since that is what most are used to and is an easy format.
Whats unique about it? Erm... ... er ... :P

```javascript
$lg('div.className > [href]').click(function(){
	$lg(this).fadeOut();
})
.append(' Click me to hide me!');
```

***For a full version of LG-JS-Frame with all modules, use the most recent LG-full.js or LG-full.min.js above***

Basics
-------------
#### Initiation
Initiate with the global '$lg' variable `$lg('selector')`
The returned object can now be manipulated using all the LG functions, and the matching elements can be access via index.
You can supply the $lg function with a number of different things;
* A CSS Selector: `$lg('div.content')` which optionally takes a second argument of a context. This is only available if selector.js is installed.
* A single element: `$lg(document.body)`
* A node list: `$lg(document.getElementsByClassName('content'))`
* An array of nodes: `$lg([div.childNodes[0], div.childNodes[1]])`
* Window or Document: `$lg(document) $lg(window)`
* A string of HTML: `$lg('<div id="test">Test Div</div>')` - This is only available if dom.js is installed.
* A HTML tag with properties: `$lg('div', {id: 'test', className: 'content', innerHTML: 'Test Div'})` - This is only available if dom.js is installed.
* Or even a document fragment ...

#### Selector.
The selector.js file in /src is a modified version of Avac-Selector-Engine tuned to work well with LG.
For information visit here: [https://github.com/AvacWeb/Avac-Selector-Engine](https://github.com/AvacWeb/Avac-Selector-Engine)
Alternatively, you can use your own or a preffered selector engine.

#### DOM Readiness.
LG does have a DOM ready function similar to that of JQuery.
`$lg(function(){ alert('DOM is ready!'); });`
You can check if the dom is loaded already, with the `$lg.isDomLoaded()` function.

Additionally, if you need to run all your dom ready functions again manually you can use this: `$lg.domReady.run(true)`
Forcing them to run regardless of dom state.

Updates/ Changelog
---------
* 31/3/2014
	- Released to public.


text:
{ Game   : RainbowSix.exe
  Version: 1.0
  Date   : 10-23-16
  Author : Brian Coffey

  Host Only

  Makes all players & hostage invincible. Also makes Blackbeard's shield invincible.
Note 1: enemymem might not be working properly due to patch 5.1. rest still works.
Note 2: Uncomment line 60 (enemymem,sub edx,#99) to make
regular terrorists 1 hit kill and bombers take 99 more damage per bullet.

}

[ENABLE]

aobscanmodule(INJECT_GOD_MODE,RainbowSix.RBcCollisionObject::SetFilterId+16F4,89 91 08 01 00 00 33 D2)
alloc(newmem_GodMode,2048,RainbowSix.RBcCollisionObject::SetFilterId+16F4)
stealtheditex(stealth,INJECT_GOD_MODE,1)

label(originalcode_godMode)
label(returnhere_godmode)
label(sedit_health)
label(_PlayerGodMode)
registersymbol(sedit_health)
registersymbol(_PlayerGodMode)
globalalloc(PlayerBase,4)
label(enemymem)
registersymbol(enemymem)
label(hostagemem)
registersymbol(hostagemem)
label(shield)
registersymbol(shield)

//======================================================

newmem_GodMode:

	//cmp dword [rcx+00000110],3FE79863
    cmp byte [rcx+00000110],63
    //mov [PlayerBase],rcx
    je _PlayerGodMode

    cmp byte [rcx+00000110],73
    je enemymem
    cmp byte [rcx+00000110],#222
    je hostagemem
    cmp byte [rcx+00000110],0
    je shield
	mov [rcx+00000108],edx
    jmp returnhere_godmode

// Blackbeard's Shield
shield:
   mov [rcx+00000108],#150
   mov [rcx+0000012C],bf000000
   jmp returnhere_godmode

enemymem:
    //sub edx,#99 // 1 hit terrorists. alternatively, change to mov edx,0 to it so enemies can't spawn
    mov [rcx+00000108],edx
    jmp returnhere_godmode

_PlayerGodMode:

       mov [rcx+00000108],#120 // mov (decimal)120 to health
       // to be used in other scripts
       // gives players extra strong rook armour
       mov [rcx+0000012C],bf000000
       jmp returnhere_godmode

hostagemem:
   mov [rcx+00000108],#150

originalcode_godMode:

	jmp returnhere_godmode

//enable:
//db 0

//======================================================

stealth:
sedit_health:
	jmp newmem_GodMode
	nop

returnhere_godmode:

[DISABLE]

sedit_health:
	mov [rcx+00000108],edx

unregistersymbol(stealthedit)
dealloc(newmem_GodMode)
dealloc(PlayerBase)


text:
import A11yDialog = require('a11y-dialog');

const dialogEl = new A11yDialog(document.getElementById("test"));
const dialogElTwo = new A11yDialog(document.getElementById("test"), document.getElementById("testContainer"));
const dialogElThree = new A11yDialog(document.getElementById("test"), "dummy-element");

dialogEl.show();
dialogEl.hide();
dialogElTwo.destroy();
dialogElThree.create();

// Test out interfaces that extends Element.
dialogEl.on("show", (el: HTMLElement) => {
    el.textContent;
});

// Test out element and event.
dialogEl.on("create", (el: HTMLElement, evt) => {
    el.textContent;

    evt.target;
});

dialogEl.on('hide', () => {
    const t = 5;
});

dialogEl.off("show", (el: HTMLElement) => {
    el.textContent;
});


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/openx_play_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/openx_play" />
</selector>


text:
using System.Collections.Generic;

namespace Umbraco.Core.Models.EntityBase
{
    public interface IUmbracoEntity : IAggregateRoot
    {
        /// <summary>
        /// Profile of the user who created this Entity
        /// </summary>
        int CreatorId { get; set; }

        /// <summary>
        /// Gets or sets the level of the Entity
        /// </summary>
        int Level { get; set; }

        /// <summary>
        /// Gets or Sets the Name of the Entity
        /// </summary>
        string Name { get; set; }

        /// <summary>
        /// Gets or sets the Id of the Parent Entity
        /// </summary>
        int ParentId { get; set; }

        /// <summary>
        /// Gets or sets the path to the Entity
        /// </summary>
        string Path { get; set; }

        /// <summary>
        /// Gets or sets the sort order of the Entity
        /// </summary>
        int SortOrder { get; set; }

        /// <summary>
        /// Boolean indicating whether this Entity is Trashed or not.
        /// If an Entity is Trashed it will be located in the Recyclebin.
        /// </summary>
        /// <remarks>
        /// When content is trashed it should be unpublished.
        /// Not all entities support being trashed, they'll always return false.
        /// </remarks>
        bool Trashed { get; }

        /// <summary>
        /// Some entities may expose additional data that other's might not, this custom data will be available in this collection
        /// </summary>
        IDictionary<string, object> AdditionalData { get; }
    }
}


text:
package org.meruvian.inca.struts2.test;

import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Assert;
import org.junit.Test;
import org.meruvian.inca.struts2.test.action.JsonOutputTestAction;
import org.meruvian.inca.struts2.test.action.model.TestActionModel;

/**
 * @author Dian Aditya
 *
 */
public class JsonOutputTest extends IncaJUnitTestCase<JsonOutputTestAction> {
	private ObjectMapper mapper = new ObjectMapper();

	@Test
	public void testJsonResponse() throws Exception {
		request.addHeader("Accept", "application/json");
		String result = executeAction("/json/responseonly");

		TestActionModel model = new TestActionModel();
		model.setName("Inca");
		model.setDescription("S2RestPlugin");

		Assert.assertEquals(mapper.writeValueAsString(model), result);
	}

	@Test
	public void testJsonParameter() throws Exception {
		TestActionModel model = new TestActionModel();
		model.setName("Inca");
		model.setDescription("S2RestPlugin");

		request.addHeader("Accept", "application/json");
		request.setContentType("application/json");
		request.setMethod("POST");
		request.setContent(mapper.writeValueAsBytes(model));

		String result = executeAction("/json/requestresponse");
		JsonOutputTestAction action = getAction();

		Assert.assertEquals("Inca", action.getModel().getName());
		Assert.assertEquals("S2RestPlugin", action.getModel().getDescription());
		Assert.assertEquals(mapper.writeValueAsString(model), result);
	}
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width" />
  <title>Build Testing</title>

Try it


text:
import GenericFormObject from '../lib/GenericFormObject'

export default class TagFormObject extends GenericFormObject {
  static get model() {
    return 'tag'
  }

  static get type() {
    return 'tags'
  }

  static get properties() {
    return [
      'name-de', 'keywords-de', 'explanations-de', 'name-en', 'keywords-en',
      'explanations-en', 'name-ar', 'keywords-ar', 'explanations-ar',
      'name-fa', 'keywords-fa', 'explanations-fa', 'name-fr', 'name-tr',
      'name-pl', 'name-ru'
    ]
  }

  static get formConfig() {
    return {
       'name-de': { type: 'string' },
       'keywords-de': { type: 'textarea' },
       'explanations-de': { type: 'textarea' },
       'name-en': { type: 'string' },
       'keywords-en': { type: 'textarea' },
       'explanations-en': { type: 'textarea' },
       'name-ar': { type: 'string' },
       'keywords-ar': { type: 'textarea' },
       'explanations-ar': { type: 'textarea' },
       'name-fa': { type: 'string' },
       'keywords-fa': { type: 'textarea' },
       'explanations-fa': { type: 'textarea' },
       'name-fr': { type: 'string' },
       'name-tr': { type: 'string' },
       'name-pl': { type: 'string' },
       'name-ru': { type: 'string' }
    }
  }

  static get requiredInputs() {
    return ['name-de', 'name-en']
  }

  validation() {
    this.applyRequiredInputs()
  }
}


text:
package com.bnmi.ourmap.web.actions;

import com.bnmi.ourmap.control.EasyDelegate;
import com.bnmi.ourmap.model.Hotspot;
import com.bnmi.ourmap.model.Map;
import com.bnmi.ourmap.model.Project;
import com.bnmi.ourmap.web.Constantes;
import com.inga.utils.SigarUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Manuel Camilo Cuesta
 */
public class NewHotspotDisplayMode extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        EasyDelegate del = (EasyDelegate) session.getAttribute(Constantes.DELEGATE);

        String formSubmited = SigarUtils.validarCadena( request.getParameter("formSubmited"));
        Integer mapid = (Integer) session.getAttribute("new_hotspot_map");
        Map m = del.getMap(mapid);
        Project p = del.getProject(m.getProjectId());
        request.setAttribute("mapid", mapid );
        request.setAttribute("map", m );
        request.setAttribute("project", p );

        NewHotspotForm.setNewHsStatus( request, 2 );

        Integer mapDisplayMode = m.getDisplayMode();
        if ( mapDisplayMode == null )
            mapDisplayMode = 0;

        // If the map display mode is not flexible, then skip this page
        if ( mapDisplayMode.intValue() != 0 )
            return mapping.findForward("add_content_new_do");

        if ( formSubmited == null )
        {

        }
        else
        {
            Integer displayMode = SigarUtils.parseInt( request.getParameter("displayMode"));
            Hotspot hs = (Hotspot) session.getAttribute("new_hotspot");
            hs.setDisplayMode( displayMode );

            return mapping.findForward("add_content_new_do");

        }

        return mapping.findForward("newhotspotdisplaymode");

    }

}


text:
package com.holonplatform.jaxrs.server.test;

import static org.junit.jupiter.api.Assertions.assertEquals;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import com.holonplatform.jaxrs.LogConfig;
import com.holonplatform.jaxrs.server.auth.AuthenticationFeature;
import com.holonplatform.test.JerseyTest5;

public class TestNoAuth extends JerseyTest5 {

	@BeforeAll
	static void setup() {
		LogConfig.setupLogging();
	}

	@Path("aresource")
	public static class AResource {

		@GET
		@Path("test")
		@Produces(MediaType.TEXT_PLAIN)
		public String test() {
			return "test";
		}

	}

	@Override
	protected Application configure() {
		return new ResourceConfig().register(AResource.class).register(AuthenticationFeature.class)
				.register(RolesAllowedDynamicFeature.class);
	}

	@Test
	public void testNoAuth() {
		String value = target("aresource/test").request().get(String.class);
		assertEquals("test", value);
	}

}


text:
/**
 * @file Chatサンプルアプリ起動スクリプト。
 */
import * as config from 'config';
import * as log4js from 'log4js';
import 'source-map-support/register';
import { createServer } from './ws';
const packagejson = require('../package.json');

// log4jsを初期設定
log4js.configure(config['log4js']);

// WebSocketサーバを起動
createServer(config['websocket'], "dist/ws");
log4js.getLogger('debug').info(`${packagejson['name']}@${packagejson['version']} started`);


text:
1;

addpath ("./common");

clear all;
close all;
clc;

h = figure (1);

hold on;
grid on;

title ("Generalization Bounds Comparison");
xlabel ("N");
ylabel ("{/Symbol e}");

% Number of examples
N = 1:10^4;

% Probability that epsilon will hold
delta = 0.05;

% VC dimension
dvc = 50;

% Plot the generalization bounds in term of N
semilogy (N, arrayfun (@ (n) vc (n, dvc, delta), N), "r-");
semilogy (N, arrayfun (@ (n) rademacher (n, dvc, delta), N), "b-");
semilogy (N, arrayfun (@ (n) parrondo (n, dvc, delta), N), "m-");
semilogy (N, arrayfun (@ (n) devroye (n, dvc, delta), N), "g-");

legend ("Original VC", "Rademacher", "Parrondo", "Devroye");

% Uncomment the following line in order to save the plot to a PNG file
% saveplot (h, 4, 3, "../img/plot_bounds.png");


text:
package com.github.typesafe_query.annotation;

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

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DefaultWhere{
	String value();
	boolean not() default false;
}


text:
from flask import Flask
from flask import render_template, redirect, url_for, jsonify

# CORS dependecies
from flask.ext.cors import CORS

app = Flask(__name__)

#CORS instance
cors = CORS(app, resources={r"/*": {"origins": "*"}}) #CORS :WARNING everything!

@app.route('/')
def home_page():
    return 'hello world'

@app.route('/all-scores/')
def get_scores():
    return 'Not Implemented'


text:
<?php

namespace Refear99\EasyMns;

use AliyunMNS\Model\MessageAttributes;
use AliyunMNS\Requests\PublishMessageRequest;

class Topic extends Mns
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 发送消息到 Topic
     *
     * @param string $topicName
     * @param array|string $message
     * @param null $messageTag
     * @param null $messageAttributes
     * @return array
     * @throws \Exception
     */
    public function publishMessage($topicName, $message, $messageTag = null, $messageAttributes = null)
    {
        try {
            if (is_array($message)) {
                $message = \GuzzleHttp\json_encode($message);
            } else if (is_string($message)) {
                $message = trim($message);
            } else {
                throw new \Exception('Invalid Message');
            }

            if ($messageAttributes) {
                $messageAttributes = new MessageAttributes($messageAttributes);
            }

            $request = new PublishMessageRequest($message, $messageTag, $messageAttributes);

            $result = $this->mns->getTopicRef($topicName)->publishMessage($request);

            if (!$result->isSucceed()) {
                throw new \Exception('Send Message Failed. Status Code ' . $result->getStatusCode());
            }

            return [
                'message_status_code' => $result->getStatusCode(),
                'message_id'          => $result->getMessageId(),
                'message_body_md5'    => $result->getMessageBodyMD5(),
            ];

        } catch (\Exception $e) {
            throw $e;
        }
    }
}


text:
import {MDCComponent} from '@material/base/component';
import {CustomEventListener, SpecificEventListener} from '@material/base/types';
import {MDCFloatingLabel, MDCFloatingLabelFactory} from '@material/floating-label/component';
import {MDCLineRipple, MDCLineRippleFactory} from '@material/line-ripple/component';
import * as menuSurfaceConstants from '@material/menu-surface/constants';
import {MDCMenu, MDCMenuFactory} from '@material/menu/component';
import * as menuConstants from '@material/menu/constants';
import {MDCMenuItemEvent} from '@material/menu/types';
import {MDCNotchedOutline, MDCNotchedOutlineFactory} from '@material/notched-outline/component';
import {MDCRippleAdapter} from '@material/ripple/adapter';
import {MDCRipple} from '@material/ripple/component';
import {MDCRippleFoundation} from '@material/ripple/foundation';
import {MDCSelectAdapter} from './adapter';
import {cssClasses, strings} from './constants';
import {MDCSelectFoundation} from './foundation';
import {MDCSelectHelperText, MDCSelectHelperTextFactory} from './helper-text/component';
import {MDCSelectIcon, MDCSelectIconFactory} from './icon/component';
import {MDCSelectEventDetail, MDCSelectFoundationMap} from './types';

export class MDCSelect extends MDCComponent<MDCSelectFoundation> {
  static override attachTo(root: Element): MDCSelect {
    return new MDCSelect(root);
  }

  private ripple!: MDCRipple|null;

  private menu!: MDCMenu;  // assigned in menuSetup()

  private selectAnchor!: HTMLElement;       // assigned in initialize()
  private selectedText!: HTMLElement;       // assigned in initialize()
  private hiddenInput!: HTMLInputElement|null;  // assigned in initialize()

  private menuElement!: Element;                  // assigned in menuSetup()
  private menuItemValues!: string[];              // assigned in menuSetup()
  private leadingIcon?: MDCSelectIcon;            // assigned in initialize()
  private helperText!: MDCSelectHelperText|null;  // assigned in initialize()
  private lineRipple!: MDCLineRipple|null;        // assigned in initialize()
  private label!: MDCFloatingLabel|null;          // assigned in initialize()
  private outline!: MDCNotchedOutline|null;       // assigned in initialize()

  // Event handlers
  private handleFocus!: SpecificEventListener<'focus'>;
  private handleBlur!: SpecificEventListener<'blur'>;
  private handleClick!: SpecificEventListener<'click'>;
  private handleKeydown!: SpecificEventListener<'keydown'>;
  private handleMenuOpened!: EventListener;
  private handleMenuClosed!: EventListener;
  private handleMenuClosing!: EventListener;
  private handleMenuItemAction!: CustomEventListener<MDCMenuItemEvent>;

  override initialize(
      labelFactory: MDCFloatingLabelFactory = (el) => new MDCFloatingLabel(el),
      lineRippleFactory: MDCLineRippleFactory = (el) => new MDCLineRipple(el),
      outlineFactory:
          MDCNotchedOutlineFactory = (el) => new MDCNotchedOutline(el),
      menuFactory: MDCMenuFactory = (el) => new MDCMenu(el),
      iconFactory: MDCSelectIconFactory = (el) => new MDCSelectIcon(el),
      helperTextFactory:
          MDCSelectHelperTextFactory = (el) => new MDCSelectHelperText(el),
  ) {
    this.selectAnchor =
        this.root.querySelector(strings.SELECT_ANCHOR_SELECTOR) as HTMLElement;
    this.selectedText =
        this.root.querySelector(strings.SELECTED_TEXT_SELECTOR) as HTMLElement;
    this.hiddenInput = this.root.querySelector(strings.HIDDEN_INPUT_SELECTOR) as
        HTMLInputElement;

    if (!this.selectedText) {
      throw new Error(
          'MDCSelect: Missing required element: The following selector must be present: ' +
          `'${strings.SELECTED_TEXT_SELECTOR}'`,
      );
    }

    if (this.selectAnchor.hasAttribute(strings.ARIA_CONTROLS)) {
      const helperTextElement = document.getElementById(
          this.selectAnchor.getAttribute(strings.ARIA_CONTROLS)!);
      if (helperTextElement) {
        this.helperText = helperTextFactory(helperTextElement);
      }
    }

    this.menuSetup(menuFactory);

    const labelElement = this.root.querySelector(strings.LABEL_SELECTOR);
    this.label = labelElement ? labelFactory(labelElement) : null;

    const lineRippleElement =
        this.root.querySelector(strings.LINE_RIPPLE_SELECTOR);
    this.lineRipple =
        lineRippleElement ? lineRippleFactory(lineRippleElement) : null;

    const outlineElement = this.root.querySelector(strings.OUTLINE_SELECTOR);
    this.outline = outlineElement ? outlineFactory(outlineElement) : null;

    const leadingIcon = this.root.querySelector(strings.LEADING_ICON_SELECTOR);
    if (leadingIcon) {
      this.leadingIcon = iconFactory(leadingIcon);
    }

    if (!this.root.classList.contains(cssClasses.OUTLINED)) {
      this.ripple = this.createRipple();
    }
  }

  /**
   * Initializes the select's event listeners and internal state based
   * on the environment's state.
   */
  override initialSyncWithDOM() {
    this.handleFocus = () => {
      this.foundation.handleFocus();
    };
    this.handleBlur = () => {
      this.foundation.handleBlur();
    };
    this.handleClick = (evt) => {
      this.selectAnchor.focus();
      this.foundation.handleClick(this.getNormalizedXCoordinate(evt));
    };
    this.handleKeydown = (evt) => {
      this.foundation.handleKeydown(evt);
    };
    this.handleMenuItemAction = (evt) => {
      this.foundation.handleMenuItemAction(evt.detail.index);
    };
    this.handleMenuOpened = () => {
      this.foundation.handleMenuOpened();
    };
    this.handleMenuClosed = () => {
      this.foundation.handleMenuClosed();
    };
    this.handleMenuClosing = () => {
      this.foundation.handleMenuClosing();
    };

    this.selectAnchor.addEventListener('focus', this.handleFocus);
    this.selectAnchor.addEventListener('blur', this.handleBlur);

    this.selectAnchor.addEventListener(
        'click', this.handleClick as EventListener);

    this.selectAnchor.addEventListener('keydown', this.handleKeydown);
    this.menu.listen(
        menuSurfaceConstants.strings.CLOSED_EVENT, this.handleMenuClosed);
    this.menu.listen(
        menuSurfaceConstants.strings.CLOSING_EVENT, this.handleMenuClosing);
    this.menu.listen(
        menuSurfaceConstants.strings.OPENED_EVENT, this.handleMenuOpened);
    this.menu.listen(
        menuConstants.strings.SELECTED_EVENT, this.handleMenuItemAction);

    if (this.hiddenInput) {
      if (this.hiddenInput.value) {
        // If the hidden input already has a value, use it to restore the
        // select's value. This can happen e.g. if the user goes back or (in
        // some browsers) refreshes the page.
        this.foundation.setValue(
            this.hiddenInput.value, /** skipNotify */ true);
        this.foundation.layout();
        return;
      }

      this.hiddenInput.value = this.value;
    }
  }

  override destroy() {
    this.selectAnchor.removeEventListener('focus', this.handleFocus);
    this.selectAnchor.removeEventListener('blur', this.handleBlur);
    this.selectAnchor.removeEventListener('keydown', this.handleKeydown);
    this.selectAnchor.removeEventListener(
        'click', this.handleClick as EventListener);

    this.menu.unlisten(
        menuSurfaceConstants.strings.CLOSED_EVENT, this.handleMenuClosed);
    this.menu.unlisten(
        menuSurfaceConstants.strings.OPENED_EVENT, this.handleMenuOpened);
    this.menu.unlisten(
        menuConstants.strings.SELECTED_EVENT, this.handleMenuItemAction);
    this.menu.destroy();

    if (this.ripple) {
      this.ripple.destroy();
    }
    if (this.outline) {
      this.outline.destroy();
    }
    if (this.leadingIcon) {
      this.leadingIcon.destroy();
    }
    if (this.helperText) {
      this.helperText.destroy();
    }

    super.destroy();
  }

  get value(): string {
    return this.foundation.getValue();
  }

  set value(value: string) {
    this.foundation.setValue(value);
  }

  setValue(value: string, skipNotify = false) {
    this.foundation.setValue(value, skipNotify);
  }

  get selectedIndex(): number {
    return this.foundation.getSelectedIndex();
  }

  set selectedIndex(selectedIndex: number) {
    this.foundation.setSelectedIndex(selectedIndex, /* closeMenu */ true);
  }

  setSelectedIndex(selectedIndex: number, skipNotify = false) {
    this.foundation.setSelectedIndex(
        selectedIndex, /* closeMenu */ true, skipNotify);
  }

  get disabled(): boolean {
    return this.foundation.getDisabled();
  }

  set disabled(disabled: boolean) {
    this.foundation.setDisabled(disabled);
    if (this.hiddenInput) {
      this.hiddenInput.disabled = disabled;
    }
  }

  set leadingIconAriaLabel(label: string) {
    this.foundation.setLeadingIconAriaLabel(label);
  }

  /**
   * Sets the text content of the leading icon.
   */
  set leadingIconContent(content: string) {
    this.foundation.setLeadingIconContent(content);
  }

  /**
   * Sets the text content of the helper text.
   */
  set helperTextContent(content: string) {
    this.foundation.setHelperTextContent(content);
  }

  /**
   * Enables or disables the default validation scheme where a required select
   * must be non-empty. Set to false for custom validation.
   * @param useDefaultValidation Set this to false to ignore default
   *     validation scheme.
   */
  set useDefaultValidation(useDefaultValidation: boolean) {
    this.foundation.setUseDefaultValidation(useDefaultValidation);
  }

  /**
   * Sets the current invalid state of the select.
   */
  set valid(isValid: boolean) {
    this.foundation.setValid(isValid);
  }

  /**
   * Checks if the select is in a valid state.
   */
  get valid(): boolean {
    return this.foundation.isValid();
  }

  /**
   * Sets the control to the required state.
   */
  set required(isRequired: boolean) {
    this.foundation.setRequired(isRequired);
  }

  /**
   * Returns whether the select is required.
   */
  get required(): boolean {
    return this.foundation.getRequired();
  }

  /**
   * Re-calculates if the notched outline should be notched and if the label
   * should float.
   */
  layout() {
    this.foundation.layout();
  }

  /**
   * Synchronizes the list of options with the state of the foundation. Call
   * this whenever menu options are dynamically updated.
   */
  layoutOptions() {
    this.foundation.layoutOptions();
    this.menu.layout();
    // Update cached menuItemValues for adapter.
    this.menuItemValues =
        this.menu.items.map((el) => el.getAttribute(strings.VALUE_ATTR) || '');

    if (this.hiddenInput) {
      this.hiddenInput.value = this.value;
    }
  }

  override getDefaultFoundation() {
    // DO NOT INLINE this variable. For backward compatibility, foundations take a Partial<MDCFooAdapter>.
    // To ensure we don't accidentally omit any methods, we need a separate, strongly typed adapter variable.
    const adapter: MDCSelectAdapter = {
      ...this.getSelectAdapterMethods(),
      ...this.getCommonAdapterMethods(),
      ...this.getOutlineAdapterMethods(),
      ...this.getLabelAdapterMethods(),
    };
    return new MDCSelectFoundation(adapter, this.getFoundationMap());
  }

  /**
   * Handles setup for the menu.
   */
  private menuSetup(menuFactory: MDCMenuFactory) {
    this.menuElement = this.root.querySelector(strings.MENU_SELECTOR)!;
    this.menu = menuFactory(this.menuElement);
    this.menu.hasTypeahead = true;
    this.menu.singleSelection = true;
    this.menuItemValues =
        this.menu.items.map((el) => el.getAttribute(strings.VALUE_ATTR) || '');
  }

  private createRipple(): MDCRipple {
    // DO NOT INLINE this variable. For backward compatibility, foundations take a Partial<MDCFooAdapter>.
    // To ensure we don't accidentally omit any methods, we need a separate, strongly typed adapter variable.
    // tslint:disable:object-literal-sort-keys Methods should be in the same order as the adapter interface.
    const adapter: MDCRippleAdapter = {
      ...MDCRipple.createAdapter({root: this.selectAnchor}),
      registerInteractionHandler: (evtType, handler) => {
        this.selectAnchor.addEventListener(evtType, handler);
      },
      deregisterInteractionHandler: (evtType, handler) => {
        this.selectAnchor.removeEventListener(evtType, handler);
      },
    };
    // tslint:enable:object-literal-sort-keys
    return new MDCRipple(this.selectAnchor, new MDCRippleFoundation(adapter));
  }

  private getSelectAdapterMethods() {
    // tslint:disable:object-literal-sort-keys Methods should be in the same order as the adapter interface.
    return {
      getMenuItemAttr: (menuItem: Element, attr: string) =>
          menuItem.getAttribute(attr),
      setSelectedText: (text: string) => {
        this.selectedText.textContent = text;

        let index = this.menu.selectedIndex;
        if (index === -1) return;
        index = index instanceof Array ? index[0] : index;
        const selectedItem = (this.menu.items[index] as HTMLElement);
        if (!selectedItem) return;
        this.selectedText.setAttribute(
            'aria-label', selectedItem.getAttribute('aria-label') || '');
      },
      isSelectAnchorFocused: () => document.activeElement === this.selectAnchor,
      getSelectAnchorAttr: (attr: string) =>
          this.selectAnchor.getAttribute(attr),
      setSelectAnchorAttr: (attr: string, value: string) => {
        this.selectAnchor.setAttribute(attr, value);
      },
      removeSelectAnchorAttr: (attr: string) => {
        this.selectAnchor.removeAttribute(attr);
      },
      addMenuClass: (className: string) => {
        this.menuElement.classList.add(className);
      },
      removeMenuClass: (className: string) => {
        this.menuElement.classList.remove(className);
      },
      openMenu: () => {
        this.menu.open = true;
      },
      closeMenu: () => {
        this.menu.open = false;
      },
      getAnchorElement: () =>
          this.root.querySelector(strings.SELECT_ANCHOR_SELECTOR)!,
      setMenuAnchorElement: (anchorEl: HTMLElement) => {
        this.menu.setAnchorElement(anchorEl);
      },
      setMenuAnchorCorner: (anchorCorner: menuSurfaceConstants.Corner) => {
        this.menu.setAnchorCorner(anchorCorner);
      },
      setMenuWrapFocus: (wrapFocus: boolean) => {
        this.menu.wrapFocus = wrapFocus;
      },
      getSelectedIndex: () => {
        const index = this.menu.selectedIndex;
        return index instanceof Array ? index[0] : index;
      },
      setSelectedIndex: (index: number) => {
        this.menu.selectedIndex = index;
      },
      focusMenuItemAtIndex: (index: number) => {
        (this.menu.items[index] as HTMLElement).focus();
      },
      getMenuItemCount: () => this.menu.items.length,
      // Cache menu item values. layoutOptions() updates this cache.
      getMenuItemValues: () => this.menuItemValues,
      getMenuItemTextAtIndex: (index: number) =>
          this.menu.getPrimaryTextAtIndex(index),
      isTypeaheadInProgress: () => this.menu.typeaheadInProgress,
      typeaheadMatchItem: (nextChar: string, startingIndex: number) =>
          this.menu.typeaheadMatchItem(nextChar, startingIndex),
    };
    // tslint:enable:object-literal-sort-keys
  }

  private getCommonAdapterMethods() {
    // tslint:disable:object-literal-sort-keys Methods should be in the same order as the adapter interface.
    return {
      addClass: (className: string) => {
        this.root.classList.add(className);
      },
      removeClass: (className: string) => {
        this.root.classList.remove(className);
      },
      hasClass: (className: string) => this.root.classList.contains(className),
      setRippleCenter: (normalizedX: number) => {
        this.lineRipple && this.lineRipple.setRippleCenter(normalizedX)
      },
      activateBottomLine: () => {
        this.lineRipple && this.lineRipple.activate();
      },
      deactivateBottomLine: () => {
        this.lineRipple && this.lineRipple.deactivate();
      },
      notifyChange: (value: string) => {
        if (this.hiddenInput) {
          this.hiddenInput.value = value;
        }

        const index = this.selectedIndex;
        this.emit<MDCSelectEventDetail>(
            strings.CHANGE_EVENT, {value, index}, true /* shouldBubble  */);
      },
    };
    // tslint:enable:object-literal-sort-keys
  }

  private getOutlineAdapterMethods() {
    // tslint:disable:object-literal-sort-keys Methods should be in the same order as the adapter interface.
    return {
      hasOutline: () => Boolean(this.outline),
      notchOutline: (labelWidth: number) => {
        this.outline && this.outline.notch(labelWidth);
      },
      closeOutline: () => {
        this.outline && this.outline.closeNotch();
      },
    };
    // tslint:enable:object-literal-sort-keys
  }

  private getLabelAdapterMethods() {
    // tslint:disable:object-literal-sort-keys Methods should be in the same order as the adapter interface.
    return {
      hasLabel: () => !!this.label,
      floatLabel: (shouldFloat: boolean) => {
        this.label && this.label.float(shouldFloat);
      },
      getLabelWidth: () => this.label ? this.label.getWidth() : 0,
      setLabelRequired: (isRequired: boolean) => {
        this.label && this.label.setRequired(isRequired);
      },
    };
    // tslint:enable:object-literal-sort-keys
  }

  /**
   * Calculates where the line ripple should start based on the x coordinate within the component.
   */
  private getNormalizedXCoordinate(evt: MouseEvent|TouchEvent): number {
    const targetClientRect = (evt.target as Element).getBoundingClientRect();
    const xCoordinate =
        this.isTouchEvent(evt) ? evt.touches[0].clientX : evt.clientX;
    return xCoordinate - targetClientRect.left;
  }

  private isTouchEvent(evt: MouseEvent|TouchEvent): evt is TouchEvent {
    return Boolean((evt as TouchEvent).touches);
  }

  /**
   * Returns a map of all subcomponents to subfoundations.
   */
  private getFoundationMap(): Partial<MDCSelectFoundationMap> {
    return {
      helperText: this.helperText ? this.helperText.foundationForSelect :
                                    undefined,
      leadingIcon: this.leadingIcon ? this.leadingIcon.foundationForSelect :
                                      undefined,
    };
  }
}


text:
import { Component }   from '@angular/core';
import { Router }      from '@angular/router';

import { AuthService } from './auth.service';

@Component({
  template: `

      <form class="center-block" (ngSubmit)="login()" #loginForm="ngForm">

          帐号
          <input type="text" class="form-control" [(ngModel)]="user.name" name="name" placeholder="员工账号">

          密码
          <input type="password" class="form-control" [(ngModel)]="user.password" name="password" placeholder="密码">

        <button type="submit" class="btn">登录</button>
      </form>

  `,
  styles: [`
    .wrapper {
      background-color: #383B42;
      position: fixed;
      width: 100%;
      height: 100%;
    }

    form {
      width: 500px;
      margin: 100px auto;
      padding: 30px 80px 50px;
      background-color: #fff;
      border: 1px solid #ddd;
      border-radius: 10px;
    }

    button {
      width: 100%;
      background-color: #18a689;
      color: #fff;
      margin-top: 20px;
    }

    button:hover {
      color: #fff;
    }
  `]
})

export class LoginComponent {
  user = { name: '', password: '' };
  constructor(public authService:AuthService, public router:Router) {}

  login() {
    this.authService.login().subscribe(() => {
      if(this.authService.isLoggedIn) {
        let url = this.authService.redirectUrl ? this.authService.redirectUrl : '/admin';
        this.router.navigate([url]);
      }
    });
  }
}


text:
require 'rack/test'
module RSpecMixin
  include Rack::Test::Methods

  def app
    MpWeixin::Server
  end
end


text:
package com.doctor.reflect;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Call stack introspection
 *
 * @author sdcuike
 *
 *         Created At 2016年8月29日 下午9:40:35
 */
public class CallStackIntrospectionDemo {
    private static final MyLogger logger = new LoggerImpl();

    public static void main(String[] args) {
        logger.logRecord("hello");

        IllegalArgumentException exception = new IllegalArgumentException("IllegalArgumentException");
        logger.logProblem("throwable", exception);
    }

    public interface MyLogger {
        // Types for log records
        int ERROR   = 0;
        int WARNING = 100;
        int STATUS  = 200;
        int DEBUG   = 300;
        int TRACE   = 400;

        void logRecord(String message);

        void logProblem(String message, Throwable throwable);
    }

    public static class LoggerImpl implements MyLogger {

        @Override
        public void logRecord(String message) {
            Throwable throwable = new Throwable();
            log(message, throwable.getStackTrace()[1]);
        }

        @Override
        public void logProblem(String message, Throwable throwable) {
            StringWriter out = new StringWriter();
            PrintWriter writer = new PrintWriter(out);
            writer.println();
            throwable.printStackTrace(writer);
            writer.flush();
            writer.close();
            log(message + out.toString(), throwable.getStackTrace()[0]);
        }

        private void log(String message, StackTraceElement stackTraceElement) {
            String className = stackTraceElement.getClassName();
            String methodName = stackTraceElement.getMethodName();
            int lineNumber = stackTraceElement.getLineNumber();
            System.out.println(String.join("  ", "模拟打印日志:", methodName, className, "" + lineNumber, message));
        }

    }
}


text:
/* 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.activiti.form.engine;

import org.activiti.form.api.FormRepositoryService;
import org.activiti.form.api.FormService;

public interface FormEngine {

    /**
     * the version of the activiti form library
     */
    public static String VERSION = "1.0.0.0"; // Note the extra .x at the end. To cater for snapshot releases with different database changes

    /**
     * The name as specified in 'process-engine-name' in the activiti.cfg.xml configuration file. The default name for a process engine is 'default
     */
    String getName();

    void close();

    FormRepositoryService getFormRepositoryService();

    FormService getFormService();

    FormEngineConfiguration getFormEngineConfiguration();
}