text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using CsQuery;

namespace DramaTracer.Utilites
{
    class clsHttp
    {
        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Windows NT 5.2; Windows NT 6.0; Windows NT 6.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; MS-RTC LM 8; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 4.0C; .NET CLR 4.0E)";
        private static CookieContainer cookiesBox;
        private bool bLogin;
        private WebProxy proxy;
        private NetworkCredential netCredentail;
        public string UserName
        { get; set; }
        public string Password
        { get; set; }
        public string BaseUrl
        { get; set; }
        public string ProxyHost
        { get; set; }
        public List<DBEpisode> Links
        { get; private set; }
        public string Title
        { get; private set; }
        public clsHttp()
        {
            bLogin = false;
            cookiesBox = null;
            proxy = null;
            netCredentail = null;
        }

        private HttpWebRequest CreateWebRequest(string url, bool bget)
        {
            WebRequest myWebRequest = WebRequest.Create(url);
            HttpWebRequest httpWebReq = (HttpWebRequest)myWebRequest;
            myWebRequest.Timeout=10000;
            if (bget)
            {
                myWebRequest.Method = "GET";
            }
            else
            {
                myWebRequest.Method = "POST";
            }

            httpWebReq.UserAgent = DefaultUserAgent;

            if (cookiesBox != null)
            {
                httpWebReq.CookieContainer = cookiesBox;
            }

            if (netCredentail != null)
            {
                myWebRequest.Credentials = netCredentail;
            }

            if (proxy != null)
            {
                myWebRequest.Proxy = proxy;
                if (netCredentail != null)
                    myWebRequest.Proxy.Credentials = netCredentail;
            }

            return httpWebReq;
        }

        private void DoLogin(string urlBase, string urlLogin, string sParam)
        {
            // pass 417 error
            System.Net.ServicePointManager.Expect100Continue = false;
            HttpWebRequest myHttpWebRequest = CreateWebRequest(urlLogin, false);
            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

            cookiesBox = new CookieContainer();
            myHttpWebRequest.CookieContainer = cookiesBox;
            string param = sParam;
            byte[] bs = Encoding.ASCII.GetBytes(param);

            using (Stream reqStream = myHttpWebRequest.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
            }

            using (WebResponse response = myHttpWebRequest.GetResponse())
            {
                netCredentail = new NetworkCredential(UserName, Password, urlBase);
            }
            bLogin = true;
        }

        private HttpWebRequest Get(string url)
        {
            if (!bLogin)
            {
                //site yyets need to login to see the drama links
                if (url.IndexOf("yyets") > 0)
                {
                    DoLogin("http://www.yyets.com",
                            "http://www.yyets.com/user/login/ajaxLogin",
                            "type=nickname&account=" + UserName + "&password=" + Password + "&remember=1");
                }
            }
            return CreateWebRequest(url, true);
        }

        public string GetText(string url)
        {
            string strHtml = string.Empty;
            var myHttpWebRequest = Get(url);

            using (WebResponse myWebResponse = myHttpWebRequest.GetResponse())
            {
                using (Stream myStream = myWebResponse.GetResponseStream())
                {
                    using (StreamReader myStreamReader = new StreamReader(myStream))
                    {
                        strHtml = myStreamReader.ReadToEnd();
                    }
                }
            }
            return strHtml;
        }

        public Stream GetStream(string url)
        {
            Stream sRet = null;
            try
            {
                var myHttpWebRequest = Get(url);
                WebResponse myWebResponse = myHttpWebRequest.GetResponse();
                sRet = myWebResponse.GetResponseStream();
            }
            catch
            {
            }
            return sRet;
        }

        private void ParserYYets(CQ doc)
        {
            if (null != Links)
            {
                Links.Clear();
                Links = null;
            }
            Links = new List<DBEpisode>();
            string[] str = System.Web.HttpUtility.HtmlDecode(doc.Select("title")[0].InnerText).Split(',');
            this.Title = str[0] + "," + str[1];
            var items = doc.Select("ul[class=resod_list]");
            foreach (IDomElement item in items)
            {
                var season = item.GetAttribute("season");
                if (season.CompareTo("103") == 0)
                    season = "預告片區";
                else
                    season = "第 " + season + " 季";
                foreach (IDomElement epi in item.ChildElements)
                {
                    var format = epi.GetAttribute("format");
                    var epiIdx = epi.GetAttribute("episode");
                    var title = epi.ChildElements.ElementAt(0).ChildElements.ElementAt(1).ChildElements.ElementAt(0).GetAttribute("title");
                    var downloads = epi.ChildElements.ElementAt(1).ChildElements.ElementAt(0);
                    foreach (var download in downloads.ChildElements)
                    {
                        if (download.NodeName.ToLower() == "a")
                        {
                            var href = download.GetAttribute("href");
                            if ((href == null) || (href.Length <= 0))
                                continue;
                            var kind = System.Web.HttpUtility.HtmlDecode(download.InnerText);
                            var dbepi = new DBEpisode();
                            dbepi.Format = format;
                            dbepi.Link = href;
                            dbepi.Name = title;
                            dbepi.Season = season;
                            dbepi.Kind = kind;
                            Links.Add(dbepi);
                        }
                    }
                }
            }
        }

        public void Parser(string url)
        {
            /*
             * if XML parser use by XmlDocument
             * will be Internal Server Error(500) .
             * so here we use CsQuery class
             */
            try
            {
                if ((url == null) || (url.Length <= 0))
                    return;
#if DEBUG
            var fs = System.IO.File.Open("11.html", FileMode.Open);
            var reader = new StreamReader(fs);
            var doc = CQ.Create(reader);
#else
            var doc = CQ.Create(GetStream(url));
#endif
            if (url.ToLower().IndexOf("yyets") > 0)
                ParserYYets(doc);
#if DEBUG
            fs.Close();
#endif
            }
            catch { }
        }

    }

    // list class for http
    class lstHttp
    {
        private List<clsHttp> Https
        { get; set; }

        public lstHttp()
        {
            Https = new List<clsHttp>();
        }

        public clsHttp Get(string url)
        {
            clsHttp ret = null;
            string baseUrl = GetBaseUrl(url);
            // searching http by base url
            foreach(clsHttp http in Https)
            {
                if (http.BaseUrl.CompareTo(baseUrl) == 0)
                {
                    ret = http;
                    break;
                }
            }
            // if not found, then create
            if (ret == null)
            {
                ret = new clsHttp();
                ret.BaseUrl = baseUrl;
                Https.Add(ret);
            }

            return ret;
        }

        private string GetBaseUrl(string url)
        {
            Uri temp = new Uri(url);
            // reurn host name
            return temp.Host.ToLower();
        }
    }
}


text:
package pl.grzegorz2047.testapi;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;

/**
 *
 * @author Grzegorz
 */
public class OnChat implements Listener {

    Test plugin;

    public OnChat(Test plugin){
        this.plugin = plugin;
    }

    @EventHandler
    void onChatListener(AsyncPlayerChatEvent e){
        Player p = e.getPlayer();
        if(!this.plugin.allowSpecChat){
            if((p.isWhitelisted() && this.plugin.allowWhitelist) || (this.plugin.lista.contains(p.getName()))){
                return;
            }else{
                p.sendMessage(this.plugin.noChatPerm);
                e.setCancelled(true);
            }
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
package edu.gemini.qpt.core.util;

import java.util.Date;
import java.util.logging.Logger;

import edu.gemini.qpt.shared.util.TimeUtils;
import edu.gemini.spModel.core.Site;
import jsky.coords.WorldCoords;
import edu.gemini.qpt.shared.sp.Obs;

public abstract class ElevationConstraintSolver extends Solver {

	@SuppressWarnings("unused")
	private static final Logger LOGGER = Logger.getLogger(ElevationConstraintSolver.class.getName());

	protected final ImprovedSkyCalc calc;
	protected final WorldCoords coords;
	protected final double min, max;

	protected ElevationConstraintSolver(Site site, WorldCoords coords, double min, double max) {
		super(TimeUtils.MS_PER_HOUR / 4, TimeUtils.MS_PER_MINUTE);
		this.coords = coords;
		this.calc = new ImprovedSkyCalc(site);
		this.max = max;
		this.min = min;
	}

	public static ElevationConstraintSolver forObs(Site site, Obs obs) {
		switch (obs.getElevationConstraintType()) {
		case AIRMASS:    return new AirmassSolver(site, obs);
		case HOUR_ANGLE: return new HourAngleSolver(site, obs);
		case NONE:       return new AirmassSolver(site, obs, 1.0, 2.0);
		default:
			throw new Error("Unknown ElevationConstraintType: " + obs.getElevationConstraintType());
		}
	}

	static class AirmassSolver extends ElevationConstraintSolver {

		protected AirmassSolver(Site site, Obs obs) {
			super(site, obs.getCoords(), obs.getElevationConstraintMin(), obs.getElevationConstraintMax());
		}

		protected AirmassSolver(Site site, Obs obs, double min, double max) {
			super(site, obs.getCoords(), min, max);
		}

		@Override
		protected boolean f(long t) {
			calc.calculate(coords, new Date(t), false);
			double airmass = calc.getAirmass();
			return (min <= airmass) && (airmass <= max);
		}

	}

	static class HourAngleSolver extends ElevationConstraintSolver {

		protected HourAngleSolver(Site site, Obs obs) {
			super(site, obs.getCoords(), obs.getElevationConstraintMin(), obs.getElevationConstraintMax());
		}

		@Override
		protected boolean f(long t) {
			calc.calculate(coords, new Date(t), false);
			double ha = calc.getHourAngle();
			return (min <= ha) && (ha <= max);
		}

	}

}


text:
'use strict';

const Alexa = require('alexa-sdk');
const util = require("./util");
const cal = require("./cal-dates");

// global variables for reference
var alexa;  // alexa SDK
const APP_ID = "";  // @todo Add from AWS
const SKILL_NAME = "Seattle Public Schools Calendar";

// Various messages based on intents/events
const WELCOME_MSG = "Welcome to " + SKILL_NAME + ". You can ask if SPS is in session today. Search for school holidays by date";
const WELCOME_REPROMPT = "For instructions on what you can say, please say help me.";
const HELP_MSG = "Here are some things you can say: Is school in session today? Is there school on the 19th of March?";
const HELP_REPROMPT = "You can ask things like is there school on December 1st or when is the next school holiday, or you can say exit...Now, what can I help you with?";
const NO_DATA_MSG = "There is no information found for that date. Would you like to search again?";
const SHUTDOWN_MSG = "Okay see you later";

function isSchoolInSession(date) {
    if (util.isEmpty(date)) {
      return false;
    }
    else if (!util.isDate(date)) {
      return false;
    }
    else {
      var d = Number( util.iso2key(date) ) ;
      var begin = Number(cal.schoolBegin);
      var end = Number(cal.schoolEnd);
      return (d >= begin && d <= end);
    }
}

/**
 * Determines when the next school day is based off current date.
 * @param {Date} date to begin checking from if null will grab current date
 * @return {Object} ISO Date of next school day
 */
function nextSchoolDay(startDate) {
  startDate = util.isDate(startDate) ? startDate : null;
  var date = (util.isEmpty(startDate)) ? new Date() : startDate;
  var nextDay = null;

  // don't iterate more than 100 days - could be summer
  var i; var keyDate; var dayEvent;

  for (i=1; i <= 100; i++) {
    date.setDate(date.getDate() + i);

    if (!util.isWeekDay(date.getDay())) {
      continue;
    }

    // weekday and see if no holiday or early dismissal
    keyDate = util.iso2key(date);
    dayEvent = cal.events[keyDate];

    // no event
    if (util.isEmpty(dayEvent) && isSchoolInSession(date)) {
      nextDay = date;
      break;
    }
    // event - see if early dismissal or holiday
    else {
      if (dayEvent.isEarlyDismissal){
        nextDay = date;
        break;
      }
    }
  }

  return nextDay;
}

/**
 * Determines when the next school holiday is based off current date.
 * @param {Date} date to begin checking from if null will grab current date
 * @return {Object} ISO Date of next holiday (day off school)
 */
function nextHoliday(startDate) {
  startDate = util.isDate(startDate) ? startDate : null;
  var date = (util.isEmpty(startDate)) ? new Date() : startDate;
  var nextDay = null;

  // don't iterate more than 100 days - could be summer
  var i; var keyDate; var dayEvent;

  for (i=1; i <= 100; i++) {
    date.setDate(date.getDate() + i);

    if (isSchoolInSession(date)) {
      break;
    }

    keyDate = util.iso2key(date);
    dayEvent = cal.events[keyDate];

    // no event
    if (util.isEmpty(dayEvent)) {
      continue;
    }
    // event - see if holiday
    else {
      if (dayEvent.hasNoSchool){
        nextDay = date;
        break;
      }
    }
  }

  return nextDay;
}

var handlers = {
  'LaunchRequest': function() {
    this.emit(':ask', WELCOME_MSG, WELCOME_REPROMPT);
  },
  'SpsCalIntent': function () {
    var itemSlot = this.event.request.intent.slots.Item;
    var itemName;
    if (itemSlot && itemSlot.value) {
      itemName = itemSlot.value.toLowerCase();
    }

    var dayEvent =  cal.events[itemName];

    if (dayEvent) {
      // @todo create unique intents per requests for school day, early dismissal, no school or holiday
      this.emit(':tell', 'Found event would load here for ' + dayEvent);
    } else {
      this.emit(':tell', 'Did not find event would load here for ask on this date ' + dayEvent);
    }
  },
  'AMAZON.HelpIntent': function () {
    this.emit(':ask', HELP_MSG, HELP_REPROMPT);
  },
  'AMAZON.CancelIntent': function () {
    this.emit(':tell', SHUTDOWN_MSG);
  },
  'AMAZON.StopIntent': function () {
    this.emit(':tell', SHUTDOWN_MSG);
  }
};

// register handlers
exports.handler = function(event, context, callback) {
  alexa = Alexa.handler(event, context);
  alexa.appId = APP_ID;
  alexa.registerHandlers(handlers);
  alexa.execute();
};


text:
type ProdKernel <: Kernel
    kerns::Vector{Kernel}
    function ProdKernel(args...)
        kerns = Array(Kernel, length(args))
        for (i,k) in enumerate(args)
            isa(k, Kernel) || throw(ArgumentError("All arguments of ProdKernel must be Kernel objects"))
            kerns[i] = k
        end
        return new(kerns)
    end
end

function show(io::IO, prodkern::ProdKernel, depth::Int = 0)
    pad = repeat(" ", 2 * depth)
    println(io, "$(pad)Type: $(typeof(prodkern))")
    for k in prodkern.kerns
        show(io, k, depth+1)
    end
end

function cov(prodkern::ProdKernel, x::Vector{Float64}, y::Vector{Float64})
    p = 1.0
    for k in prodkern.kerns
        p = p.*cov(k, x, y)
    end
    return p
end

function cov(prodkern::ProdKernel, X::Matrix{Float64})
    d, nobsv = size(X)
    p = ones(nobsv, nobsv)
    for k in prodkern.kerns
        p[:,:] = p .* cov(k, X)
    end
    return p
end

function get_params(prodkern::ProdKernel)
    p = Array(Float64, 0)
    for k in prodkern.kerns
        append!(p, get_params(k))
    end
    p
end

get_param_names(prodkern::ProdKernel) = composite_param_names(prodkern.kerns, :pk)

function num_params(prodkern::ProdKernel)
    n = 0
    for k in prodkern.kerns
        n += num_params(k)
    end
    n
end

function set_params!(prodkern::ProdKernel, hyp::Vector{Float64})
    i, n = 1, num_params(prodkern)
    length(hyp) == num_params(prodkern) || throw(ArgumentError("ProdKernel object requires $(n) hyperparameters"))
    for k in prodkern.kerns
        np = num_params(k)
        set_params!(k, hyp[i:(i+np-1)])
        i += np
    end
end

# This function is extremely inefficient
function grad_kern(prodkern::ProdKernel, x::Vector{Float64}, y::Vector{Float64})
     dk = Array(Float64, 0)
      for k in prodkern.kerns
          p = 1.0
          for j in prodkern.kerns[find(k.!=prodkern.kerns)]
              p = p.*cov(j, x, y)
          end
        append!(dk,grad_kern(k, x, y).*p)
      end
    dk
end

function grad_stack!(stack::AbstractArray, X::Matrix{Float64}, prodkern::ProdKernel)
    d, nobsv = size(X)
    num_kerns = length(prodkern.kerns)

    cross_kerns = Array(Float64, nobsv, nobsv, num_kerns)
    for (i,kern) in enumerate(prodkern.kerns)
        cross_kerns[:,:,i] = cov(kern, X)
    end

    s = 1
    for (i,kern) in enumerate(prodkern.kerns)
        np = num_params(kern)
        grad_stack!(view(stack,:,:,s:(s+np-1)), X, kern)
        for j in 1:num_kerns
            if j != i
                broadcast!(.*, view(stack,:,:,s:(s+np-1)), view(stack,:,:,s:(s+np-1)), view(cross_kerns, :,:,j))
            end
        end
        s += np
    end
    stack
end

# Multiplication operators
function *(k1::ProdKernel, k2::Kernel)
    kerns = [k1.kerns; k2]
    ProdKernel(kerns...)
end
function *(k1::ProdKernel, k2::ProdKernel)
    kerns = [k1.kerns; k2.kerns]
    ProdKernel(kerns...)
end
*(k1::Kernel, k2::Kernel) = ProdKernel(k1,k2)
*(k1::Kernel, k2::ProdKernel) = *(k2,k1)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace FossLock.Web.ViewModels
{
    public class HumanContactViewModel
    {
        [MaxLength(255)]
        public string FirstName { get; set; }

        [MaxLength(255)]
        public string LastName { get; set; }

        [Phone]
        public string Phone1 { get; set; }

        [Phone]
        public string Phone2 { get; set; }

        [Phone]
        public string Fax { get; set; }

        [EmailAddress]
        public string Email { get; set; }

        [DataType(DataType.MultilineText)]
        public string Notes { get; set; }
    }
}


text:
using LibGit2Sharp;
using Microsoft.Extensions.Options;

namespace GitVersion;

public static class RepositoryExtensions
{
    public static IGitRepository ToGitRepository(this IRepository repository) => new GitRepository(repository);
    public static IGitRepositoryInfo ToGitRepositoryInfo(IOptions<GitVersionOptions> options) => new GitRepositoryInfo(options);

    public static void RunSafe(Action operation)
    {
        try
        {
            operation();
        }
        catch (LibGit2Sharp.LockedFileException ex)
        {
            // Wrap this exception so that callers that want to catch it don't need to take a dependency on LibGit2Sharp.
            throw new LockedFileException(ex);
        }
    }

    public static T RunSafe<T>(Func<T> operation)
    {
        try
        {
            return operation();
        }
        catch (LibGit2Sharp.LockedFileException ex)
        {
            // Wrap this exception so that callers that want to catch it don't need to take a dependency on LibGit2Sharp.
            throw new LockedFileException(ex);
        }
    }
}


text:
- [#210](https://github.com/amsul/pickadate.js/issues/210): Wrapped files using UMD patterns.
- [#207](https://github.com/amsul/pickadate.js/issues/207): Japanese translations added.
- Some other slight improvements.

## 3.2.0

- [#178](https://github.com/amsul/pickadate.js/issues/178): Fix for flicker on iOS while changing months.
- Added `render(true)` option to render full picker or just the "face" ([read more](http://amsul.github.io/pickadate.js/api.htm#method-render)).

## 3.1.4

- Fix for Polish translation.
- Added a `container` option to specify the picker root element's outlet.
- Fix for `$` conflict in translation files.

## 3.1.3

- Korean translations added.

## 3.1.2

- [#168](https://github.com/amsul/pickadate.js/issues/168): Fixed month navigation with disabled dates.

## 3.1.1

- [#161](https://github.com/amsul/pickadate.js/issues/161): Corrected "no-drop" cursor on input element for certain browsers.
- [#158](https://github.com/amsul/pickadate.js/issues/158): Fixed CSS for disabled dates with unfocused input.
- [#155](https://github.com/amsul/pickadate.js/issues/155): Corrected unescaped translations.

## 3.1.0

- [#140](https://github.com/amsul/pickadate.js/issues/140): Fix for freezing with unexpected date format.
- [#154](https://github.com/amsul/pickadate.js/issues/154): Fix for "mm" and "m" formats opening with incorrect month.
- Border styling adjusted for disabled times.

## v3.0.5

- [#145](https://github.com/amsul/pickadate.js/issues/145): Fix for `getFirstWordLength` not being defined.
- [#137](https://github.com/amsul/pickadate.js/issues/137): Corrected Norwegian translation.

## v3.0.4

- [#132](https://github.com/amsul/pickadate.js/issues/132): Fix for using `firstDay` with month starting on Sunday.
- Improved disabled dates validation.

## v3.0.3

- [#126](https://github.com/amsul/pickadate.js/issues/126): Fix for all dates disabled.
- [#127](https://github.com/amsul/pickadate.js/issues/127): Fix for jQuery no conflict.
- [#129](https://github.com/amsul/pickadate.js/issues/129): Fix for month nav wrapping around same year.

## v3.0.2

- [#124](https://github.com/amsul/pickadate.js/issues/124): Fixed bug with navigating past year.

## v3.0.1

- [#123](https://github.com/amsul/pickadate.js/issues/123): Removed `hiddenSuffix` extra quote character.
- Fixed issue with month navigation on the 31st date.

## v3.0.0

With this major release, the entire API has been rethought to allow the picker to be much more configurable and extensible. These are the most notable updates:

- [#20](https://github.com/amsul/pickadate.js/issues/20): Introduced a new [time picker](http://amsul.github.io/pickadate.js/time.htm).
- [#112](https://github.com/amsul/pickadate.js/issues/112): Firefox select month/year fix.
- [#84](https://github.com/amsul/pickadate.js/issues/84): Scrollbar not hidden to avoid page shift.
- [#89](https://github.com/amsul/pickadate.js/issues/89): Better event handling on clicks/focuses/keydowns within the holder.
- [#98](https://github.com/amsul/pickadate.js/issues/98): Destroy picker data from element.
- Added Grunt.js build system.
- Added QUnit test suite.
- Added Travis integration.
- Updated themes to be LESS-based.
- Removed "inline" and "inline-fixed" themes.
- Removed jam.js bindings within `package.json`.
- Removed official support for IE7. Still works but looks odd.

To enable all this goodness, some **backward-incompatible changes** have been introduced. These are the main ones:

- [#85](https://github.com/amsul/pickadate.js/issues/85): Months have __zero-as-index__:

	Just as in JavaScript's native Date object, the `month` used to create dates is now 	based on zero as the first index. Meaning:

	```
	[2013,0,1] → January 01, 2013
	[2013,11,1] → December 01, 2013
	```

- API revised:

	```
	isOpen → get('open')
	getDate → get('select')
	getDateLimit → get('min') or get('max')
	setDate → set('select', …)
	setDateLimit → set('min', …) or set('max', …)
	show → set('view', …)
	```

- Options revised:

	```
	showMonthsFull → showMonthsShort
	showWeekdaysShort → showWeekdaysFull
	yearSelector → selectYears
	monthSelector → selectMonths
	dateMin → min
	dateMax → max
	datesDisabled → disable
	onSelect → onSet
	```

- Options removed:

	```
	monthPrev
	monthNext
	```
	To add labels for the month navigation tabs, use CSS pseudo-elements instead.

- A few [HTML classes](http://amsul.github.io/pickadate.js/date.htm#classes) name and property changes.

- [Formatting rules](http://amsul.github.io/pickadate.js/date.htm#formats) that appear within a word need to be escaped with an exclamation mark (!).

#### Please do read the [docs](http://amsul.github.io/pickadate.js/date.htm#options) and [api](http://amsul.github.io/pickadate.js/api.htm) to see exactly how these new options and methods work.

## Older changelogs

If you're looking for changes in older versions, please [browse the tags](https://github.com/amsul/pickadate.js/tags) for the relevant commit archive and changelog file.


text:
package org.elasticsearch.xpack.monitoring.test;

import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.ingest.ConfigurationUtils;
import org.elasticsearch.ingest.IngestDocument;
import org.elasticsearch.ingest.Processor;
import org.elasticsearch.plugins.IngestPlugin;
import org.elasticsearch.plugins.Plugin;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * Mock representation of the Ingest Common plugin for the subset of processors that are needed for the pipelines in Monitoring's exporters.
 */
public class MockIngestPlugin extends Plugin implements IngestPlugin {

    @Override
    public Map<String, Processor.Factory> getProcessors(final Processor.Parameters parameters) {
        final Map<String, String[]> processorFields = MapBuilder.<String, String[]>newMapBuilder()
                .put("gsub", new String[] { "field", "pattern", "replacement" })
                .put("rename", new String[] { "field", "target_field" })
                .put("set", new String[] { "field", "value" })
                .put("script", new String[] { "source" })
                .map();

        return processorFields.entrySet()
                              .stream()
                              .map(MockProcessorFactory::new)
                              .collect(Collectors.toMap(factory -> factory.type, factory -> factory));
    }

    static class MockProcessorFactory implements Processor.Factory {

        private final String type;
        private final String[] fields;

        MockProcessorFactory(final Map.Entry<String, String[]> factory) {
            this(factory.getKey(), factory.getValue());
        }

        MockProcessorFactory(final String type, final String[] fields) {
            this.type = type;
            this.fields = fields;
        }

        @Override
        public Processor create(Map<String, Processor.Factory> processorFactories,
                                String tag,
                                String description, Map<String, Object> config) throws Exception {
            // read fields so the processor succeeds
            for (final String field : fields) {
                ConfigurationUtils.readObject(type, tag, config, field);
            }

            return new MockProcessor(type, tag, description);
        }

    }

    static class MockProcessor implements Processor {

        private final String type;
        private final String tag;
        private final String description;

        MockProcessor(final String type, final String tag, final String description) {
            this.type = type;
            this.tag = tag;
            this.description = description;
        }

        @Override
        public IngestDocument execute(IngestDocument ingestDocument) throws Exception {
            // mock processor does nothing
            return ingestDocument;
        }

        @Override
        public String getType() {
            return type;
        }

        @Override
        public String getTag() {
            return tag;
        }

        @Override
        public String getDescription() {
            return description;
        }

    }

}


text:
layout: doc_pl
title: Class Variables
previous: Instance Variables
previous_url: ruby/instance-variables
next: Global Variables
next_url: ruby/global-variables
review: true
---


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.gcsc.jfx3d;

import java.util.ArrayList;

/**
 *
 * @author Eugen
 */
public class Triangle extends Geometry2D {

    private int[] nodes = new int[3];
    private int index = -1;

    public Triangle(int v0, int v1, int v2, int index){
        this.nodes[0] = v0;
        this.nodes[1] = v1;
        this.nodes[2] = v2;
        this.index = index;
    }

    @Override
    public int[] getNodes() {
        return nodes;
    }

    @Override
    public void setNodes(int[] nodes) {
        this.nodes = nodes;
    }

    public int getIndex(){
        return this.index;
    }

    @Override
    public int[] getFacesArray() {
        int[] arr = {this.nodes[0],0,this.nodes[1],0,this.nodes[2],0};
        return arr;
    }

    @Override
    public String getCoordinatesOfPoints(ArrayList listOfAllVertices) {
        return ("2D Object : " + this.index + "\n"+
                "Vertex 1: " + listOfAllVertices.get(nodes[0]*3) + " " +listOfAllVertices.get(nodes[0]*3+1) + " " + listOfAllVertices.get(nodes[0]*3+2) + "\n" +
                "Vertex 2: " + listOfAllVertices.get(nodes[1]*3) + " " +listOfAllVertices.get(nodes[1]*3+1) + " " + listOfAllVertices.get(nodes[1]*3+2) + "\n" +
                "Vertex 3: " + listOfAllVertices.get(nodes[2]*3) + " " +listOfAllVertices.get(nodes[2]*3+1) + " " + listOfAllVertices.get(nodes[2]*3+2) + "\n" );
    }

}


text:
"""
Description of individual model.
"""
module individual
importall common
using fitness, core, utility
export sort, sort!, isbetter, best!, best

# Load contents.
include("individual/stage.jl")

"""
Sorts a list of individuals in descending order of fitness, from best to worst.
"""
sort{F}(s::FitnessScheme, l::Vector{Tuple{Int, F}}) =
  sort(l, lt = (x, y) -> isbetter(s, x, y))

"""
Sorts a list of individuals in descending order of fitness, from best to worst,
in place.
"""
sort!{F}(s::FitnessScheme, l::Vector{Tuple{Int, F}}) =
  sort!(l, lt = (x, y) -> isbetter(s, x, y))

"""
Compares an individual X to an individual Y to determine whether X is an
improvement upon Y.
"""
isbetter{F}(s::FitnessScheme, x::Tuple{Int, F}, y::Tuple{Int, F}) =
  compare(s, x, y) == -1
compare{F}(s::FitnessScheme, x::Tuple{Int, F},  y::Tuple{Int, F}) =
  compare(s, x[2], y[2])

"""
Returns the "best" individual from a provided list, according to a given
fitness scheme.

Fails if the if list of individuals is empty.
"""
function best{F}(s::FitnessScheme, inds::Vector{Tuple{Int, F}})
  bst = inds[1]
  for i in inds
    if isbetter(s, i, bst)
      bst = i
    end
  end
  return bst
end

"""
Performs any necessary post-processing on the individuals using this fitness
scheme.
"""
scale!{F}(::FitnessScheme, ::Vector{Tuple{Int, F}}) = return
end


text:
const assert = require('assert');
const { expect, should } = require('chai');
const fs = require('fs');
const uAPI = require('../../src');
const Parser = require('../../src/Request/uapi-parser');
const utilsParser = require('../../src/Services/Utils/UtilsParser');

const UtilsError = uAPI.errors.Utils;
const RequestError = uAPI.errors.Request;
const xmlFolder = `${__dirname}/../FakeResponses/Utils`;

describe('#utilsParser', () => {
  describe('currencyConvert()', () => {
    it('should parse single currency pair request', () => {
      const uParser = new Parser('util:CurrencyConversionRsp', 'v47_0', {});
      const parseFunction = utilsParser.CURRENCY_CONVERSION;
      const xml = fs.readFileSync(`${xmlFolder}/currency-conversion.single.xml`).toString();
      return uParser.parse(xml).then((json) => {
        const result = parseFunction.call(uParser, json);
        expect(result).to.be.an('array').and.to.have.lengthOf(1);
        result.forEach(c => expect(c).to.be.an('object').and.to.have.all.keys(['from', 'to', 'rate']));
      });
    });

    it('should parse multi currency pair request', () => {
      const uParser = new Parser('util:CurrencyConversionRsp', 'v47_0', {});
      const parseFunction = utilsParser.CURRENCY_CONVERSION;
      const xml = fs.readFileSync(`${xmlFolder}/currency-conversion.multi.xml`).toString();
      return uParser.parse(xml).then((json) => {
        const result = parseFunction.call(uParser, json);
        expect(result).to.be.an('array').and.to.have.lengthOf(2);
        result.forEach((c) => {
          expect(c).to.be.an('object').and.to.have.all.keys(['from', 'to', 'rate']);
          expect(c.rate).to.be.a('number');
        });
      });
    });

    it('should throw parsing error', () => {
      const parseFunction = utilsParser.CURRENCY_CONVERSION;
      try {
        parseFunction({});
      } catch (e) {
        assert(e instanceof UtilsError.UtilsParsingError, 'Incorrect error thrown');
        return;
      }
      should.fail('No error was thrown');
    });

    it('should test error handling', () => {
      const parseFunction = utilsParser.UTILS_ERROR;
      const uParser = new Parser('util:CurrencyConversionRsp', 'v47_0', {});
      const xml = fs.readFileSync(`${xmlFolder}/../Other/UnableToFareQuoteError.xml`).toString(); // any error
      return uParser
        .parse(xml)
        .then((json) => {
          const errData = uParser.mergeLeafRecursive(json['SOAP:Fault'][0]);
          return parseFunction.call(uParser, errData);
        })
        .then(() => assert(false, 'Error should be thrown'))
        .catch((err) => {
          expect(err).to.be.an.instanceOf(RequestError.RequestRuntimeError.UnhandledError);
          expect(err.causedBy).to.be.an.instanceOf(UtilsError.UtilsRuntimeError);
        });
    });
  });
  describe('referenceData()', () => {
    it('should parse sample data response for Country', () => {
      const uParser = new Parser('util:ReferenceDataRetrieveRsp', 'v47_0', {});
      const parseFunction = utilsParser.REFERENCE_DATATYPE;
      const xml = fs.readFileSync(`${xmlFolder}/country-data.xml`).toString();
      return uParser.parse(xml).then((json) => {
        const result = parseFunction.call(uParser, json);
        expect(result).to.be.an('array').and.to.have.lengthOf(3);
        result.forEach(c => expect(c).to.be.an('object').and.to.have.all.keys(['code', 'name', 'deprecated']));
      });
    });

    it('should parse sample data response for Hotel Amenities', () => {
      const uParser = new Parser('util:ReferenceDataRetrieveRsp', 'v47_0', {});
      const parseFunction = utilsParser.REFERENCE_DATATYPE;
      const xml = fs.readFileSync(`${xmlFolder}/hotelAmenities-data.xml`).toString();
      return uParser.parse(xml).then((json) => {
        const result = parseFunction.call(uParser, json);
        expect(result).to.be.an('array').and.to.have.lengthOf(3);
        result.forEach(c => expect(c).to.be.an('object').and.to.have.all.keys(['code', 'name', 'description', 'deprecated', 'additionalInfo']));
      });
    });

    it('should parse sample data response for Payment Type', () => {
      const uParser = new Parser('util:ReferenceDataRetrieveRsp', 'v47_0', {});
      const parseFunction = utilsParser.REFERENCE_DATATYPE;
      const xml = fs.readFileSync(`${xmlFolder}/paymentType-data.xml`).toString();
      return uParser.parse(xml).then((json) => {
        const result = parseFunction.call(uParser, json);
        expect(result).to.be.an('array').and.to.have.lengthOf(3);
        result.forEach(c => expect(c).to.be.an('object').and.to.have.all.keys(['code', 'name', 'description', 'deprecated', 'additionalInfo']));
      });
    });

    it('should throw parsing error', () => {
      const parseFunction = utilsParser.REFERENCE_DATATYPE;
      try {
        parseFunction({});
      } catch (e) {
        assert(e instanceof UtilsError.UtilsParsingError, 'Incorrect error thrown');
        return;
      }
      should.fail('No error was thrown');
    });

    it('should test error handling', () => {
      const parseFunction = utilsParser.UTILS_ERROR;
      const uParser = new Parser('util:ReferenceDataRetrieveRsp', 'v47_0', {});
      const xml = fs.readFileSync(`${xmlFolder}/../Other/ReferenceDataError.xml`).toString(); // any error
      return uParser
        .parse(xml)
        .then((json) => {
          const errData = uParser.mergeLeafRecursive(json['SOAP:Fault'][0]);
          return parseFunction.call(uParser, errData);
        })
        .then(() => assert(false, 'Error should be thrown'))
        .catch((err) => {
          expect(err).to.be.an.instanceOf(RequestError.RequestRuntimeError.UnhandledError);
          expect(err.causedBy).to.be.an.instanceOf(UtilsError.UtilsRuntimeError);
        });
    });

    it('should test error handling', () => {
      const parseFunction = utilsParser.UTILS_ERROR;
      const uParser = new Parser('SOAP:Fault', 'v47_0', {});
      const xml = fs.readFileSync(`${xmlFolder}/../Other/ReferenceDataError.xml`).toString(); // any error
      return uParser
        .parse(xml)
        .then((json) => {
          const errData = uParser.mergeLeafRecursive(json['SOAP:Fault'][0]);
          return parseFunction.call(uParser, errData);
        })
        .then(() => assert(false, 'Error should be thrown'))
        .catch((err) => {
          expect(err).to.be.an.instanceOf(RequestError.RequestRuntimeError.UnhandledError);
          expect(err.causedBy).to.be.an.instanceOf(UtilsError.UtilsRuntimeError);
        });
    });
  });
});


text:
/**
 * Swagger api specific code.
 */
package com.dhl.serv.config.apidoc;


text:
package org.calrissian.flowmix.core.model.op;

import org.calrissian.flowmix.api.Function;

public class EachOp implements FlowOp {

    public static final String EACH = "each";

    Function function;

    public EachOp(Function function) {
        this.function = function;
    }

    public Function getFunction() {
        return function;
    }

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

        EachOp that = (EachOp) o;

        if (function != null ? !function.equals(that.function) : that.function != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return function != null ? function.hashCode() : 0;
    }

    @Override
    public String getComponentName() {
        return "each";
    }
}


text:
import hashlib
import time

# Number of zeros required at the beginning of the computed hash
def const_zeros():
    return 6

# Number of hashes to find for which the condition is satisfied
def const_count():
    return 5

# Determined whether the byte array meets the required condition
def ismagic(byte_array):
    bismagic = True

    # Compute MD5 hash of the byte array
    m = hashlib.md5()
    m.update(byte_array)
    md5_hash = m.hexdigest()

    # Check the number of zeros
    for i in range(const_zeros()):
        if md5_hash[i] != '0':
            bismagic = False
            break

    # Print the hash if it meets the condition
    if bismagic:
        print(md5_hash, end=' - ')
        # Print the byte array for which the condition was met
        for b in byte_array:
            print(str(b).rjust(3), end=' ')
        # Break the line
        print()

    # Return True if the condition was met, False otherwise
    return bismagic

# Main program function
def main():
    counter = 0
    barr = bytearray()

    # Get time at which the computation has started
    starttime = time.time()

    # Until the required number of hashes is computed
    while counter < const_count():
        # Get the current length of the byte array
        barrlen = len(barr)
        # If the byte array is empty or it's full of 255 values
        if barrlen == 0 or barr[barrlen - 1] == 255:
            # Set all the bytes to 0
            for i in range(barrlen):
                barr[i] = 0
            # Add new element to the byte array
            barr.append(0)
        # No need to add another element to the byte array
        else:
            # Increment the lowest byte possible
            for i in range(barrlen):
                # Overflow each element that has value 255
                if barr[i] == 255:
                    barr[i] = 0
                # Increment the lower possible element
                else:
                    barr[i] += 1
                    break

        # If the byte array meets the condition
        if ismagic(barr):
            # Increment the counter of computed hashed that meet the condition
            counter += 1

    # Calculate the time difference between the start of the computation and its end
    totalsec = time.time() - starttime
    # Separate hours, minutes and seconds
    hours = int(totalsec / 3600)
    minutes = int(totalsec / 60 % 60)
    seconds = round(totalsec % 60)

    # Print the computation time
    print("Computation time:", end=' ')

    # Hours
    if hours > 1:
        print(hours, "hours", end=' ')
    elif hours == 1:
        print("1 hour", end=' ')

    # Minutes
    if minutes > 1:
        print(minutes, "minutes", end=' ')
    elif minutes == 1:
        print("1 minute", end=' ')

    # Seconds
    print(seconds, "seconds")

# Start the program
main()


text:
class ApplicationHelper::Button::ButtonNewDiscover < ApplicationHelper::Button::Basic
  include ApplicationHelper::Button::Mixins::SubListViewScreenMixin

  def visible?
    !sub_list_view_screen?
  end
end


text:
namespace android.content.pm
{
	[global::MonoJavaBridge.JavaClass()]
	public partial class ServiceInfo : android.content.pm.ComponentInfo, android.os.Parcelable
	{
		internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
		protected ServiceInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
		{
		}
		private static global::MonoJavaBridge.MethodId _m0;
		public override global::java.lang.String toString()
		{
			return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.pm.ServiceInfo.staticClass, "toString", "()Ljava/lang/String;", ref global::android.content.pm.ServiceInfo._m0) as java.lang.String;
		}
		private static global::MonoJavaBridge.MethodId _m1;
		public virtual void dump(android.util.Printer arg0, java.lang.String arg1)
		{
			global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.pm.ServiceInfo.staticClass, "dump", "(Landroid/util/Printer;Ljava/lang/String;)V", ref global::android.content.pm.ServiceInfo._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
		}
		public void dump(global::android.util.PrinterDelegate arg0, java.lang.String arg1)
		{
			dump((global::android.util.PrinterDelegateWrapper)arg0, arg1);
		}
		private static global::MonoJavaBridge.MethodId _m2;
		public override void writeToParcel(android.os.Parcel arg0, int arg1)
		{
			global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.pm.ServiceInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V", ref global::android.content.pm.ServiceInfo._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
		}
		private static global::MonoJavaBridge.MethodId _m3;
		public virtual int describeContents()
		{
			return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.pm.ServiceInfo.staticClass, "describeContents", "()I", ref global::android.content.pm.ServiceInfo._m3);
		}
		private static global::MonoJavaBridge.MethodId _m4;
		public ServiceInfo() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.content.pm.ServiceInfo._m4.native == global::System.IntPtr.Zero)
				global::android.content.pm.ServiceInfo._m4 = @__env.GetMethodIDNoThrow(global::android.content.pm.ServiceInfo.staticClass, "<init>", "()V");
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.ServiceInfo.staticClass, global::android.content.pm.ServiceInfo._m4);
			Init(@__env, handle);
		}
		private static global::MonoJavaBridge.MethodId _m5;
		public ServiceInfo(android.content.pm.ServiceInfo arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.content.pm.ServiceInfo._m5.native == global::System.IntPtr.Zero)
				global::android.content.pm.ServiceInfo._m5 = @__env.GetMethodIDNoThrow(global::android.content.pm.ServiceInfo.staticClass, "<init>", "(Landroid/content/pm/ServiceInfo;)V");
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.ServiceInfo.staticClass, global::android.content.pm.ServiceInfo._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
			Init(@__env, handle);
		}
		internal static global::MonoJavaBridge.FieldId _permission2126;
		public global::java.lang.String permission
		{
			get
			{
				global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
				return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetObjectField(this.JvmHandle, _permission2126)) as java.lang.String;
			}
			set
			{
			}
		}
		internal static global::MonoJavaBridge.FieldId _CREATOR2127;
		public static global::android.os.Parcelable_Creator CREATOR
		{
			get
			{
				global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
				return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable_Creator>(@__env.GetStaticObjectField(global::android.content.pm.ServiceInfo.staticClass, _CREATOR2127)) as android.os.Parcelable_Creator;
			}
		}
		static ServiceInfo()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::android.content.pm.ServiceInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/pm/ServiceInfo"));
			global::android.content.pm.ServiceInfo._permission2126 = @__env.GetFieldIDNoThrow(global::android.content.pm.ServiceInfo.staticClass, "permission", "Ljava/lang/String;");
			global::android.content.pm.ServiceInfo._CREATOR2127 = @__env.GetStaticFieldIDNoThrow(global::android.content.pm.ServiceInfo.staticClass, "CREATOR", "Landroid/os/Parcelable$Creator;");
		}
	}
}


text:
package com.yf.designPattern.decorator;

public interface Shape {
	public void draw();
}


text:
using namespace System;
using namespace PcapDotNet::Base;
using namespace PcapDotNet::Core;

// static
DateTime PacketTimestamp::MinimumPacketTimestamp::get()
{
    return _minimumPacketTimestamp;
}

// static
DateTime PacketTimestamp::MaximumPacketTimestamp::get()
{
    return _maximumPacketTimestamp;
}

// static
void PacketTimestamp::PcapTimestampToDateTime(const timeval& pcapTimestamp, [Runtime::InteropServices::Out] DateTime% dateTime)
{
    dateTime = DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind::Utc);
    TimeSpan seconds = TimeSpan::FromSeconds(pcapTimestamp.tv_sec);
    TimeSpan microseconds = TimeSpan::FromTicks(pcapTimestamp.tv_usec * TimeSpanExtensions::TicksPerMicrosecond);
    dateTime = dateTime.Add(seconds + microseconds);
    dateTime = dateTime.ToLocalTime();
}

// static
void PacketTimestamp::DateTimeToPcapTimestamp(DateTime dateTime, timeval& pcapTimestamp)
{
    dateTime = dateTime.ToUniversalTime();
    TimeSpan timespan = dateTime - DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind::Utc);
    pcapTimestamp.tv_sec = (long)timespan.TotalSeconds;
    pcapTimestamp.tv_usec = (long)((timespan.TotalMilliseconds - 1000 * (double)pcapTimestamp.tv_sec) * 1000);
}

// static
void PacketTimestamp::Initialize()
{
    // Min
    timeval pcapTimestamp;
    pcapTimestamp.tv_sec = Int32::MinValue;
    pcapTimestamp.tv_usec = Int32::MinValue;
    PacketTimestamp::PcapTimestampToDateTime(pcapTimestamp, _minimumPacketTimestamp);

    pcapTimestamp.tv_sec = Int32::MaxValue;
    pcapTimestamp.tv_usec = Int32::MaxValue;
    PacketTimestamp::PcapTimestampToDateTime(pcapTimestamp, _maximumPacketTimestamp);
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using SQLitePCL;

namespace Microsoft.CodeAnalysis.SQLite.Interop
{
    [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Name chosen to match SQLitePCL.raw")]
    internal static class NativeMethods
    {
        public static SafeSqliteHandle sqlite3_open_v2(string filename, int flags, string vfs, out Result result)
        {
            result = (Result)raw.sqlite3_open_v2(filename, out var wrapper, flags, vfs);
            if (result != Result.OK)
            {
                wrapper = null;
            }

            try
            {
                // Always return a non-null handle to match default P/Invoke marshaling behavior. SafeHandle.IsInvalid
                // will be true when the handle is not usable, but the handle instance can be disposed either way.
                return new SafeSqliteHandle(wrapper);
            }
            catch
            {
                raw.sqlite3_close(wrapper);
                throw;
            }
        }

        public static SafeSqliteStatementHandle sqlite3_prepare_v2(SafeSqliteHandle db, string sql, out Result result)
        {
            using var _ = db.Lease();

            result = (Result)raw.sqlite3_prepare_v2(db.DangerousGetWrapper(), sql, out var wrapper);
            if (result != (int)Result.OK)
            {
                wrapper = null;
            }

            try
            {
                // Always return a non-null handle to match default P/Invoke marshaling behavior. SafeHandle.IsInvalid
                // will be true when the handle is not usable, but the handle instance can be disposed either way.
                return new SafeSqliteStatementHandle(db, wrapper);
            }
            catch
            {
                raw.sqlite3_finalize(wrapper);
                throw;
            }
        }

        public static SafeSqliteBlobHandle sqlite3_blob_open(SafeSqliteHandle db, string sdb, string table, string col, long rowid, int flags, out Result result)
        {
            using var _ = db.Lease();

            result = (Result)raw.sqlite3_blob_open(db.DangerousGetWrapper(), sdb, table, col, rowid, flags, out var wrapper);
            if (result != (int)Result.OK)
            {
                wrapper = null;
            }

            try
            {
                // Always return a non-null handle to match default P/Invoke marshaling behavior. SafeHandle.IsInvalid
                // will be true when the handle is not usable, but the handle instance can be disposed either way.
                return new SafeSqliteBlobHandle(db, wrapper);
            }
            catch
            {
                raw.sqlite3_blob_close(wrapper);
                throw;
            }
        }

        public static string sqlite3_errmsg(SafeSqliteHandle db)
        {
            using var _ = db.Lease();
            return raw.sqlite3_errmsg(db.DangerousGetWrapper());
        }

        public static string sqlite3_errstr(int rc)
        {
            return raw.sqlite3_errstr(rc);
        }

        public static int sqlite3_extended_errcode(SafeSqliteHandle db)
        {
            using var _ = db.Lease();
            return raw.sqlite3_extended_errcode(db.DangerousGetWrapper());
        }

        public static Result sqlite3_busy_timeout(SafeSqliteHandle db, int ms)
        {
            using var _ = db.Lease();
            return (Result)raw.sqlite3_busy_timeout(db.DangerousGetWrapper(), ms);
        }

        public static long sqlite3_last_insert_rowid(SafeSqliteHandle db)
        {
            using var _ = db.Lease();
            return raw.sqlite3_last_insert_rowid(db.DangerousGetWrapper());
        }

        public static int sqlite3_blob_bytes(SafeSqliteBlobHandle blob)
        {
            using var _ = blob.Lease();
            return raw.sqlite3_blob_bytes(blob.DangerousGetWrapper());
        }

        public static Result sqlite3_blob_read(SafeSqliteBlobHandle blob, byte[] b, int n, int offset)
        {
            using var _ = blob.Lease();
            return (Result)raw.sqlite3_blob_read(blob.DangerousGetWrapper(), b, n, offset);
        }

        public static Result sqlite3_reset(SafeSqliteStatementHandle stmt)
        {
            using var _ = stmt.Lease();
            return (Result)raw.sqlite3_reset(stmt.DangerousGetWrapper());
        }

        public static Result sqlite3_step(SafeSqliteStatementHandle stmt)
        {
            using var _ = stmt.Lease();
            return (Result)raw.sqlite3_step(stmt.DangerousGetWrapper());
        }

        public static Result sqlite3_bind_text(SafeSqliteStatementHandle stmt, int index, string val)
        {
            using var _ = stmt.Lease();
            return (Result)raw.sqlite3_bind_text(stmt.DangerousGetWrapper(), index, val);
        }

        public static Result sqlite3_bind_int64(SafeSqliteStatementHandle stmt, int index, long val)
        {
            using var _ = stmt.Lease();
            return (Result)raw.sqlite3_bind_int64(stmt.DangerousGetWrapper(), index, val);
        }

        public static byte[] sqlite3_column_blob(SafeSqliteStatementHandle stmt, int index)
        {
            using var _ = stmt.Lease();
            return raw.sqlite3_column_blob(stmt.DangerousGetWrapper(), index);
        }

        public static int sqlite3_column_int(SafeSqliteStatementHandle stmt, int index)
        {
            using var _ = stmt.Lease();
            return raw.sqlite3_column_int(stmt.DangerousGetWrapper(), index);
        }

        public static long sqlite3_column_int64(SafeSqliteStatementHandle stmt, int index)
        {
            using var _ = stmt.Lease();
            return raw.sqlite3_column_int64(stmt.DangerousGetWrapper(), index);
        }

        public static string sqlite3_column_text(SafeSqliteStatementHandle stmt, int index)
        {
            using var _ = stmt.Lease();
            return raw.sqlite3_column_text(stmt.DangerousGetWrapper(), index);
        }
    }
}


text:
node-docs
=========

Esprima based Nodejs docs generator form source code


text:
<?php
/**
 * Created by PhpStorm.
 * User: jhonDoe
 * Date: 16/03/2015
 * Time: 19:44
 */

namespace medaSys\AOBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
 * @ORM\Entity
 * @ORM\Table(name="suiviPlis")
 */
class suiviPlis {
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @ORM\Column(type="datetime",nullable=true)
     * @Assert\NotBlank
     * @Assert\GreaterThan("+1 days")
     */
    protected $dateOuverture;
    /**
     * @ORM\OneToOne(targetEntity="responsable")
     */
    protected $responsableCompte;
    /**
     * @ORM\OneToOne(targetEntity="responsable")
     */
    protected $chagerDepot;
    /**
     * @ORM\Column(type="string", length=100 ,nullable=true)
     */
    protected $seance;
    /**
     * @ORM\Column(type="string", length=100 ,nullable=true)
     */
    protected $lieuxOuverture;
    /**
     * @ORM\OneToOne(targetEntity="situationAppel",mappedBy="suiviPlis")
     */
    protected $situationAppel;
    /**
     * @ORM\OneToMany(targetEntity="lot", mappedBy="suiviPlis")
     */
    protected $lots;
    /**
     * @ORM\OneToMany(targetEntity="soumissionnairesPlis", mappedBy="suiviPlis",cascade={"remove","persist"})
     */
    protected $soumissionnaires;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->lots = new \Doctrine\Common\Collections\ArrayCollection();
        $this->dateOuverture=new \DateTime();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set dateOuverture
     *
     * @param \datetime $dateOuverture
     * @return suiviPlis
     */
    public function setDateOuverture(\datetime $dateOuverture=null)
{
    $this->dateOuverture = $dateOuverture;

    return $this;
}

    /**
     * Get dateOuverture
     *
     * @return \datetime
     */
    public function getDateOuverture()
    {
        return $this->dateOuverture;
    }
    public function setLieuxOuverture($lieuxOuverture)
    {
        $this->lieuxOuverture = $lieuxOuverture;

        return $this;
    }

    /**
     * Get dateOuverture
     *
     * @return \datetime
     */
    public function getLieuxOuverture()
    {
        return $this->lieuxOuverture;
    }

    /**
     * Set seance
     *
     * @param string $seance
     * @return suiviPlis
     */
    public function setSeance($seance)
    {
        $this->seance = $seance;

        return $this;
    }

    /**
     * Get seance
     *
     * @return string
     */
    public function getSeance()
    {
        return $this->seance;
    }

    /**
     * Set responsableCompte
     *
     * @param \medaSys\AOBundle\Entity\responsable $responsableCompte
     * @return suiviPlis
     */
    public function setResponsableCompte(\medaSys\AOBundle\Entity\responsable $responsableCompte = null)
    {
        $this->responsableCompte = $responsableCompte;

        return $this;
    }

    /**
     * Get responsableCompte
     *
     * @return \medaSys\AOBundle\Entity\responsable
     */
    public function getResponsableCompte()
    {
        return $this->responsableCompte;
    }

    /**
     * Set chagerDepot
     *
     * @param \medaSys\AOBundle\Entity\responsable $chagerDepot
     * @return suiviPlis
     */
    public function setChagerDepot(\medaSys\AOBundle\Entity\responsable $chagerDepot = null)
    {
        $this->chagerDepot = $chagerDepot;

        return $this;
    }

    /**
     * Get chagerDepot
     *
     * @return \medaSys\AOBundle\Entity\responsable
     */
    public function getChagerDepot()
    {
        return $this->chagerDepot;
    }

    /**
     * Set situationAppel
     *
     * @param \medaSys\AOBundle\Entity\situationAppel $situationAppel
     * @return suiviPlis
     */
    public function setSituationAppel(\medaSys\AOBundle\Entity\situationAppel $situationAppel = null)
    {
        $this->situationAppel = $situationAppel;

        return $this;
    }

    /**
     * Get situationAppel
     *
     * @return \medaSys\AOBundle\Entity\situationAppel
     */
    public function getSituationAppel()
    {
        return $this->situationAppel;
    }

    /**
     * Add lots
     *
     * @param \medaSys\AOBundle\Entity\lot $lots
     * @return suiviPlis
     */
    public function addLot(\medaSys\AOBundle\Entity\lot $lots)
    {
        $this->lots[] = $lots;

        return $this;
    }

    /**
     * Remove lots
     *
     * @param \medaSys\AOBundle\Entity\lot $lots
     */
    public function removeLot(\medaSys\AOBundle\Entity\lot $lots)
    {
        $this->lots->removeElement($lots);
    }

    /**
     * Get lots
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getLots()
    {
        return $this->lots;
    }

    /**
     * Add soumissionnaires
     *
     * @param \medaSys\AOBundle\Entity\soumissionnairesPlis $soumissionnaires
     * @return suiviPlis
     */
    public function addSoumissionnaire(\medaSys\AOBundle\Entity\soumissionnairesPlis $soumissionnaires)
    {
        $this->soumissionnaires[] = $soumissionnaires;

        return $this;
    }

    /**
     * Remove soumissionnaires
     *
     * @param \medaSys\AOBundle\Entity\soumissionnairesPlis $soumissionnaires
     */
    public function removeSoumissionnaire(\medaSys\AOBundle\Entity\soumissionnairesPlis $soumissionnaires)
    {
        $this->soumissionnaires->removeElement($soumissionnaires);
    }

    /**
     * Get soumissionnaires
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getSoumissionnaires()
    {
        return $this->soumissionnaires;
    }
}


text:
JsonLD Processor
================

.. toctree::
   :maxdepth: 4

   spreadflow_jsonld


text:
/*
 * Mixin that inject to user model object consumer set of methods necessary for
 * dealing with abcenses.
 *
 * */

'use strict';

var
    _             = require('underscore'),
    Promise       = require("bluebird"),
    CalendarMonth = require('../../calendar_month'),
    moment        = require('moment');

module.exports = function(sequelize){

  this._get_calendar_months_to_show = function(args){
    var year       = args.year,
    show_full_year = args.show_full_year;

    if (show_full_year) {
      return _.map([1,2,3,4,5,6,7,8,9,10,11,12], function(i){
        return moment(year.format('YYYY')+'-'+i+'-01');
      });
    }

    return _.map([0,1,2,3], function(delta){
      return moment().add(delta, 'months').startOf('month');
    })
  };

  this.promise_calendar = function(args) {
    var year       = args.year || moment(),
    show_full_year = args.show_full_year || false,
    model          = sequelize.models,
    this_user      = this,
    // Find or if we need to show multi year calendar
    is_multi_year = moment().month() > 8;

    var months_to_show = this_user._get_calendar_months_to_show({
      year           : year.clone(),
      show_full_year : show_full_year
    });

    return Promise.join(

      Promise.try(function(){
        return this_user.getDepartment();
      }),

      Promise.try(function(){
        return this_user.getCompany({
          include:[
            { model : model.BankHoliday, as : 'bank_holidays' },
            { model : model.LeaveType, as : 'leave_types' },
          ]
        });
      }),

      Promise.try(function(){
        return this_user.getMy_leaves({
          where : {
            status : { $ne : sequelize.models.Leave.status_rejected()},
            $or : {
              date_start : {
                $between : [
                  moment(year).startOf('year').format('YYYY-MM-DD'),
                  moment(
                    year.clone().add((is_multi_year ? 1 : 0), 'years')
                  ).endOf('year').format('YYYY-MM-DD'),
                ]
              },
              date_end : {
                $between : [
                  moment( year ).startOf('year').format('YYYY-MM-DD'),
                  moment(
                    year.clone().add((is_multi_year ? 1 : 0), 'years')
                  ).endOf('year').format('YYYY-MM-DD'),
                ]
              }
            }
          },
        });
      }),

      function(department, company, leaves){
        var leave_days = _.flatten( _.map(leaves, function(leave){
          return _.map( leave.get_days(), function(leave_day){
            leave_day.leave = leave;
            return leave_day;
          });
        }));

        return Promise.resolve(
          _.map(months_to_show, function(month){
            return new CalendarMonth(
              month,
              {
                bank_holidays :
                  department.include_public_holidays
                  ?  _.map(
                    company.bank_holidays,
                    function(day){return day.date}
                  )
                  : [],
                leave_days : leave_days,
              }
            );
          })
        );
      }

    ); // End of join
  };

  this.validate_overlapping = function(new_leave_attributes) {
    var this_user = this;

    var days_filter = {
      $between : [
        new_leave_attributes.from_date,
        moment(new_leave_attributes.to_date)
          .add(1,'days').format('YYYY-MM-DD'),
      ],
    };

    return this_user.getMy_leaves({
      where : {
        status : { $ne : sequelize.models.Leave.status_rejected()},

        $or : {
          date_start : days_filter,
          date_end : days_filter,
        },
      },
    })

    .then(function(overlapping_leaves){

      // Check there are overlapping leaves
      if (overlapping_leaves.length === 0){
          return Promise.resolve(1);
      }

      var overlapping_leave = overlapping_leaves[0];

      if (overlapping_leave.fit_with_leave_request(
            new_leave_attributes
      )){
          return Promise.resolve(1);
      }

      // Otherwise it is overlapping!
      var error = new Error('Overlapping booking!');
      error.user_message = 'Overlapping booking!';
      throw error;

    });
  }; // end of validate_overlapping

  // Promise all leaves requested by current user, regardless
  // their statuses
  //
  this.promise_my_leaves = function(args){

    var where_clause = {},
        year         = args.year || moment();

    if (args && args.filter_status) {
      where_clause = { status : args.filter_status };
    }

    if (args && ! args.ignore_year) {
      where_clause['$or'] = {
        date_start : {
          $between : [
            moment(year).startOf('year').format('YYYY-MM-DD'),
            moment(year).endOf('year').format('YYYY-MM-DD'),
          ]
        },
        date_end : {
          $between : [
            moment(year).startOf('year').format('YYYY-MM-DD'),
            moment(year).endOf('year').format('YYYY-MM-DD'),
          ]
        }
      };
    }

    var promise_my_leaves = this.getMy_leaves({
      // TODO here is cartesian product between leave types and users,
      // needs to be split
      include : [{
        model : sequelize.models.LeaveType,
        as    : 'leave_type',
      },{
        model : sequelize.models.User,
        as    : 'user',
        include : [{
          model : sequelize.models.Company,
          as : 'company',
          include : [{
            model : sequelize.models.BankHoliday,
            as : 'bank_holidays',
          }],
        }],
      }],
      where : where_clause,
    })

    // Fetch approvers for each leave in separate query, to avoid cartesian
    // products.
    .then(function(leaves){

      return Promise.resolve(leaves)
        .map(
          function(leave){
            return leave.promise_approver()
            .then(function(approver){
              leave.approver = approver;
              return Promise.resolve(leave);
            });
          }, {
            concurrency : 10,
          }
        );
    })

    return promise_my_leaves;
  };

  this.promise_my_active_leaves = function(args) {
    var year = args.year || moment();

    return this.promise_my_leaves({
      year          : year,
      filter_status : [
        sequelize.models.Leave.status_approved(),
        sequelize.models.Leave.status_new(),
        sequelize.models.Leave.status_pended_revoke(),
      ],
    });
  };

  // Promises leaves ever booked for current user
  this.promise_my_active_leaves_ever = function(args) {

    return this.promise_my_leaves({
      ignore_year : true,
      filter_status : [
        sequelize.models.Leave.status_approved(),
        sequelize.models.Leave.status_new(),
        sequelize.models.Leave.status_pended_revoke(),
      ],
    });
  };

  // Promise leaves that are needed to be Approved/Rejected
  //
  this.promise_leaves_to_be_processed = function(){
    return this.getSupervised_leaves({
      include : [{
        model : sequelize.models.LeaveType,
        as    : 'leave_type',
      },{
        model : sequelize.models.User,
        as    : 'user',
        include : [{
          model : sequelize.models.Company,
          as : 'company',
          include : [{
            model : sequelize.models.BankHoliday,
            as    : 'bank_holidays',
          }],
        },{
          model : sequelize.models.Department,
          as    : 'department',
        }],
      }],
      where : {
        status : [
          sequelize.models.Leave.status_new(),
          sequelize.models.Leave.status_pended_revoke()
        ]
      },
    });
  }; // END of promise_leaves_to_be_processed

  this.calculate_number_of_days_taken_from_allowence = function(args){
    var leave_type = args ? args.leave_type : null,
        leaves_to_traverse = this.my_leaves || [];

    // If leave_type was provided, we care only about leaves of that type
    if (leave_type) {
      leaves_to_traverse = _.filter(
        leaves_to_traverse,
        function(leave){ return leave.leaveTypeId === leave_type.id; }
      );
    }

    return _.reduce(
      _.map(
        _.filter(
          leaves_to_traverse,
          function (leave){ return leave.is_approved_leave(); }
        ),
        function(leave){ return leave.get_deducted_days_number(args); }
      ),
      function(memo, num){ return memo + num },
      0
    ) || 0;
  };

  // Based on leaves attached to the current user object,
  // the method does not perform any additional queries
  //
  this.get_leave_statistics_by_types = function(args){

    if (! args ) args = {};

    var statistics = {},
      limit_by_top = args.limit_by_top || false;

    this.company.leave_types.forEach(function(leave_type){
      var initial_stat = {
        leave_type : leave_type,
        days_taken : 0,
      };
      if (leave_type.limit && leave_type.limit > 0) {
        initial_stat.limit = leave_type.limit;
      }
      statistics[leave_type.id] = initial_stat;
    });

    // Calculate statistics as an object
    _.filter(
      this.my_leaves,
      function (leave){ return leave.is_approved_leave() }
    )
    .forEach(
      function(leave){

        var stat_obj = statistics[leave.leave_type.id];

        stat_obj.days_taken = stat_obj.days_taken + leave.get_deducted_days_number({
          ignore_allowance : true,
        });
      }
    );

    var statistic_arr = _.map(
      _.pairs(statistics),
      function(pair){
        return pair[1];
      }
    );

    statistic_arr = _.sortBy(
        statistic_arr,
        'days_taken'
      )
      .reverse();

    if (limit_by_top) {
      statistic_arr = _.first(statistic_arr, 4);
    }

    return _.sortBy(statistic_arr, function(rec){ return rec.leave_type.name; });
  },

  this.get_automatic_adjustment = function(args) {

    var now = (args && args.now) ? moment(args.now) : moment();

    if (
      now.year() !== moment(this.start_date).year()
      && ( ! this.end_date || moment(this.end_date).year() > now.year() )
    ){
        return 0;
    }

    var start_date = moment(this.start_date).year() === now.year()
      ? moment(this.start_date)
      : now.startOf('year'),
    end_date = this.end_date && moment(this.end_date).year() <= now.year()
      ? moment(this.end_date)
      : moment().endOf('year');

    return -1*(this.department.allowence - Math.round(
      this.department.allowence * end_date.diff(start_date, 'days') / 365
    ));
  };

  this.calculate_total_number_of_days_n_allowence = function(year) {

    // If optional paramater year was provided we need to calculate allowance
    // for that year, and if it is something other then current year,
    // adjustment should be made, return nominal setting from department
    if (year && year != moment().year()) {
      return this.department.allowence
    }

    // Get general allowence based on department
    return this.department.allowence
      + this.get_automatic_adjustment()
      // Adjust it based on current user
      + this.adjustment;
  };

  this.promise_my_leaves_for_calendar = function(args){
    var year = args.year || moment();

    return this.getMy_leaves({
      where : {
        status : { $ne : sequelize.models.Leave.status_rejected()},

        $or : {
          date_start : {
            $between : [
              moment(year).startOf('year').format('YYYY-MM-DD'),
              moment(year).endOf('year').format('YYYY-MM-DD'),
            ]
          },
          date_end : {
            $between : [
              moment(year).startOf('year').format('YYYY-MM-DD'),
              moment(year).endOf('year').format('YYYY-MM-DD'),
            ]
          }
        }
      },
    }); // End of MyLeaves
  };

  // For given leave object (not necessary one with corresponding record in DB)
  // check if current user is capable to have it, that is if user's remaining
  // vacation allowance is big enough to accommodate the leave.
  //
  // If validation fails an exceptionis thrown.
  //
  this.validate_leave_fits_into_remaining_allowance = function(args){
    var self   = this,
    leave_type = args.leave_type,
    leave      = args.leave,
    // Derive year from Leave object
    year       = args.year || moment(leave.date_start);

    // Make sure object contain all necessary data for that check
    return self.reload_with_leave_details({
      year : year.clone(),
    })
    .then(function(employee){
      return employee.reload_with_session_details();
    })
    .then(function(employee){
      return employee.company.reload_with_bank_holidays()
        .then(function(){ return Promise.resolve(employee); });
    })
    .then(function(employee){

      // Throw an exception when less than zero vacation would remain
      // if we add currently requested absence
      if (
        employee.calculate_number_of_days_available_in_allowence(
          year.format('YYYY')
        )
          -
        leave.get_deducted_days_number({
          year       : year.format('YYYY'),
          user       : employee,
          leave_type : leave_type,
        })
          <
        0
      ) {

        var error = new Error('Requested absence is longer than remaining allowance');
        error.user_message = error.toString();
        throw error;
      }

      return Promise.resolve(employee);
    })

    // Check that adding new leave of this type will not exceed maximum limit of
    // that type (if it is defined)
    .then(function(employee){
      if (
        // There is a limit for current type
        leave_type.limit
        // ... and lemit is bigger than zero
        && leave_type.limit > 0
      ) {

        // ... sum of used dayes for this limit is going to be bigger then limit
        var would_be_used = employee.calculate_number_of_days_taken_from_allowence({
            year             : year.format('YYYY'),
            leave_type       : leave_type,
            ignore_allowance : true,
          })
            +
          leave.get_deducted_days_number({
            year             : year.format('YYYY'),
            user             : employee,
            leave_type       : leave_type,
            ignore_allowance : true,
          });

        if (would_be_used > leave_type.limit) {

          var error = new Error('Adding requested '+leave_type.name
            +" absense would exceed maximum allowed for such type by "
            +(would_be_used - leave_type.limit)
          );

          error.user_message = error.toString();
          throw error;
        }
      }
    });
  };

};


text:
/* Authors: Lutong Wang and Bangqi Xu */
/*
 * Copyright (c) 2019, The Regents of the University of California
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the University nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _FR_FLEXGC_H_
#define _FR_FLEXGC_H_

#include <memory>

#include "frDesign.h"

namespace fr {
class drNet;
class drPatchWire;
class FlexDRWorker;
class gcNet;
class gcPin;

class FlexGCWorker
{
 public:
  // constructors
  FlexGCWorker(frTechObject* techIn,
               Logger* logger,
               FlexDRWorker* drWorkerIn = nullptr);
  ~FlexGCWorker();
  // setters
  void setExtBox(const Rect& in);
  void setDrcBox(const Rect& in);
  bool setTargetNet(frBlockObject* in);
  gcNet* getTargetNet();
  void resetTargetNet();
  void addTargetObj(frBlockObject* in);
  void setTargetObjs(const std::set<frBlockObject*>& targetObjs);
  void setIgnoreDB();
  void setIgnoreMinArea();
  void setIgnoreLongSideEOL();
  void setIgnoreCornerSpacing();
  void setEnableSurgicalFix(bool in);
  void addPAObj(frConnFig* obj, frBlockObject* owner);
  // getters
  std::vector<std::unique_ptr<gcNet>>& getNets();
  gcNet* getNet(frNet* net);
  frDesign* getDesign() const;
  const std::vector<std::unique_ptr<frMarker>>& getMarkers() const;
  const std::vector<std::unique_ptr<drPatchWire>>& getPWires() const;
  // others
  void init(const frDesign* design);
  int main();
  void end();
  // initialization from FlexPA, initPA0 --> addPAObj --> initPA1
  void initPA0(const frDesign* design);
  void initPA1();
  void updateDRNet(drNet* net);
  // used in rp_prep
  void checkMinStep(gcPin* pin);
  void updateGCWorker();

 private:
  class Impl;
  std::unique_ptr<Impl> impl_;
};
}  // namespace fr

#endif


text:
package com.google.gwt.inject.client.binder;

import java.lang.annotation.Annotation;

/**
 * Builder returned from calls to expose, used to add an (optional) annotation
 * to the element that is being exposed.  This is similar to
 * {@link GinAnnotatedBindingBuilder} but doesn't allow specifying a value.
 * See the EDSL examples at {@link GinBinder}.
 */
public interface GinAnnotatedElementBuilder {
  /**
   * See the EDSL examples at {@link GinBinder}.
   */
  void annotatedWith(Class<? extends Annotation> annotationType);

  /**
   * See the EDSL examples at {@link GinBinder}.
   */
  void annotatedWith(Annotation annotation);
}


text:
package org.apache.calcite.sql.validate;

import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlIdentifier;

import java.util.Map;

/**
 * A scope which contains nothing besides a few parameters. Like
 * {@link EmptyScope} (which is its base class), it has no parent scope.
 *
 * @see ParameterNamespace
 */
public class ParameterScope extends EmptyScope {
  //~ Instance fields --------------------------------------------------------

  /**
   * Map from the simple names of the parameters to types of the parameters
   * ({@link RelDataType}).
   */
  private final Map<String, RelDataType> nameToTypeMap;

  //~ Constructors -----------------------------------------------------------

  public ParameterScope(
      SqlValidatorImpl validator,
      Map<String, RelDataType> nameToTypeMap) {
    super(validator);
    this.nameToTypeMap = nameToTypeMap;
  }

  //~ Methods ----------------------------------------------------------------

  public SqlIdentifier fullyQualify(SqlIdentifier identifier) {
    return identifier;
  }

  public SqlValidatorScope getOperandScope(SqlCall call) {
    return this;
  }

  public SqlValidatorNamespace resolve(
      String name,
      SqlValidatorScope[] ancestorOut,
      int[] offsetOut) {
    final RelDataType type = nameToTypeMap.get(name);
    return new ParameterNamespace(validator, type);
  }
}

// End ParameterScope.java


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.17-3-28
description: Array.prototype.some - value of 'length' is boundary value (2^32)
---*/

        var accessed = false;

        function callbackfn(val, idx, obj) {
            accessed = true;
            return val > 10;
        }

        var obj = {
            0: 12,
            length: 4294967296
        };

assert(Array.prototype.some.call(obj, callbackfn), 'Array.prototype.some.call(obj, callbackfn) !== true');
assert(accessed, 'accessed !== true');


text:
using System;
using System.Collections.Generic;
using System.Text;
using Gallio.Common.Diagnostics;

namespace Gallio.Runtime.Logging
{
    /// <summary>
    /// The severity prefix logger wraps another loggers and encodes the severity of a
    /// log entry into the log message itself in a standard form.
    /// </summary>
    /// <remarks>
    /// <para>
    /// This wrapper is useful when the base logger may not be able to
    /// report the severity via other means or when severity information must be
    /// reconstructed from plain text.
    /// </para>
    /// </remarks>
    /// <seealso cref="SeverityPrefixParser"/>
    public class SeverityPrefixLogger : BaseLogger
    {
        private readonly ILogger inner;

        internal static readonly Dictionary<LogSeverity, string> SeverityPrefixes = new Dictionary<LogSeverity, string>()
        {
            { LogSeverity.Debug, "[Debug] " },
            { LogSeverity.Info, "[Info] " },
            { LogSeverity.Important, "[Important] " },
            { LogSeverity.Warning, "[Warning] " },
            { LogSeverity.Error, "[Error] " },
        };

        /// <summary>
        /// Creates a prefix logger.
        /// </summary>
        /// <param name="inner">The inner logger.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="inner"/> is null.</exception>
        public SeverityPrefixLogger(ILogger inner)
        {
            if (inner == null)
                throw new ArgumentNullException("inner");

            this.inner = inner;
        }

        /// <inheritdoc />
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            inner.Log(severity, SeverityPrefixes[severity] + message, exceptionData);
        }
    }
}


text:
namespace views {
class Separator;
}  // namespace views

namespace ash {
namespace tray {
class BluetoothDetailedView;
}  // namespace tray

class BluetoothDeviceListItemView;
class TriView;

// BluetoothDeviceListController implementation.
class ASH_EXPORT BluetoothDeviceListControllerImpl
    : public BluetoothDeviceListController {
 public:
  explicit BluetoothDeviceListControllerImpl(
      tray::BluetoothDetailedView* bluetooth_detailed_view);
  BluetoothDeviceListControllerImpl(const BluetoothDeviceListControllerImpl&) =
      delete;
  BluetoothDeviceListControllerImpl& operator=(
      const BluetoothDeviceListControllerImpl&) = delete;
  ~BluetoothDeviceListControllerImpl() override;

 private:
  friend class BluetoothDeviceListControllerTest;

  // BluetoothDeviceListController:
  void UpdateBluetoothEnabledState(bool enabled) override;
  void UpdateDeviceList(
      const PairedBluetoothDevicePropertiesPtrs& connected,
      const PairedBluetoothDevicePropertiesPtrs& previously_connected) override;

  // Creates a sub-header with text represented by the |text_id| message ID when
  // |sub_header| is |nullptr|, otherwise uses the provided |sub_header|. The
  // used sub-header is then moved to index |index| within the device list and
  // returned.
  TriView* CreateSubHeaderIfMissingAndReorder(TriView* sub_header,
                                              int text_id,
                                              int index);

  // Creates and initializes a view for each of the device properties within
  // |device_property_list| if a view does not already exist, otherwise re-using
  // the existing view to avoid disrupting a11y. Each view will be reordered to
  // start at |index| and will be removed from |previous_views|. The index of
  // the position after the final view that was added is returned.
  int CreateViewsIfMissingAndReorder(
      const PairedBluetoothDevicePropertiesPtrs& device_property_list,
      base::flat_map<std::string, BluetoothDeviceListItemView*>* previous_views,
      int index);

  tray::BluetoothDetailedView* bluetooth_detailed_view_;

  bool is_bluetooth_enabled_ = false;
  base::flat_map<std::string, BluetoothDeviceListItemView*>
      device_id_to_view_map_;
  views::Separator* device_list_separator_ = nullptr;
  TriView* connected_sub_header_ = nullptr;
  TriView* no_device_connected_sub_header_ = nullptr;
  TriView* previously_connected_sub_header_ = nullptr;
};

}  // namespace ash

#endif  // ASH_SYSTEM_BLUETOOTH_BLUETOOTH_DEVICE_LIST_CONTROLLER_IMPL_H_


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

    <artifactId>msg-job-client</artifactId>

</project>