text:
var active = 0;
var navs = [];
$(document).ready(function() {
  $(".nav-link").map(function() { navs.push($(this).attr("data-target")); });

  $(".nav-link").on("click", function() { showContent($(this).attr("data-target")); });
});

function showContent(currId) {
  $(".content-box").addClass("hidden");
  $("#" + currId).removeClass("hidden");
  $("#" + currId).addClass("slideInRight");
  active = navs.indexOf(currId);
  $(".nav-link").removeClass("active slideInLeft");
  document.getElementsByClassName("nav-link")[active].className += " slideInLeft active";
}

$(window).bind("DOMMouseScroll mousewheel", function(e) {
  active =
    e.originalEvent.wheelDelta / 120 > 0 ? (active - 1) % navs.length : (active + 1) % navs.length;
  if (active < 0) {active = navs.length - 1; }
  showContent(navs[active]);
});


text:
namespace crashpad {
namespace test {

//! \brief Facilitates the launching of child processes from unit tests.
class WinChildProcess {
 public:
  //! \brief Groups handles used to communicate with, observe, and manage a
  //!     child process.
  struct Handles {
    //! \brief A handle to read from an anonymous pipe shared with the child
    //!     process.
    ScopedFileHANDLE read;
    //! \brief A handle to write to an anonymous pipe shared with the child
    //!     process.
    ScopedFileHANDLE write;
    //! \brief A handle to the child process.
    ScopedKernelHANDLE process;
  };

  WinChildProcess();
  virtual ~WinChildProcess() {}

  //! \brief Returns true if the current process is a child process.
  static bool IsChildProcess();

  //! \brief Runs the child process defined by T if the current process is a
  //!     child process; does not return in that case. Otherwise, returns.
  template <class T>
  static void EntryPoint() {
    if (IsChildProcess()) {
      // The static_cast here will cause a compiler failure if T is not a
      // subclass of WinChildProcess. It's the constructor of WinChildProcess
      // that performs the pipe handshake with the parent process (without which
      // we would have a hang).
      T child_process;
      int result = static_cast<WinChildProcess*>(&child_process)->Run();
      exit(result);
    }
  }

  //! \brief Launches a child process and returns the Handles for that process.
  //!     The process is guaranteed to be executing by the time this method
  //!     returns. Returns null and logs a GTest failure in case of failure.
  static scoped_ptr<Handles> Launch();

 protected:
  //! \brief Returns a handle to read from an anonymous pipe shared with the
  //!     parent process.
  //!
  //! It is an error to call this after CloseReadPipe() has been called.
  //!
  //! \return The read pipe's file handle.
  FileHandle ReadPipeHandle() const;

  //! \brief Returns a handle to write to an anonymous pipe shared with the
  //!     parent process.
  //!
  //! It is an error to call this after CloseWritePipe() has been called.
  //!
  //! \return The write pipe's file handle.
  FileHandle WritePipeHandle() const;

  //! \brief Closes the read pipe.
  //!
  //! ReadPipeHandle() must not be called after this.
  void CloseReadPipe();

  //! \brief Closes the write pipe.
  //!
  //! An attempt to read from the read pipe in the parent process will indicate
  //! end-of-file. WritePipeHandle() must not be called after this.
  void CloseWritePipe();

 private:
  //! \brief The subclass-provided child routine.
  //!
  //! Subclasses must implement this method to define how the child operates.
  //! Subclasses may exit with a failure status by using `LOG(FATAL)`,
  //! `abort()`, or similar. They may also exit by returning their exit code
  //! from this method. It is up to the client to observe and interpret the
  //! child's exit code.
  //!
  //! \return The child process exit code.
  virtual int Run() = 0;

  ScopedFileHANDLE pipe_read_;
  ScopedFileHANDLE pipe_write_;

  DISALLOW_COPY_AND_ASSIGN(WinChildProcess);
};

}  // namespace test
}  // namespace crashpad

#endif  // CRASHPAD_TEST_WIN_WIN_CHILD_PROCESS_H_

redpajama_set_name: RedPajamaGithub


text:
Processing gui version of composite video simulator.

Please install ControlP5 library first.
Works with Processing 2.x

* Original code: https://github.com/joncampbell123/composite-video-simulator
* Processing code: https://github.com/tsulej/GenerateMe/tree/master/composite_video_simulator
* Gui code by Atagen: https://github.com/atagen/Atagen


text:
AlephRecord structure
=====================

.. automodule:: aleph.datastructures.alephrecord
    :members:
    :undoc-members:


text:
class Operation
end


text:
"""

MCMC utility module

Formulas based on "Monte Carlo Statistical Methods"  (Robert & Casella: 2nd Ed. 2004)

The underlying idea is as follows:

The mcmc framework describes simulation techniques which can be adapted to e.g. trace out
a hyperdimensional surface of any adequately smooth function parameterized by a set of tunable parameters.
The fashion in which the surface is explored has in some scenarios significant advantages over e.g. a
brute-force type of search which places unnecessary weight on "uninteresting" parts of the parameter space due
to the nature of its sampling scheme. This is especially true when the function to be evaluated is expensive to
compute wrt CPU-time.

The mcmc scheme is Bayesian in nature. The mode of the function depends on the "best-estimates" of parameters. But
each parameter has its own distribution (which allows us to inspect the uncertainty in our estimate) which we can
observe in 1D by marginalizing over all other parameters: in a frequentist paradigm one thinks of each parameter
estimate as a point-estimate which does not have any certainty by itself (the uncertainty is captured in the target
function only).

While interesting in its own right, we will not consider parameter distributions here: we are purely interested in
optimizing the target function (our machine learning model) with respect to the performance metric.

Notes:

* Implement a stopping criterion:
    1) stop after N iterations
    2) stop when function cannot be further optimized withing a set tolerance
    3)

* As the algo will run on a single machine we cannot use the "intra- and between chain variance" stopping criterion.
  (This variable is normally referred to as 'R' in the literature. See e.g. Rubin.)

*

"""

if __name__ == '__main__':
    import sys
    sys.exit(-1)


text:
export class HTTPError extends Error {
  constructor(status:number, msg: string) {
    super(msg);
    this.message = msg;
    this.status = status;
  }

  status: number;
}

export class ConnectionBrokenError extends  HTTPError {
  constructor() {
    super(0, 'Connection to server broken');
  }
}

export class AuthenticationRequiredError extends HTTPError {
  constructor() {
    super(401, 'Authentication required');
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Frequently Asked Questions (FAQ) — CaaStle 0.0.1 documentation</title>
    <link rel="stylesheet" href="_static/sphinxdoc.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="Roadmap" href="roadmap.html" />
    <link rel="prev" title="CaaStle CLI" href="cli.html" />

Navigation

          next

          previous |

CaaStle 0.0.1 documentation »

Previous topic

CaaStle CLI

Next topic

Roadmap

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Frequently Asked Questions (FAQ)

How is Platform-as-Code (PaC) different from Platform-as-a-Service (PaaS)?

Platform-as-Code is a non-hosted implementation of platform functionality.
There is no private / public hosted central server like PaaSes.
This approach helps improve dev/prod parity and ability to recreate application environments anywhere.

How is Platform-as-Code (PaC) different from Infrastructure-as-Code (IaC)?

Infrastructure-as-Code implementation treats every platform element as infrastructure resource.
In contrast, Platform-as-Code offers application-centric abstractions that simplify modeling a deployment as per the application architecture.

How does Platform-as-Code (PaC) approach compare with language-based deployment approach of Metaparticle?

Metaparticle provides cloud deployment primitives that can be integrated directly within an application's code.
It is essentially a reusable deployment library.
Platform-as-Code (PaC) approach is language neutral. It provides high-level abstractions for defining the
entire stack of a containerized cloud application. It leverages popular declarative definition formats such as Kubernetes yaml format for application definition.

How does CaaStle strike balance between high-level abstractions and providing control when needed?

CaaStle tries to balance the fine line between abstraction and control through following three aspects of its design:

First, for defining platform elements in environment yaml file, CaaStle plans to support all the attributes that
the corresponding cloud resource exposes. For the platform elements that are currently supported in CaaStle - AWS RDS,
AWS ECS, Google Cloud SQL, Google GKE - limited set of attributes are supported in the yaml file. But we will be
supporting all the settable attributes soon. (In the mean time if you are interested in any particular attribute,
file a Github issue and we will add it to CaaStle).

Second, for microservices definition we take a two pronged approach. For applications that involve a single container, we
support a simple application definition format that supports minimal set of attributes which would be typically used
to deploy such applications. These attributes include, image uri, container_port, host_port, environment
variables. For multi-container applications we support Kubernetes's native yaml file. You can define your container Pods
in Kubernetes's standard format. We require you to define a single file containing all your Pod definitions in it.

Third, we provide the mechanism of environment-specific shell (see below) through which you can execute native commands specific to the resources in the environment.
For instance, when developing/deploying your applications on GKE, you might want to execute "kubectl get pods" to
see if your application's Pods have started up on the GKE cluster. Or you might want to execute "kubectl describe pods <podname>"
to see what caused a Pod from not starting up. The environment-specific shell allows you to execute all such commands
without requiring you to install and setup cloud CLIs on your machines.

What is environment-specific shell in CaaStle?

CaaStle provides cld env shell command that can be used to get a environment-specific shell.
This shell allows you to execute cloud-native CLI commands corresponding to the platform elements in that environment, e.g. 'gcloud sql', 'aws rds', 'kubectl', etc.
This shell can be quite handy when you are developing applications using CaaStle.
It offers a great tool for traceability without having to setup number of CLI tools.

Who are the target users of CaaStle?

Development teams developing containerized cloud applications that run on public clouds like AWS or Google cloud.

What are the typical use-cases of CaaStle?

CaaStle is targeted as a common tool between developers and operations engineers.
CaaStle provides easy way for developers and ops to collaborate on declarative platform definitions.
Developers can use CaaStle as local development environment, along with Docker.
Ops engineers can integrate CaaStle-based application deployment workflow in their standard Jenkins like DevOps workflow.
CaaStle's features of application-centric shell, full-stack platform elements association view,
and environment change history (upcoming) are useful for developers and ops engineers alike when
debugging application behaviors or managing environments.

How does CaaStle differ from Infrastructure-as-Code tools such as Terraform or AWS CloudFormation?

CaaStle provides application-centric abstractions whereas IaC tools work with infrastructure abstractions.

How does CaaStle differ from cloud native PaaSes like AWS Elastic Beanstalk or Google App Engine?

CaaStle is a non-hosted implementation of platform functionality. It integrates with Cloud-based
container orchestration engine systems directly from your laptop. PaaSes introduce an additional hosted indirection which makes them opaque for application developers.

Navigation

          next

          previous |

CaaStle 0.0.1 documentation »


text:
package models

type LastOperationFields struct {
	Type        string
	State       string
	Description string
	CreatedAt   string
	UpdatedAt   string
}

type ServiceInstanceCreateRequest struct {
	Name      string                 `json:"name"`
	SpaceGUID string                 `json:"space_guid"`
	PlanGUID  string                 `json:"service_plan_guid,omitempty"`
	Params    map[string]interface{} `json:"parameters,omitempty"`
	Tags      []string               `json:"tags,omitempty"`
}

type ServiceInstanceUpdateRequest struct {
	PlanGUID string                 `json:"service_plan_guid,omitempty"`
	Params   map[string]interface{} `json:"parameters,omitempty"`
	Tags     []string               `json:"tags"`
}

type ServiceInstanceFields struct {
	GUID             string
	Name             string
	LastOperation    LastOperationFields
	SysLogDrainURL   string
	RouteServiceURL  string
	ApplicationNames []string
	Params           map[string]interface{}
	DashboardURL     string
	Tags             []string
}

type ServiceInstance struct {
	ServiceInstanceFields
	ServiceBindings []ServiceBindingFields
	ServiceKeys     []ServiceKeyFields
	ServicePlan     ServicePlanFields
	ServiceOffering ServiceOfferingFields
}

func (inst ServiceInstance) IsUserProvided() bool {
	return inst.ServicePlan.GUID == ""
}


text:
var fs = require('fs');
var request = require('request');

var nuget = './nuget.exe';

console.info('Downloading \'nuget.exe\'...');
console.info();

request
    .get('https://dist.nuget.org/win-x86-commandline/v5.10.0/nuget.exe')
    .on('error', function (err) {
        console.error(err);
    })
    .on('response', function (response) {
        if (response.statusCode == 200) {
            console.info('Successfully downloaded \'nuget.exe\'.');
        } else {
            console.error('Downloading \'nuget.exe\' failed. statusCode \'' + response.statusCode + '\'');
        }
    })
    .pipe(fs.createWriteStream(nuget));


text:
#ifndef STAN_MATH_PRIM_FUN_PROJ_HPP
#define STAN_MATH_PRIM_FUN_PROJ_HPP

#include <stan/math/prim/fun/is_inf.hpp>
#include <complex>
#include <limits>

namespace stan {
namespace math {
/**
 * Return the projection of the complex argument onto the Riemann
 * sphere.
 *
 * @tparam V value type of argument
 * @param[in] z argument
 * @return projection of the argument onto the Riemann sphere
 */
template <typename V>
inline std::complex<V> proj(const std::complex<V>& z) {
  return std::proj(z);
}

namespace internal {
/**
 * Return the projection of the complex argument onto the Riemann
 * sphere.
 *
 * @tparam V value type of argument
 * @param[in] z argument
 * @return projection of the argument onto the Riemann sphere
 */
template <typename V>
inline std::complex<V> complex_proj(const std::complex<V>& z) {
  if (is_inf(z.real()) || is_inf(z.imag())) {
    return {std::numeric_limits<V>::infinity(), z.imag() < 0 ? -0.0 : 0.0};
  }
  return z;
}
}  // namespace internal
}  // namespace math
}  // namespace stan

#endif


text:
[CmdletBinding()]
param()

. $PSScriptRoot\..\..\..\Tests\lib\Initialize-Test.ps1
. $PSScriptRoot\MockVariable.ps1 -Force
. $PSScriptRoot\MockHelper.ps1 -Force

Unregister-Mock Get-VstsInput
Unregister-Mock Start-Job
Unregister-Mock Receive-Job
Unregister-Mock Get-Job
Unregister-Mock Remove-Job
Unregister-Mock Start-Sleep
Unregister-Mock Import-Module

Register-Mock Get-VstsInput { return $EnvironmentNameForFailedJob } -ParametersEvaluator{ $Name -eq  "MachineNames" }
Register-Mock Get-VstsInput { return $password } -ParametersEvaluator{ $Name -eq  "AdminPassword" }
Register-Mock Get-VstsInput { return $validSourcePackage } -ParametersEvaluator{ $Name -eq  "SourcePath" }
Register-Mock Get-VstsInput { return $validApplicationPath } -ParametersEvaluator{ $Name -eq  "TargetPath" }
Register-Mock Get-VstsInput { return $false } -ParametersEvaluator{ $Name -eq  "CleanTargetBeforeCopy" }
Register-Mock Get-VstsInput { return $true } -ParametersEvaluator{ $Name -eq  "CopyFilesInParallel" }

Register-Mock Receive-Job { }  -ParametersEvaluator { $Id -eq 1 }
Register-Mock Receive-Job { throw "Copy to one or more machines failed." }  -ParametersEvaluator { $Id -eq 2 }

#Start-Job Register-Mocks
Register-Mock Start-Job { $testJobs.Add($Job1); return $job1} -ParametersEvaluator{$ArgumentList -contains $validResource1.Name }
Register-Mock Start-Job { $testJobs.Add($Job2); return $job2} -ParametersEvaluator{$ArgumentList -contains $validResource1Duplicate.Name -and $ArgumentList -contains $environmentWinRMHttpPortForDuplicateResource }
Register-Mock Start-Job { $testJobs.Add($Job2); return $job2} -ParametersEvaluator{$ArgumentList -contains $validResource2.Name }

#Get-Job Register-Mocks
Register-Mock Get-Job { return $testJobs }

#Start-Sleep Register-Mocks
Register-Mock Start-Sleep { }

#Remove-Job Register-Mocks
Register-Mock Remove-Job { $testJobs.RemoveAt(0) }

Register-Mock Register-Environment { return GetEnvironmentWithStandardProvider $EnvironmentNameForFailedJob  } -ParametersEvaluator{$EnvironmentName -eq $EnvironmentNameForFailedJob}

#Import-Module Register-Mocks
Register-Mock Import-Module { }

Assert-Throws {
    & "$copyFilesToMachinesPath"
} -MessagePattern "Copy to one or more machines failed."


text:
.. ExTASY-0.2 documentation master file, created by
   sphinx-quickstart on Tue Jun 16 13:24:49 2015.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

ExTASY |VERSION|
================

.. toctree::
   :maxdepth: 4

**Github Page**

https://github.com/radical-cybertools/ExTASY

**Mailing List**

* Users : https://groups.google.com/forum/#!forum/extasy-project
* Developers : https://groups.google.com/forum/#!forum/extasy-devel

**Build Status**

    .. image:: http://ci.radical-project.org/buildStatus/icon?job=ExTASY-0.2
        :target: http://ci.radical-project.org/job/ExTASY-0.2

**Contents**

.. toctree::
   :numbered:
   :maxdepth: 3

   pages/intro.rst
   pages/installation.rst
   pages/getting_started.rst
   pages/examples.rst
   pages/coam.rst
   pages/grlsd.rst
   pages/apiref.rst
   pages/develop.rst
   pages/resources.rst
   pages/trouble.rst
   pages/misc.rst

Indices and tables
==================

* :ref:`genindex`
* :ref:`search`

.. |VERSION| replace:: 0.2


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

namespace CoreAudioApi.Interfaces
{/// <summary>
    /// Stores information about an audio jack sink.
    /// </summary>
    /// <remarks>
    /// MSDN Reference: http://msdn.microsoft.com/en-us/library/dd316549.aspx
    /// </remarks>
    [StructLayout(LayoutKind.Sequential)]
    internal struct KSJACK_SINK_INFORMATION
    {
        /// <summary>
        /// Specifies the type of connection.
        /// </summary>
        [MarshalAs(UnmanagedType.I4)]
        public Int32 ConnType;

        /// <summary>
        /// Specifies the sink manufacturer identifier.
        /// </summary>
        [MarshalAs(UnmanagedType.U2)]
        public UInt16 ManufacturerId;

        /// <summary>
        /// Specifies the sink product identifier.
        /// </summary>
        [MarshalAs(UnmanagedType.U2)]
        public UInt16 ProductId;

        /// <summary>
        /// Specifies the latency of the audio sink.
        /// </summary>
        [MarshalAs(UnmanagedType.U2)]
        public UInt16 AudioLatency;

        /// <summary>
        /// Specifies whether the sink supports High-bandwidth Digital Content Protection (HDCP).
        /// </summary>
        [MarshalAs(UnmanagedType.Bool)]
        public bool HDCPCapable;

        /// <summary>
        /// Specifies whether the sink supports ACP Packet, ISRC1, or ISRC2.
        /// </summary>
        [MarshalAs(UnmanagedType.Bool)]
        public bool AICapable;

        /// <summary>
        /// Specifies the length of the string in the SinkDescription member.
        /// </summary>
        [MarshalAs(UnmanagedType.U1)]
        public byte SinkDescriptionLength;
    }
}


text:
/**
 *
 * The classes in this package represent the JPA implementation
 * of PetClinic's persistence layer.
 *
 */
package com.rambird.repository.jpa;


text:
/*
 * directory.h
 *
 * Functions used to deal with directory entries.
 */

#ifndef DIRECTORY_H
#define DIRECTORY_H

/* Add stuff in here */

#endif


text:
package com.cathive.fx.credits;

import java.net.URL;

import javafx.util.Builder;

/**
 *
 * @author Benjamin P. Jung
 */
public final class LicenseBuilder implements Builder<License> {

    private String id;
    private String name;
    private URL url;

    private LicenseBuilder() {
        super();
    }

    public LicenseBuilder create() {
        return new LicenseBuilder();
    }

    @Override
    public License build() {
        final License license = new License();
        license.setId(id);
        license.setName(name);
        license.setUrl(url);
        return license;
    }

    public LicenseBuilder id(final String id) {
        this.id = id;
        return this;
    }

    public LicenseBuilder name(final String name) {
        this.name = name;
        return this;
    }

    public LicenseBuilder url(final URL url) {
        this.url = url;
        return this;
    }

}


text:
"use strict";

var path = require("path");

var rootPath = path.normalize(__dirname + "/..");

module.exports = {
    development: {
        port: 8888,
        path: {
            root: rootPath,
            views: path.join(rootPath, "views")
        }
    }
};


text:
namespace NPOI.SS.Formula.Functions
{
    using System;
    using NPOI.SS.Formula.Eval;
    /**
 * Common interface for the matching criteria.
 */
    internal interface I_MatchPredicate
    {
        bool Matches(ValueEval x);
    }
    internal interface I_MatchAreaPredicate : I_MatchPredicate
    {
        bool Matches(TwoDEval x, int rowIndex, int columnIndex);
    }
    /**
     * Common logic for COUNT, COUNTA and COUNTIF
     *
     * @author Josh Micich
     */
    class CountUtils
    {

        private CountUtils()
        {
            // no instances of this class
        }

        /**
         * @return 1 if the evaluated cell matches the specified criteria
         */
        public static int CountMatchingCell(RefEval refEval, I_MatchPredicate criteriaPredicate)
        {
            if (criteriaPredicate.Matches(refEval.InnerValueEval))
            {
                return 1;
            }
            return 0;
        }
        public static int CountArg(ValueEval eval, I_MatchPredicate criteriaPredicate)
        {
            if (eval == null)
            {
                throw new ArgumentException("eval must not be null");
            }
            if (eval is TwoDEval)
            {
                return CountUtils.CountMatchingCellsInArea((TwoDEval)eval, criteriaPredicate);
            }
            if (eval is RefEval)
            {
                return CountUtils.CountMatchingCell((RefEval)eval, criteriaPredicate);
            }
            return criteriaPredicate.Matches(eval) ? 1 : 0;
        }
        /**
	 * @return the number of evaluated cells in the range that match the specified criteria
	 */
        public static int CountMatchingCellsInArea(TwoDEval areaEval, I_MatchPredicate criteriaPredicate)
        {
            int result = 0;

            int height = areaEval.Height;
            int width = areaEval.Width;
            for (int rrIx = 0; rrIx < height; rrIx++)
            {
                for (int rcIx = 0; rcIx < width; rcIx++)
                {
                    ValueEval ve = areaEval.GetValue(rrIx, rcIx);

                    if (criteriaPredicate is I_MatchAreaPredicate)
                    {
                        I_MatchAreaPredicate areaPredicate = (I_MatchAreaPredicate)criteriaPredicate;
                        if (!areaPredicate.Matches(areaEval, rrIx, rcIx)) continue;
                    }

                    if (criteriaPredicate.Matches(ve))
                    {
                        result++;
                    }
                }
            }
            return result;
        }
    }
}


text:
package org.ecg.refdata.ejb.generator;

import org.ecg.refdata.datasource.ejb.PersistenceDataSourceSB;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.ecg.refdata.datasource.entities.NameAndDescriptionItem;
import org.ecg.refdata.datasource.entities.codeDescription.CodeDescriptionItem;
import org.ecg.refdata.datasource.entities.commons.ReferenceDataAbstractDataType;
import org.ecg.refdata.datasource.entities.simpleItem.SimpleItemDataType;
import org.ecg.refdata.datasource.entities.simpleItem.SimpleItemItem;
import org.ecg.refdata.datasource.xml.ReferenceData;
import org.ecg.refdata.datasource.xml.XMLFileDataSource;
import org.ecg.refdata.exceptions.ReferenceDataSourceInternalException;

/**
 * Testing servlet for generating sample data for EJB persistence
 *
 */
public class SampleGenerator extends javax.servlet.http.HttpServlet implements
        javax.servlet.Servlet {

    private static final long serialVersionUID = 1L;

    // private static Logger logger = Logger.getLogger(SampleGenerator.class
    // .getName());
    private final static String XML_SUFFIX = "xml";

    private String filesSource = "C:\\workspaceEE\\skg-referencedata\\skg-referencedata-tests\\skg-referencedata-sampledata-generator\\src\\main\\resources\\com\\skg\\refdata\\defaultsXml";

    PersistenceDataSourceSB persistenceBean;

    public SampleGenerator() {
        super();
    }

    /*
      * (non-Java-doc)
      *
      * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
      * HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doProcess(request, response);
    }

    /*
      * (non-Java-doc)
      *
      * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
      * HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doProcess(request, response);
    }

    private void doProcess(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();

        out.println("");
        out.println("");
        out.println("");

        out.println("");

        String requiredIp = request.getParameter("ip");

        String jnpName = request.getParameter("jnp");

        String requiredInterface = request.getParameter("group1");

        filesSource = request.getParameter("src");

        out.println("
requiredIp
" + requiredIp);
        out.println("
jnpName
" + jnpName);
        out.println("
RequiredInterface
" + requiredInterface);
        out.println("
Dictionaries source
" + filesSource);

        out.println("Home directory: " + System.getProperty("user.dir"));

        Context ctx;

        try {

            Properties properties = new Properties();

//            properties.put("java.naming.factory.initial",
//                    "org.jnp.interfaces.NamingContextFactory");
//            properties.put("java.naming.factory.url.pkgs",
//                    "org.jboss.naming rg.jnp.interfaces");
            properties.put("java.naming.factory.initial",
                    "org.apache.openejb.client.RemoteInitialContextFactory");
            properties.put("java.naming.provider.url", "" + requiredIp);

            ctx = new InitialContext(properties);

            out.println("Getting ejbPersistence instance
");

            persistenceBean = (PersistenceDataSourceSB) ctx.lookup(jnpName);// + "/"+ requiredInterface);

            out.println("Reference to EJBFacade Datasource successfully obtained
");

            out.println("
List of input xml files

");

            out.println("
Persisting data:

");

           generateDataXML(filesSource, persistenceBean);

        } catch (Exception e) {

            e.printStackTrace();

        }

        out.println("");
        out.println("");

        out.close();

    }

    public void generateDataXML(String path, PersistenceDataSourceSB ejbInterface) {

        XMLFileDataSource xmlFileDataSource = new XMLFileDataSource();
        xmlFileDataSource.setUseEmbeddedData(false);
        xmlFileDataSource
                .setFilesSource(path);
        try {
            xmlFileDataSource.initializeReferenceDataMap();
        } catch (ReferenceDataSourceInternalException e) {
            e.printStackTrace();
        }

        Map<String, ReferenceData> referenceDataMap = xmlFileDataSource
                .getMapReferenceData();

        for (Map.Entry<String, ReferenceData> xmlReferenceDataEntry : referenceDataMap
                .entrySet()) {

            ReferenceData xmlReferenceData = xmlReferenceDataEntry
                    .getValue();
            String dictionaryId = xmlReferenceDataEntry.getKey();

            SimpleItemDataType simType = new SimpleItemDataType();

            System.out.println("Id slownika: " + dictionaryId);
            simType.setRefDataId(dictionaryId);
            simType.setOrigin("PL");
            simType.setSource("PL");
            simType.setLastChange(new Date());
            simType.setItemCodeType("PL110");
            simType.setItemType("itemType");

            // public SimpleItemItem(
            // ReferenceDataAbstractDataTypeEntity referenceDataTypeEntity) {
            // super(referenceDataTypeEntity);
            // }

            for (ReferenceData.SimpleItem simpleItem : xmlReferenceData.getSimpleItem()) {
                SimpleItemItem simpleItemItem = new SimpleItemItem(simType);
                simpleItemItem.setCode(simpleItem.getCode());
                // simpleItemItem.setNational(simpleItem.getNational());
                // prefer to use our date

                SimpleDateFormat sdf = new SimpleDateFormat();
                sdf.applyPattern("MM/dd/yyyy");

                Date validFrom = new Date();
                Date validTo = new Date();

                try {
                    validFrom = sdf.parse("17/10/2007");
                    validTo = sdf.parse("17/10/2035");
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                simpleItemItem.setValidFrom(validFrom);
                simpleItemItem.setValidTo(validTo);

                for (ReferenceData.SimpleItem.CodeDescription codeDescription : simpleItem.getCodeDescription()) {
                    CodeDescriptionItem codeDescriptionItem = new CodeDescriptionItem(
                            codeDescription.getDescription(), codeDescription
                            .getLanguageCode(), simpleItemItem);
                    simpleItemItem.addCodeDescriptionItems(codeDescriptionItem);

                }
                simType.addReferenceDataAbstractItemEntity(simpleItemItem);
                //simpleItemItem.setReferenceDataAbstractDataTypeEntity(simType)
                // ;

            }

            for (ReferenceData.NameAndDescription nameAndDescription : xmlReferenceData
                    .getNameAndDescription()) {
                NameAndDescriptionItem nameAndDescriptionItem = new NameAndDescriptionItem(
                        nameAndDescription.getName(), nameAndDescription
                        .getDescription(), nameAndDescription
                        .getLanguageCode(), simType);
                simType.addNameAndDescriptionItem(nameAndDescriptionItem);

            }
            ReferenceDataAbstractDataType ref = simType;
            ref.setVersionNumber(0);
            try {
                ejbInterface.persistReferenceDataAbstractDataType(ref);
                System.out.println("Dictionary with id: " + ref.getRefDataId()
                        + " added to database");
            } catch (Exception x) {
                x.printStackTrace();
            }
        }
    }
}


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.bitcoinj.core;

import static com.google.common.base.Preconditions.checkArgument;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Nullable;

import org.bitcoinj.crypto.TransactionSignature;

public class TransactionWitness {
    public static final TransactionWitness EMPTY = new TransactionWitness(0);

    /**
     * Creates the stack pushes necessary to redeem a P2WPKH output. If given signature is null, an empty push will be
     * used as a placeholder.
     */
    public static TransactionWitness redeemP2WPKH(@Nullable TransactionSignature signature, ECKey pubKey) {
        checkArgument(pubKey.isCompressed(), "only compressed keys allowed");
        TransactionWitness witness = new TransactionWitness(2);
        witness.setPush(0, signature != null ? signature.encodeToBitcoin() : new byte[0]); // signature
        witness.setPush(1, pubKey.getPubKey()); // pubkey
        return witness;
    }

    private final List<byte[]> pushes;

    public TransactionWitness(int pushCount) {
        pushes = new ArrayList<>(Math.min(pushCount, Utils.MAX_INITIAL_ARRAY_LENGTH));
    }

    public byte[] getPush(int i) {
        return pushes.get(i);
    }

    public int getPushCount() {
        return pushes.size();
    }

    public void setPush(int i, byte[] value) {
        while (i >= pushes.size()) {
            pushes.add(new byte[]{});
        }
        pushes.set(i, value);
    }

    protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
        stream.write(new VarInt(pushes.size()).encode());
        for (int i = 0; i < pushes.size(); i++) {
            byte[] push = pushes.get(i);
            stream.write(new VarInt(push.length).encode());
            stream.write(push);
        }
    }

    @Override
    public String toString() {
        List<String> stringPushes = new ArrayList<>();
        for (int j = 0; j < this.getPushCount(); j++) {
            byte[] push = this.getPush(j);
            if (push == null) {
                stringPushes.add("NULL");
            } else if (push.length == 0) {
                stringPushes.add("EMPTY");
            } else {
                stringPushes.add(Utils.HEX.encode(push));
            }
        }
        return Utils.SPACE_JOINER.join(stringPushes);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TransactionWitness other = (TransactionWitness) o;
        if (pushes.size() != other.pushes.size()) return false;
        for (int i = 0; i < pushes.size(); i++) {
            if (!Arrays.equals(pushes.get(i), other.pushes.get(i))) return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hashCode = 1;
        for (byte[] push : pushes) {
            hashCode = 31 * hashCode + (push == null ? 0 : Arrays.hashCode(push));
        }
        return hashCode;
    }
}


text:
<?xml version="1.0"?>
<config>
    <modules>
        <AW_Followupemail>
            <version>3.5.0</version><platform>ee</platform>
        </AW_Followupemail>
    </modules>

    <frontend>
        <translate>
            <modules>
                <AW_Followupemail>
                    <files>
                        <default>AW_Followupemail.csv</default>
                    </files>
                </AW_Followupemail>
            </modules>
        </translate>
        <routers>
            <followupemail>
                <use>standard</use>
                <args>
                    <module>AW_Followupemail</module>
                    <frontName>followupemail</frontName>
                </args>
            </followupemail>
        </routers>
        <layout>
            <updates>
                <followupemail>
                    <file>followupemail.xml</file>
                </followupemail>
            </updates>
        </layout>

        <events>
            <controller_action_predispatch_checkout_onepage_saveOrder>
                <observers>
                    <followupemail>
                        <type>singleton</type>
                        <class>followupemail/observer</class>
                        <method>processSubscription</method>
                    </followupemail>
                </observers>
            </controller_action_predispatch_checkout_onepage_saveOrder>
        </events>

    </frontend>

    <admin>
        <routers>
            <followupemail_admin>
                <use>admin</use>
                <args>
                    <module>AW_Followupemail</module>
                    <frontName>followupemail_admin</frontName>
                </args>
            </followupemail_admin>
        </routers>
    </admin>

    <adminhtml>
        <translate>
            <modules>
                <AW_Followupemail>
                    <files>
                        <default>AW_Followupemail.csv</default>
                    </files>
                </AW_Followupemail>
            </modules>
        </translate>
        <menu>
            <followupemail module="followupemail">
                <title>Follow Up Email</title>
                <sort_order>71</sort_order>
                <children>
                    <items module="followupemail">
                        <title>Manage Rules</title>
                        <sort_order>10</sort_order>
                        <action>followupemail_admin/adminhtml_rules</action>
                    </items>
                    <entries module="followupemail">
                        <title>Mail log</title>
                        <sort_order>20</sort_order>
                        <action>followupemail_admin/adminhtml_queue</action>
                    </entries>
                    <linktracking module="followupemail">
                        <title>Link Tracking</title>
                        <sort_order>30</sort_order>
                        <action>followupemail_admin/adminhtml_linktracking</action>
                    </linktracking>
                    <coupons module="followupemail">
                        <title>Coupons</title>
                        <sort_order>40</sort_order>
                        <action>followupemail_admin/adminhtml_coupons</action>
                    </coupons>
                    <settings module="followupemail">
                        <title>Settings</title>
                        <sort_order>50</sort_order>
                        <action>adminhtml/system_config/edit/section/followupemail</action>
                    </settings>
                </children>
            </followupemail>
        </menu>
        <acl>
            <resources>
                <all>
                    <title>Allow Everything</title>
                </all>
                <admin>
                    <children>
                        <followupemail>
                            <title>Followupemail Module</title>
                            <sort_order>10</sort_order>
                            <children>
                                <items>
                                    <title>Rules manager</title>
                                </items>
                                <entries>
                                    <title>Email queue</title>
                                </entries>
                                <linktracking>
                                    <title>Link tracking</title>
                                </linktracking>
                                <coupons>
                                    <title>Coupons Management</title>
                                </coupons>
                                <settings>
                                    <title>Settings</title>
                                </settings>
                            </children>
                        </followupemail>
                        <system>
                            <children>
                                <config>
                                    <children>
                                        <followupemail>
                                            <title>aheadWorks - Follow Up Email Section</title>
                                        </followupemail>
                                    </children>
                                </config>
                            </children>
                        </system>
                    </children>
                </admin>
            </resources>
        </acl>
        <layout>
            <updates>
                <followupemail>
                    <file>followupemail.xml</file>
                </followupemail>
            </updates>
        </layout>
    </adminhtml>

    <global>
        <models>
            <followupemail>
                <class>AW_Followupemail_Model</class>
                <resourceModel>followupemail_mysql4</resourceModel>
            </followupemail>
            <followupemail_mysql4>
                <class>AW_Followupemail_Model_Mysql4</class>
                <entities>
                    <rule>

aw_followup_rule

                    </rule>
                    <queue>

aw_followup_queue

                    </queue>
                    <linktracking>

aw_followup_link_track

                    </linktracking>
                    <config>

aw_followup_config

                    </config>
                </entities>
            </followupemail_mysql4>
            <newsletter>
                <rewrite>
                    <subscriber>AW_Followupemail_Model_Subscriber</subscriber>
                </rewrite>
            </newsletter>
            <salesrule_mysql4>
                <rewrite>
                    <rule_collection>AW_Followupemail_Model_Mysql4_Salesrule_Collection</rule_collection>
                </rewrite>
            </salesrule_mysql4>
            <log_resource>
                <rewrite>
                    <visitor>AW_Followupemail_Model_Resource_Visitor</visitor>
                </rewrite>
            </log_resource>
        </models>
        <resources>
            <followupemail_setup>
                <setup>
                    <module>AW_Followupemail</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </followupemail_setup>
            <followupemail_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </followupemail_write>
            <followupemail_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </followupemail_read>
        </resources>
        <blocks>
            <followupemail>
                <class>AW_Followupemail_Block</class>
            </followupemail>

        </blocks>
        <helpers>
            <followupemail>
                <class>AW_Followupemail_Helper</class>
            </followupemail>
        </helpers>
        <template>
            <email>
                <followupemail_template_variables_demo translate="label" module="followupemail">
                    Follow Up Email template variables demo
                    <file>followupemail_variables_demo.html</file>
                    <type>html</type>
                </followupemail_template_variables_demo>
            </email>
        </template>

        <events>
            <wishlist_share>
                <observers>
                    <followupemail>
                        <type>singleton</type>
                        <class>followupemail/events</class>
                        <method>wishlistShared</method>
                    </followupemail>
                </observers>
            </wishlist_share>
            <wishlist_add_product>
                <observers>
                    <followupemail>
                        <type>singleton</type>
                        <class>followupemail/events</class>
                        <method>wishlistProductAdd</method>
                    </followupemail>
                </observers>
            </wishlist_add_product>
            <customer_save_commit_after>
                <observers>
                    <followupemail>
                        <type>singleton</type>
                        <class>followupemail/events</class>
                        <method>customerAfterSave</method>
                    </followupemail>
                </observers>
            </customer_save_commit_after>
            <salesrule_rule_get_coupon_types>
                <observers>
                    <followupemail>
                        <type>singleton</type>
                        <class>followupemail/events</class>
                        <method>addFUECouponType</method>
                    </followupemail>
                </observers>
            </salesrule_rule_get_coupon_types>
            <controller_action_predispatch>
                <observers>
                    <followupemail>
                        <type>singleton</type>
                        <class>followupemail/events</class>
                        <method>checkCouponsMenu</method>
                    </followupemail>
                </observers>
            </controller_action_predispatch>
            <an_subscriber_subscribe>
                <observers>
                    <followupemail>
                        <type>singleton</type>
                        <class>followupemail/events</class>
                        <method>newsletterSubscribe</method>
                    </followupemail>
                </observers>
            </an_subscriber_subscribe>
            <an_subscriber_unsubscribe>
                <observers>
                    <followupemail>
                        <type>singleton</type>
                        <class>followupemail/events</class>
                        <method>newsletterSubscribe</method>
                    </followupemail>
                </observers>
            </an_subscriber_unsubscribe>
            <an_subscriber_delete>
                <observers>
                    <followupemail>
                        <type>singleton</type>
                        <class>followupemail/events</class>
                        <method>deleteSubscriber</method>
                    </followupemail>
                </observers>
            </an_subscriber_delete>
            <newsletter_subscriber_save_after>
                <observers>
                    <followupemail>
                        <type>singleton</type>
                        <class>followupemail/events</class>
                        <method>newsletterSubscribe</method>
                    </followupemail>
                </observers>
            </newsletter_subscriber_save_after>
            <newsletter_subscriber_delete_after>
                <observers>
                    <followupemail>
                        <type>singleton</type>
                        <class>followupemail/events</class>
                        <method>deleteSubscriber</method>
                    </followupemail>
                </observers>
            </newsletter_subscriber_delete_after>
            <customer_save_after>
                <observers>
                    <followupemail>
                        <type>singleton</type>
                        <class>followupemail/events</class>
                        <method>checkCustomer</method>
                    </followupemail>
                </observers>
            </customer_save_after>
        </events>

    </global>

    <crontab>
        <jobs>
            <rule_apply_all>
                <schedule>
                    <cron_expr>* * * * *</cron_expr>
                </schedule>
                <run>
                    <model>followupemail/cron::cronJobs</model>
                </run>
            </rule_apply_all>
            <rule_apply_birthday>
                <schedule>
                    <cron_expr>* * * * *</cron_expr>
                </schedule>
                <run>
                    <model>followupemail/crondaily::cronJobs</model>
                </run>
            </rule_apply_birthday>
        </jobs>
    </crontab>
    <phpunit>
        <suite>
            <modules>
                <AW_Followupemail/>
            </modules>
        </suite>
    </phpunit>
    <default>
        <followupemail>
            <general>
                <sender>general</sender>
                <keeplog>1</keeplog>
                <displaysubscribebuttononcheckoutpage>1</displaysubscribebuttononcheckoutpage>
            </general>
        </followupemail>
    </default>
</config>


text:
==========
Quickstart
==========

This page provides a quick introduction to Laranav and introductory examples.
If you have not already installed, head over to the :ref:`installation`
page.

Creating a menu
===============

Configuration
-------------

First, open ``config/laranav/config.php``:

.. code-block:: php
    'default' => [
        ...
    ]

Any menus added here automatically inherit their configuration from ``default``,
and can be overridden by specifying them in explicitly for each menu.
You can read more about available options [here](#configphp).

Menu items
----------

Next, we will define items for the menu in ``config/laranav/menus.php``:

.. code-block:: php
    'default' => [
        ...
    ],

Items can link to a simple URL, or you can use Laravel's `UrlGenerator` object to generate URLs. You can read more about available options [here](#menusphp)

Rendering the menu
------------------

Finally, in your template, add `{!! Nav::menu('myMenu')->toHtml() !!}` and your menu should render!


text:
"""
Test various methods of the RbuildConfiguration object.
"""

import os
from rbuild_test import rbuildhelp

import tempfile

from rbuild import rbuildcfg

class ConfigTest(rbuildhelp.RbuildHelper):
    def testWriteCheckoutFile(self):
        """
        Validate the output of the function used to write the rbuildrc
        in new product checkouts.
        """
        config = rbuildcfg.RbuildConfiguration()
        config.configLine('name Mr. User')
        config.configLine('contact mr.user@foo.com')
        config.configLine('repositoryMap []')
        config.configLine('repositoryMap foo.com https://repo.foo.com/conary/')
        config.configLine('repositoryMap bar.com https://dev.bar.com/conary/')
        config.configLine('user someuser somepassword')
        config.configLine('serverUrl http://myrbuilder.foo')
        config.configLine('signatureKey ASDF')
        config.configLine('signatureKeyMap foo FDSA')
        config.configLine('quiet True')

        dumpFile = tempfile.NamedTemporaryFile()
        config.writeCheckoutFile(dumpFile.name)
        dumpFile.seek(0)
        dump = dumpFile.read()

        expected = '''# contact (Default: None) (At `rbuild init': mr.user@foo.com)
# name (Default: None) (At `rbuild init': Mr. User)
# pluginDirs (Default: /usr/share/rbuild/plugins:~/.rbuild/plugins.d) (At `rbuild init': /usr/share/rbuild/plugins:~/.rbuild/plugins.d)
# quiet (Default: False) (At `rbuild init': True)
# repositoryMap (Default: [])
repositoryMap             foo.com                   https://repo.foo.com/conary/
repositoryMap             bar.com                   https://dev.bar.com/conary/
# rmakePluginDirs (Default: /usr/share/rmake/plugins:~/.rmake/plugins.d) (At `rbuild init': /usr/share/rmake/plugins:~/.rmake/plugins.d)
# rmakeUrl (Default: None) (At `rbuild init': None)
# serverUrl (Default: None) (At `rbuild init': http://myrbuilder.foo)
# signatureKey (Default: None) (At `rbuild init': ASDF)
# signatureKeyMap (Default: []) (At `rbuild init': foo FDSA)
'''

        self.failUnlessEqual(dump, expected)

    def testPluginConfigurations(self):
        # Dump config file
        cfgFile = os.path.join(self.workDir, "rbuildrc")
        self.rbuildCfg.store(file(cfgFile, "w"))
        # Add a few sections
        with file(cfgFile, "a") as f:
            f.write("""
[edit]
name Marvin the Martian
device Illudium Q-36 Explosive Space Modulator
[dummy-section]
dummy-option-1 1
dummy-option-2 2
""")
        self.rbuildCfg.__init__(readConfigFiles=False, ignoreErrors=True)
        self.rbuildCfg.read(cfgFile)

        from rbuild import handle
        _C = rbuildcfg.cfg
        # Mock plugin loading so we can add some config options to one
        # of the plugins
        origLoadPluginFromFileName = handle.pluginloader.PluginManager.loadPluginFromFileName
        def mockedLoadPluginFromFileName(slf, dir, fileName, *args, **kwargs):
            plugin = origLoadPluginFromFileName(slf, dir, fileName, *args, **kwargs)
            if plugin and plugin.name == 'edit':
                class MyPluginConfiguration(plugin.PluginConfiguration):
                    name = (_C.CfgString, 'Jean Valjean')
                    device = _C.CfgString
                self.mock(plugin, 'PluginConfiguration', MyPluginConfiguration)
            return plugin
        self.mock(handle.pluginloader.PluginManager, 'loadPluginFromFileName',
                mockedLoadPluginFromFileName)
        handle = self.getRbuildHandle()
        handle.Edit.registerCommands()
        handle.Edit.initialize()

        section = handle.getConfig().getSection('edit')
        self.assertEquals(section.name, 'Marvin the Martian')
        self.assertEquals(section.device, 'Illudium Q-36 Explosive Space Modulator')
        # The section is passed by reference to the plugin
        self.assertTrue(handle.Edit.pluginCfg is section)

        # Dump the handler's config. It should include just the edit
        # section
        newCfg = cfgFile + '.new'
        handle.getConfig().writeToFile(newCfg)
        self.assertEquals(file(newCfg).read(), file(newCfg).read())


text:
**This repository and project has now been archived and is no longer supported. The code will remain available for reference and information.**

# Piaware Flight Data Reader
## Martin O'Hanlon (martin@ohanlonweb.com)
## http://www.stuffaboutcode.com

## Description
A python 3 module to read flight data from the PiAware solution.

[http://www.stuffaboutcode.com/2015/09/read-piaware-flight-data-with-python.html](http://www.stuffaboutcode.com/2015/09/read-piaware-flight-data-with-python.html)

## Structure
* flightdata.py - the flightdata python module

## Usage

	from flightdata import FlightData
	from time import sleep

	myflights = FlightData()
	while True:
		#loop through each aircraft found
		for aircraft in myflights.aircraft:

			#read the aircraft data
			print(aircraft.hex)
			print(aircraft.squawk)
			print(aircraft.flight)
			print(aircraft.lat)
			print(aircraft.lon)
			print(aircraft.validposition)
			print(aircraft.altitude)
			print(aircraft.vert_rate)
			print(aircraft.track)
			print(aircraft.validtrack)
			print(aircraft.speed)
			print(aircraft.messages)
			print(aircraft.seen)
			print(aircraft.mlat)

	sleep(1)

	#refresh the flight data
	myflights.refresh()

## Version history
* 0.1 - Initial stable version


text:
#include "battery.h"
#include "battery_smart.h"
#include "console.h"
#include "host_command.h"
#include "i2c.h"
#include "smbus.h"
#include "timer.h"
#include "util.h"

/* Console output macros */
#define CPUTS(outstr) cputs(CC_CHARGER, outstr);
#define CPRINTS(format, args...) cprints(CC_CHARGER, format, ## args)

#define BATTERY_NO_RESPONSE_TIMEOUT	(1000*MSEC)

static int fake_state_of_charge = -1;

test_mockable int sbc_read(int cmd, int *param)
{
	return i2c_read16(I2C_PORT_CHARGER, CHARGER_ADDR, cmd, param);
}

test_mockable int sbc_write(int cmd, int param)
{
	return i2c_write16(I2C_PORT_CHARGER, CHARGER_ADDR, cmd, param);
}

test_mockable int sb_read(int cmd, int *param)
{
#ifdef CONFIG_BATTERY_CUT_OFF
	/*
	 * Some batteries would wake up after cut-off if we talk to it.
	 */
	if (battery_is_cut_off())
		return EC_RES_ACCESS_DENIED;
#endif
#ifdef CONFIG_SMBUS
	{
		int rv;
		uint16_t d16 = 0;
		rv = smbus_read_word(I2C_PORT_BATTERY, BATTERY_ADDR, cmd, &d16);
		*param = d16;
		return rv;
	}
#else
	return i2c_read16(I2C_PORT_BATTERY, BATTERY_ADDR, cmd, param);
#endif
}

test_mockable int sb_write(int cmd, int param)
{
#ifdef CONFIG_BATTERY_CUT_OFF
	/*
	 * Some batteries would wake up after cut-off if we talk to it.
	 */
	if (battery_is_cut_off())
		return EC_RES_ACCESS_DENIED;
#endif
#ifdef CONFIG_SMBUS
	return smbus_write_word(I2C_PORT_BATTERY, BATTERY_ADDR, cmd, param);
#else
	return i2c_write16(I2C_PORT_BATTERY, BATTERY_ADDR, cmd, param);
#endif
}

int sb_read_string(int port, int slave_addr, int offset, uint8_t *data,
	int len)
{
#ifdef CONFIG_BATTERY_CUT_OFF
	/*
	 * Some batteries would wake up after cut-off if we talk to it.
	 */
	if (battery_is_cut_off())
		return EC_RES_ACCESS_DENIED;
#endif
#ifdef CONFIG_SMBUS
	return smbus_read_string(port, slave_addr, offset, data, len);
#else
	return i2c_read_string(port, slave_addr, offset, data, len);
#endif
}

int battery_get_mode(int *mode)
{
	return sb_read(SB_BATTERY_MODE, mode);
}

/**
 * Force battery to mAh mode (instead of 10mW mode) for reporting capacity.
 *
 * @return non-zero if error.
 */

static int battery_force_mah_mode(void)
{
	int val, rv;
	rv = battery_get_mode(&val);
	if (rv)
		return rv;

	if (val & MODE_CAPACITY)
		rv = sb_write(SB_BATTERY_MODE, val & ~MODE_CAPACITY);

	return rv;
}

int battery_state_of_charge_abs(int *percent)
{
	return sb_read(SB_ABSOLUTE_STATE_OF_CHARGE, percent);
}

int battery_remaining_capacity(int *capacity)
{
	int rv = battery_force_mah_mode();
	if (rv)
		return rv;

	return sb_read(SB_REMAINING_CAPACITY, capacity);
}

int battery_full_charge_capacity(int *capacity)
{
	int rv = battery_force_mah_mode();
	if (rv)
		return rv;

	return sb_read(SB_FULL_CHARGE_CAPACITY, capacity);
}

int battery_time_to_empty(int *minutes)
{
	return sb_read(SB_AVERAGE_TIME_TO_EMPTY, minutes);
}

int battery_run_time_to_empty(int *minutes)
{
	return sb_read(SB_RUN_TIME_TO_EMPTY, minutes);
}

int battery_time_to_full(int *minutes)
{
	return sb_read(SB_AVERAGE_TIME_TO_FULL, minutes);
}

/* Read battery status */
int battery_status(int *status)
{
	return sb_read(SB_BATTERY_STATUS, status);
}

/* Battery charge cycle count */
int battery_cycle_count(int *count)
{
	return sb_read(SB_CYCLE_COUNT, count);
}

int battery_design_capacity(int *capacity)
{
	int rv = battery_force_mah_mode();
	if (rv)
		return rv;

	return sb_read(SB_DESIGN_CAPACITY, capacity);
}

/* Designed battery output voltage
 * unit: mV
 */
int battery_design_voltage(int *voltage)
{
	return sb_read(SB_DESIGN_VOLTAGE, voltage);
}

/* Read serial number */
int battery_serial_number(int *serial)
{
	return sb_read(SB_SERIAL_NUMBER, serial);
}

test_mockable int battery_time_at_rate(int rate, int *minutes)
{
	int rv;
	int ok, time;
	int loop, cmd, output_sign;

	if (rate == 0) {
		*minutes = 0;
		return EC_ERROR_INVAL;
	}

	rv = sb_write(SB_AT_RATE, rate);
	if (rv)
		return rv;
	loop = 5;
	while (loop--) {
		rv = sb_read(SB_AT_RATE_OK, &ok);
		if (rv)
			return rv;
		if (ok) {
			if (rate > 0) {
				cmd = SB_AT_RATE_TIME_TO_FULL;
				output_sign = -1;
			} else {
				cmd = SB_AT_RATE_TIME_TO_EMPTY;
				output_sign = 1;
			}
			rv = sb_read(cmd, &time);
			if (rv)
				return rv;

			*minutes = (time == 0xffff) ? 0 : output_sign * time;
			return EC_SUCCESS;
		} else {
			/* wait 10ms for AT_RATE_OK */
			msleep(10);
		}
	}
	return EC_ERROR_TIMEOUT;
}

test_mockable int battery_manufacture_date(int *year, int *month, int *day)
{
	int rv;
	int ymd;

	rv = sb_read(SB_SPECIFICATION_INFO, &ymd);
	if (rv)
		return rv;

	/* battery date format:
	 * ymd = day + month * 32 + (year - 1980) * 256
	 */
	*year  = (ymd >> 8) + 1980;
	*month = (ymd & 0xff) / 32;
	*day   = (ymd & 0xff) % 32;

	return EC_SUCCESS;
}

/* Read manufacturer name */
test_mockable int battery_manufacturer_name(char *dest, int size)
{
	return sb_read_string(I2C_PORT_BATTERY, BATTERY_ADDR,
			       SB_MANUFACTURER_NAME, dest, size);
}

/* Read device name */
test_mockable int battery_device_name(char *dest, int size)
{
	return sb_read_string(I2C_PORT_BATTERY, BATTERY_ADDR,
			       SB_DEVICE_NAME, dest, size);
}

/* Read battery type/chemistry */
test_mockable int battery_device_chemistry(char *dest, int size)
{
	return sb_read_string(I2C_PORT_BATTERY, BATTERY_ADDR,
			       SB_DEVICE_CHEMISTRY, dest, size);
}

void battery_get_params(struct batt_params *batt)
{
	struct batt_params batt_new = {0};
	int v;

	if (sb_read(SB_TEMPERATURE, &batt_new.temperature))
		batt_new.flags |= BATT_FLAG_BAD_TEMPERATURE;

	if (sb_read(SB_RELATIVE_STATE_OF_CHARGE, &batt_new.state_of_charge)
	    && fake_state_of_charge < 0)
		batt_new.flags |= BATT_FLAG_BAD_STATE_OF_CHARGE;

	/* If soc is faked, override with faked data */
	if (fake_state_of_charge >= 0)
		batt_new.state_of_charge = fake_state_of_charge;

	if (sb_read(SB_VOLTAGE, &batt_new.voltage))
		batt_new.flags |= BATT_FLAG_BAD_VOLTAGE;

	/* This is a signed 16-bit value. */
	if (sb_read(SB_CURRENT, &v))
		batt_new.flags |= BATT_FLAG_BAD_CURRENT;
	else
		batt_new.current = (int16_t)v;

	if (sb_read(SB_CHARGING_VOLTAGE, &batt_new.desired_voltage))
		batt_new.flags |= BATT_FLAG_BAD_DESIRED_VOLTAGE;

	if (sb_read(SB_CHARGING_CURRENT, &batt_new.desired_current))
		batt_new.flags |= BATT_FLAG_BAD_DESIRED_CURRENT;

	if (battery_remaining_capacity(&batt_new.remaining_capacity))
		batt_new.flags |= BATT_FLAG_BAD_REMAINING_CAPACITY;

	if (battery_full_charge_capacity(&batt_new.full_capacity))
		batt_new.flags |= BATT_FLAG_BAD_FULL_CAPACITY;

	if (battery_status(&batt_new.status))
		batt_new.flags |= BATT_FLAG_BAD_STATUS;

	/* If any of those reads worked, the battery is responsive */
	if ((batt_new.flags & BATT_FLAG_BAD_ANY) != BATT_FLAG_BAD_ANY)
		batt_new.flags |= BATT_FLAG_RESPONSIVE;

#if defined(CONFIG_BATTERY_PRESENT_CUSTOM) ||	\
	defined(CONFIG_BATTERY_PRESENT_GPIO)
	/* Hardware can tell us for certain */
	batt_new.is_present = battery_is_present();
#else
	/* No hardware test, so we only know it's there if it responds */
	if (batt_new.flags & BATT_FLAG_RESPONSIVE)
		batt_new.is_present = BP_YES;
	else
		batt_new.is_present = BP_NOT_SURE;
#endif

	/*
	 * Charging allowed if both desired voltage and current are nonzero
	 * and battery isn't full (and we read them all correctly).
	 */
	if (!(batt_new.flags & (BATT_FLAG_BAD_DESIRED_VOLTAGE |
				BATT_FLAG_BAD_DESIRED_CURRENT |
				BATT_FLAG_BAD_STATE_OF_CHARGE)) &&
#ifdef CONFIG_BATTERY_REQUESTS_NIL_WHEN_DEAD
		/*
		 * TODO (crosbug.com/p/29467): remove this workaround
		 * for dead battery that requests no voltage/current
		 */
		((batt_new.desired_voltage &&
			batt_new.desired_current &&
			batt_new.state_of_charge < BATTERY_LEVEL_FULL) ||
		(batt_new.desired_voltage == 0 &&
			batt_new.desired_current == 0 &&
			batt_new.state_of_charge == 0)))
#else
	    batt_new.desired_voltage &&
	    batt_new.desired_current &&
	    batt_new.state_of_charge < BATTERY_LEVEL_FULL)
#endif
		batt_new.flags |= BATT_FLAG_WANT_CHARGE;
	else
		/* Force both to zero */
		batt_new.desired_voltage = batt_new.desired_current = 0;

	/* Update visible battery parameters */
	memcpy(batt, &batt_new, sizeof(*batt));
}

/* Wait until battery is totally stable */
int battery_wait_for_stable(void)
{
	int status;
	uint64_t wait_timeout = get_time().val + BATTERY_NO_RESPONSE_TIMEOUT;

	CPRINTS("Wait for battery stabilized during %d",
			 BATTERY_NO_RESPONSE_TIMEOUT);
	while (get_time().val < wait_timeout) {
		/* Starting pinging battery */
		if (battery_status(&status) == EC_SUCCESS) {
			/* Battery is stable */
			CPRINTS("battery responded with status %x", status);
			return EC_SUCCESS;
		}
		msleep(25); /* clock stretching could hold 25ms */
	}
	CPRINTS("battery not responding");
	return EC_ERROR_NOT_POWERED;
}

#ifndef CONFIG_CHARGER_V1
static int command_battfake(int argc, char **argv)
{
	char *e;
	int v;

	if (argc == 2) {
		v = strtoi(argv[1], &e, 0);
		if (*e || v < -1 || v > 100)
			return EC_ERROR_PARAM1;

		fake_state_of_charge = v;
	}

	if (fake_state_of_charge >= 0)
		ccprintf("Fake batt %d%%\n",
			 fake_state_of_charge);

	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(battfake, command_battfake,
			"percent (-1 = use real level)",
			"Set fake battery level",
			NULL);
#endif

/*****************************************************************************/
/* Smart battery pass-through
 */
#ifdef CONFIG_I2C_PASSTHROUGH
static int host_command_sb_read_word(struct host_cmd_handler_args *args)
{
	int rv;
	int val;
	const struct ec_params_sb_rd *p = args->params;
	struct ec_response_sb_rd_word *r = args->response;

	if (p->reg > 0x1c)
		return EC_RES_INVALID_PARAM;
	rv = sb_read(p->reg, &val);
	if (rv)
		return EC_RES_ERROR;

	r->value = val;
	args->response_size = sizeof(struct ec_response_sb_rd_word);

	return EC_RES_SUCCESS;
}
DECLARE_HOST_COMMAND(EC_CMD_SB_READ_WORD,
		     host_command_sb_read_word,
		     EC_VER_MASK(0));

static int host_command_sb_write_word(struct host_cmd_handler_args *args)
{
	int rv;
	const struct ec_params_sb_wr_word *p = args->params;

	if (p->reg > 0x1c)
		return EC_RES_INVALID_PARAM;
	rv = sb_write(p->reg, p->value);
	if (rv)
		return EC_RES_ERROR;

	return EC_RES_SUCCESS;
}
DECLARE_HOST_COMMAND(EC_CMD_SB_WRITE_WORD,
		     host_command_sb_write_word,
		     EC_VER_MASK(0));

static int host_command_sb_read_block(struct host_cmd_handler_args *args)
{
	int rv;
	const struct ec_params_sb_rd *p = args->params;
	struct ec_response_sb_rd_block *r = args->response;

	if ((p->reg != SB_MANUFACTURER_NAME) &&
	    (p->reg != SB_DEVICE_NAME) &&
	    (p->reg != SB_DEVICE_CHEMISTRY) &&
	    (p->reg != SB_MANUFACTURER_DATA))
		return EC_RES_INVALID_PARAM;
	rv = sb_read_string(I2C_PORT_BATTERY, BATTERY_ADDR, p->reg,
			     r->data, 32);
	if (rv)
		return EC_RES_ERROR;

	args->response_size = sizeof(struct ec_response_sb_rd_block);

	return EC_RES_SUCCESS;
}
DECLARE_HOST_COMMAND(EC_CMD_SB_READ_BLOCK,
		     host_command_sb_read_block,
		     EC_VER_MASK(0));

static int host_command_sb_write_block(struct host_cmd_handler_args *args)
{
	/* Not implemented */
	return EC_RES_INVALID_COMMAND;
}
DECLARE_HOST_COMMAND(EC_CMD_SB_WRITE_BLOCK,
		     host_command_sb_write_block,
		     EC_VER_MASK(0));
#endif


text:
'use strict';

/*jshint -W079 */
const open = require('open');

exports.openurl = function (url) {
  open(url, function (err, stdout, stderr) {
    if (err) {
      console.log('Can not open browser, please open your browser to visit: ' + url);
      process.exit(0);
    }
    if (stdout || stderr) {
      console.log(stdout, stderr);
    }
    process.exit(0);
  });
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Poria oleagina Overh.

### Remarks
null


text:
package com.hazelcast.cache.impl.operation;

import com.hazelcast.cache.BackupAwareEntryProcessor;
import com.hazelcast.cache.impl.CacheDataSerializerHook;
import com.hazelcast.cache.impl.record.CacheRecord;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.spi.impl.operationservice.Operation;

import javax.cache.processor.EntryProcessor;
import java.io.IOException;

/**
 * Operation of the Cache Entry Processor.
 * <p>{@link javax.cache.processor.EntryProcessor} is executed on the partition.
 * {@link com.hazelcast.cache.impl.ICacheRecordStore} provides the required functionality and this
 * operation is responsible for parameter passing and handling the backup at the end.</p>
 */
public class CacheEntryProcessorOperation
        extends MutatingCacheOperation {

    private EntryProcessor entryProcessor;
    private Object[] arguments;

    private transient CacheRecord backupRecord;
    private transient EntryProcessor backupEntryProcessor;

    public CacheEntryProcessorOperation() {
    }

    public CacheEntryProcessorOperation(String cacheNameWithPrefix, Data key, int completionId,
                                        javax.cache.processor.EntryProcessor entryProcessor, Object... arguments) {
        super(cacheNameWithPrefix, key, completionId);
        this.entryProcessor = entryProcessor;
        this.arguments = arguments;
        this.completionId = completionId;
    }

    @Override
    public boolean shouldBackup() {
        return true;
    }

    @Override
    public Operation getBackupOperation() {
        if (backupEntryProcessor != null) {
            return new CacheBackupEntryProcessorOperation(name, key, backupEntryProcessor, arguments);
        } else {
            if (backupRecord != null) {
                // After entry processor is executed if there is a record, this means that possible add/update
                return new CachePutBackupOperation(name, key, backupRecord);
            } else {
                // If there is no record, this means possible remove by entry processor.
                // TODO In case of non-existing key, this cause redundant remove operation to backups
                // Better solution may be using a new interface like "EntryProcessorListener" on "invoke" method
                // for handling add/update/remove cases properly at execution of "EntryProcessor".
                return new CacheRemoveBackupOperation(name, key);
            }
        }
    }

    @Override
    public int getClassId() {
        return CacheDataSerializerHook.ENTRY_PROCESSOR;
    }

    @Override
    public void run()
            throws Exception {
        response = recordStore.invoke(key, entryProcessor, arguments, completionId);
        if (entryProcessor instanceof BackupAwareEntryProcessor) {
            BackupAwareEntryProcessor processor = (BackupAwareEntryProcessor) entryProcessor;
            backupEntryProcessor = processor.createBackupEntryProcessor();
        }
        if (backupEntryProcessor == null) {
            backupRecord = recordStore.getRecord(key);
        }
    }

    @Override
    public void afterRun() throws Exception {
        if (recordStore.isWanReplicationEnabled()) {
            CacheRecord record = recordStore.getRecord(key);
            if (record != null) {
                publishWanUpdate(key, record);
            } else {
                publishWanRemove(key);
            }
        }
        super.afterRun();
    }

    @Override
    protected void writeInternal(ObjectDataOutput out)
            throws IOException {
        super.writeInternal(out);
        out.writeObject(entryProcessor);
        out.writeBoolean(arguments != null);
        if (arguments != null) {
            out.writeInt(arguments.length);
            for (Object arg : arguments) {
                out.writeObject(arg);
            }
        }
    }

    @Override
    protected void readInternal(ObjectDataInput in)
            throws IOException {
        super.readInternal(in);
        entryProcessor = in.readObject();
        final boolean hasArguments = in.readBoolean();
        if (hasArguments) {
            final int size = in.readInt();
            arguments = new Object[size];
            for (int i = 0; i < size; i++) {
                arguments[i] = in.readObject();
            }
        }
    }

}


text:
#include "SkHalf.h"
#include "SkFloatBits.h"

uint16_t halfMantissa(SkHalf h) {
    return h & 0x03ff;
}

uint16_t halfExponent(SkHalf h) {
    return (h >> 10) & 0x001f;
}

uint16_t halfSign(SkHalf h) {
    return h >> 15;
}

union FloatUIntUnion {
    uint32_t fUInt;    // this must come first for the initializations below to work
    float    fFloat;
};

// based on Fabien Giesen's float_to_half_fast3()
// see https://gist.github.com/rygorous/2156668
SkHalf SkFloatToHalf(float f) {
    static const uint32_t f32infty = { 255 << 23 };
    static const uint32_t f16infty = { 31 << 23 };
    static const FloatUIntUnion magic = { 15 << 23 };
    static const uint32_t sign_mask = 0x80000000u;
    static const uint32_t round_mask = ~0xfffu;
    SkHalf o = 0;

    FloatUIntUnion floatUnion;
    floatUnion.fFloat = f;

    uint32_t sign = floatUnion.fUInt & sign_mask;
    floatUnion.fUInt ^= sign;

    // NOTE all the integer compares in this function can be safely
    // compiled into signed compares since all operands are below
    // 0x80000000. Important if you want fast straight SSE2 code
    // (since there's no unsigned PCMPGTD).

    // Inf or NaN (all exponent bits set)
    if (floatUnion.fUInt >= f32infty)
        // NaN->qNaN and Inf->Inf
        o = (floatUnion.fUInt > f32infty) ? 0x7e00 : 0x7c00;
    // (De)normalized number or zero
    else {
        floatUnion.fUInt &= round_mask;
        floatUnion.fFloat *= magic.fFloat;
        floatUnion.fUInt -= round_mask;
        // Clamp to signed infinity if overflowed
        if (floatUnion.fUInt > f16infty) {
            floatUnion.fUInt = f16infty;
        }

        o = floatUnion.fUInt >> 13; // Take the bits!
    }

    o |= sign >> 16;
    return o;
}

// based on Fabien Giesen's half_to_float_fast2()
// see https://fgiesen.wordpress.com/2012/03/28/half-to-float-done-quic/
float SkHalfToFloat(SkHalf h) {
    static const FloatUIntUnion magic = { 126 << 23 };
    FloatUIntUnion o;

    if (halfExponent(h) == 0)
    {
        // Zero / Denormal
        o.fUInt = magic.fUInt + halfMantissa(h);
        o.fFloat -= magic.fFloat;
    }
    else
    {
        // Set mantissa
        o.fUInt = halfMantissa(h) << 13;
        // Set exponent
        if (halfExponent(h) == 0x1f)
            // Inf/NaN
            o.fUInt |= (255 << 23);
        else
            o.fUInt |= ((127 - 15 + halfExponent(h)) << 23);
    }

    // Set sign
    o.fUInt |= (halfSign(h) << 31);
    return o.fFloat;
}


text:
title: "Getting Started"
description: "Get started with Sensu."
product: "Sensu Go"
version: "5.3"
weight: 10
layout: "base-for-directory-listing"
menu:
  sensu-go-5.3:
    identifier: getting-started
---

{{< directoryListing >}}


text:
namespace Parrot.Tests.Parser
{
    using System.Collections.Generic;
    using System.Linq;
    using NUnit.Framework;
    using Parrot.Nodes;

    [TestFixture]
    public class StringLiteralTests : ParrotParserTestsBase
    {
        [Test]
        public void Blah()
        {
            var document = Parse("\"string\"\"with quote in it\"");
            Assert.AreEqual("string\"with quote in it", (document.Children[0] as StringLiteral).ToString());
        }

        [Test]
        public void StringLiteralPipeAsLastElementOfFile()
        {
            //TODO: Remove \r\n
            //This appears to be a bug in the gold engine
            //when converted to new lexer/parser remove
            //the \r\n
            var document = Parse("|string literal\r\n");
            Assert.AreEqual(1, document.Children.Count);
            Assert.AreEqual("string", document.Children[0].Name);
        }

        [Test]
        public void StringLiteralPipeChildFollowedByStringLiteralPipeChild()
        {
            var document = Parse(@"container {
                                            style[type='text/css'] |label { margin-right: .5em; font-weight: bold; }
                                            title |Parrot Test Drive
                                       }");

            Assert.AreEqual(1, document.Children.Count);
            Assert.AreEqual(2, document.Children[0].Children.Count);
        }

        [Test]
        public void IdentifierPartsTests()
        {
            var results = GetIdentifierParts("input:submit#id.class").ToList();
            Assert.AreEqual(4, results.Count);

            Assert.AreEqual("input", results[0].Name);
            Assert.AreEqual(IdentifierType.Literal, results[0].Type);
            Assert.AreEqual("submit", results[1].Name);
            Assert.AreEqual(IdentifierType.Type, results[1].Type);
            Assert.AreEqual("id", results[2].Name);
            Assert.AreEqual(IdentifierType.Id, results[2].Type);
            Assert.AreEqual("class", results[3].Name);
            Assert.AreEqual(IdentifierType.Class, results[3].Type);
        }

        [Test]
        public void StringWithAtFollowedByEquals()
        {
            var document = Parse("'s=@Name'");
            Assert.IsNotNull(document);
        }

        public IEnumerable<Identifier> GetIdentifierParts(string source)
        {
            int index = 0;

            var partType = IdentifierType.Literal;

            for (int i = 0; i < source.Length; i++)
            {
                switch (source[i])
                {
                    case ':':
                        yield return new Identifier
                            {
                                Name = source.Substring(index, i - index),
                                Type = partType
                            };
                        partType = IdentifierType.Type;
                        index = i + 1;
                        break;
                    case '#':
                        yield return new Identifier
                            {
                                Name = source.Substring(index, i - index),
                                Type = partType
                            };
                        partType = IdentifierType.Id;
                        index = i + 1;
                        break;
                    case '.':
                        yield return new Identifier
                            {
                                Name = source.Substring(index, i - index),
                                Type = partType
                            };
                        partType = IdentifierType.Class;
                        index = i + 1;
                        break;
                }
            }

            yield return new Identifier
                {
                    Name = source.Substring(index),
                    Type = partType
                };
        }
    }
}


text:
<?php

namespace ua_parser;

if (PHP_SAPI !== 'cli')
  exit('updating the regexes.yaml file is slow and not recommended at server-side');

const URL = 'https://raw.github.com/tobie/ua-parser/master/regexes.yaml';

print 'downloading yaml file from ' . URL . PHP_EOL;

if (!($data = file_get_contents(URL)))
  exit('unable to load data from url: ' . URL);

$path = realpath(__DIR__ . '/../lib') . '/regexes.yaml';

// make backup and write data

if (is_file($path . '.bkp')) {
  print "removing old backup file\n";
  unlink($path . '.bkp');
}

if (is_file($path)) {
  print "creating new backup file ($path.bkp)\n";
  rename($path, $path . '.bkp');
}

print "saving data into $path\n";
file_put_contents($path, $data);

print "\ndone!\n";


text:
package sun.awt.image;

public class BadDepthException extends Exception {
    public BadDepthException() {
    }
}


text:
package com.beck.ep.team.ui;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.osgi.service.prefs.Preferences;

public class CheckBoxAction extends Action {
	private Preferences pref;
	private String prefKey;

	public CheckBoxAction(String text, Preferences pref, String prefKey, boolean def) {
		super(text, IAction.AS_CHECK_BOX);
		boolean flag = pref.getBoolean(prefKey, def);
		this.pref = pref;
		this.prefKey = prefKey;
		setChecked(flag);
	}

	public void run() {
		pref.putBoolean(prefKey, isChecked());
	}
}


text:
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
#if !(NET20 || NETFX_CORE || ASPNETCORE50)
using System.Data.Linq;
#endif
#if !(NETFX_CORE || ASPNETCORE50)
using System.Data.SqlTypes;
#endif
using System.Text;
using Newtonsoft.Json.Converters;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif ASPNETCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif

namespace Newtonsoft.Json.Tests.Converters
{
    [TestFixture]
    public class BinaryConverterTests : TestFixtureBase
    {
        private static readonly byte[] TestData = Encoding.UTF8.GetBytes("This is some test data!!!");

        public class ByteArrayClass
        {
            public byte[] ByteArray { get; set; }
            public byte[] NullByteArray { get; set; }
        }

#if !(NET20 || NETFX_CORE || PORTABLE || PORTABLE40 || ASPNETCORE50)
        [Test]
        public void DeserializeBinaryClass()
        {
            string json = @"{
  ""Binary"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
  ""NullBinary"": null
}";

            BinaryClass binaryClass = JsonConvert.DeserializeObject<BinaryClass>(json, new BinaryConverter());

            Assert.AreEqual(new Binary(TestData), binaryClass.Binary);
            Assert.AreEqual(null, binaryClass.NullBinary);
        }

        [Test]
        public void DeserializeBinaryClassFromJsonArray()
        {
            string json = @"{
  ""Binary"": [0, 1, 2, 3],
  ""NullBinary"": null
}";

            BinaryClass binaryClass = JsonConvert.DeserializeObject<BinaryClass>(json, new BinaryConverter());

            Assert.AreEqual(new byte[] { 0, 1, 2, 3 }, binaryClass.Binary.ToArray());
            Assert.AreEqual(null, binaryClass.NullBinary);
        }

        public class BinaryClass
        {
            public Binary Binary { get; set; }
            public Binary NullBinary { get; set; }
        }

        [Test]
        public void SerializeBinaryClass()
        {
            BinaryClass binaryClass = new BinaryClass();
            binaryClass.Binary = new Binary(TestData);
            binaryClass.NullBinary = null;

            string json = JsonConvert.SerializeObject(binaryClass, Formatting.Indented, new BinaryConverter());

            StringAssert.AreEqual(@"{
  ""Binary"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
  ""NullBinary"": null
}", json);
        }
#endif

        [Test]
        public void SerializeByteArrayClass()
        {
            ByteArrayClass byteArrayClass = new ByteArrayClass();
            byteArrayClass.ByteArray = TestData;
            byteArrayClass.NullByteArray = null;

            string json = JsonConvert.SerializeObject(byteArrayClass, Formatting.Indented);

            StringAssert.AreEqual(@"{
  ""ByteArray"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
  ""NullByteArray"": null
}", json);
        }

#if !(NETFX_CORE || PORTABLE || PORTABLE40 || ASPNETCORE50)
        public class SqlBinaryClass
        {
            public SqlBinary SqlBinary { get; set; }
            public SqlBinary? NullableSqlBinary1 { get; set; }
            public SqlBinary? NullableSqlBinary2 { get; set; }
        }

        [Test]
        public void SerializeSqlBinaryClass()
        {
            SqlBinaryClass sqlBinaryClass = new SqlBinaryClass();
            sqlBinaryClass.SqlBinary = new SqlBinary(TestData);
            sqlBinaryClass.NullableSqlBinary1 = new SqlBinary(TestData);
            sqlBinaryClass.NullableSqlBinary2 = null;

            string json = JsonConvert.SerializeObject(sqlBinaryClass, Formatting.Indented, new BinaryConverter());

            StringAssert.AreEqual(@"{
  ""SqlBinary"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
  ""NullableSqlBinary1"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
  ""NullableSqlBinary2"": null
}", json);
        }

        [Test]
        public void DeserializeSqlBinaryClass()
        {
            string json = @"{
  ""SqlBinary"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
  ""NullableSqlBinary1"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
  ""NullableSqlBinary2"": null
}";

            SqlBinaryClass sqlBinaryClass = JsonConvert.DeserializeObject<SqlBinaryClass>(json, new BinaryConverter());

            Assert.AreEqual(new SqlBinary(TestData), sqlBinaryClass.SqlBinary);
            Assert.AreEqual(new SqlBinary(TestData), sqlBinaryClass.NullableSqlBinary1);
            Assert.AreEqual(null, sqlBinaryClass.NullableSqlBinary2);
        }
#endif

        [Test]
        public void DeserializeByteArrayClass()
        {
            string json = @"{
  ""ByteArray"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
  ""NullByteArray"": null
}";

            ByteArrayClass byteArrayClass = JsonConvert.DeserializeObject<ByteArrayClass>(json);

            CollectionAssert.AreEquivalent(TestData, byteArrayClass.ByteArray);
            Assert.AreEqual(null, byteArrayClass.NullByteArray);
        }

        [Test]
        public void DeserializeByteArrayFromJsonArray()
        {
            string json = @"{
  ""ByteArray"": [0, 1, 2, 3],
  ""NullByteArray"": null
}";

            ByteArrayClass c = JsonConvert.DeserializeObject<ByteArrayClass>(json);
            Assert.IsNotNull(c.ByteArray);
            Assert.AreEqual(4, c.ByteArray.Length);
            CollectionAssert.AreEquivalent(new byte[] { 0, 1, 2, 3 }, c.ByteArray);
        }
    }
}


text:
using Cake.Core;
using Cake.Core.IO;
using Cake.Core.Tooling;
using System.Collections.Generic;
using System.Linq;

namespace Cake.Docker
{
    /// <summary>
    /// Base class for all Docker related tools.
    /// </summary>
    /// <typeparam name="TSettings">The settings type.</typeparam>
    public abstract class DockerComposeTool<TSettings>: Tool<TSettings>
        where TSettings: ToolSettings
    {
        private readonly ICakeEnvironment _environment;
        private readonly IFileSystem _fileSystem;

        /// <summary>
        /// Initializes a new instance of the <see cref="DockerTool{TSettings}"/> class.
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="environment">The environment.</param>
        /// <param name="processRunner">The process runner.</param>
        /// <param name="tools">The tools.</param>
        protected DockerComposeTool(
            IFileSystem fileSystem,
            ICakeEnvironment environment,
            IProcessRunner processRunner,
            IToolLocator tools)
            : base(fileSystem, environment, processRunner, tools)
        {
            _fileSystem = fileSystem;
            _environment = environment;
        }

        /// <summary>
        /// Gets the name of the tool.
        /// </summary>
        /// <returns>The name of the tool.</returns>
        protected override string GetToolName()
        {
            return "DockerCompose";
        }

        /// <summary>
        /// Gets the possible names of the tool executable.
        /// </summary>
        /// <returns>The tool executable name.</returns>
        protected override IEnumerable<string> GetToolExecutableNames()
        {
            // In WSL (Windows Subsystem for Linux), both 'docker-compose' and
            // 'docker-compose.exe' are available. The Linux version of docker-compose
            // must have precedence over the windows version so that the native
            // (i.e. Linux) version of docker-compose is used under WSL.
            if (_environment.Platform.IsUnix())
            {
                return new[] { "docker-compose", "docker-compose.exe" };
            }
            else
            {
                return new[] { "docker-compose.exe", "docker-compose" };
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <returns></returns>
        protected override IEnumerable<FilePath> GetAlternativeToolPaths(TSettings settings)
        {
            var path = DockerResolver.GetDockerPath(_fileSystem, _environment);
            return path != null
                ? new[] { path }
                : Enumerable.Empty<FilePath>();
        }
    }
}


text:
liangkai
renwei
renyashun

# Author
liangkai
renyashun
zhangshengchao

# Reviewer
liangkai
renyashun
zhangshengchao
zhapuyu


text:
<!doctype html>

<meta charset="utf-8" />

    <canvas width="600" height="400" id="cvs"></canvas>

            <button id="save">save</button> or <button id="convert">convert to</button> as:
            <select id="sel">
                <option value="png">png</option>
                <option value="jpeg">jpeg</option>
                <option value="bmp">bmp</option>
            </select>

            width : <input type="number" value="300" id="imgW" />

            height : <input type="number" value="200" id="imgH" />


text:
/*! \file jpush_api.c
* \brief jpush API deal implementation
* \author Sean Wang
* \date 2016
* \version 1.0
* @ingroup outer_interface

*/

#define JPUSH_API_C

#include <Python.h>

#include "utils/log/log.h"

#include "jpush_api.h"

/***
 * Function init_jpush_interface()
 * Initialize the jpush interface layer
 *
 */
void init_jpush_interface()
{
	/*int ret = 0;

	PRT_LOG_T(LOG_ERR, OUTER_INTERFACE, "Start to init jpush interface...\n");
	Py_Initialize();
	PyObject *pModule = NULL;
	PyObject *pFunc = NULL;
	PyObject *pReturn = NULL;
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('/home/openair/xiao-zhi-app-service/outer_interface/jpush_api/')");
	// create and set 2 float args(all args format is tuple type)
	PyObject *pArgs = PyTuple_New(1);
	PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", "test python jpush api"));
	pModule = PyImport_ImportModule("jpush_api");
	if (!pModule)
	{
		PRT_LOG_T(LOG_ERR, OUTER_INTERFACE, "Import python module error\n");
	}
	else
	{
		pFunc = PyObject_GetAttrString(pModule, "jpush_push");
		if (!pFunc)
		{
			PRT_LOG_T(LOG_ERR, OUTER_INTERFACE, "Get python function error\n");
		}
		else
		{
			pReturn = PyEval_CallObject(pFunc, pArgs);
			if (!pReturn)
			{
				PRT_LOG_T(LOG_ERR, OUTER_INTERFACE, "Perform python function error\n");
			}
			else
			{
				// convert python return result to int
				PyArg_Parse(pReturn, "i", &ret);
				PRT_LOG_T(LOG_INFO, OUTER_INTERFACE, "ret=%d\n", ret);
			}
		}
	}
	Py_Finalize();*/
}

/***
 * Function send_msg_to_jpush()
 * Sending message info to jpush
 * return: OK 0; NOK -1
 *
 */
int send_msg_to_jpush(char *push_info)
{
	int ret = 0;

	PRT_LOG_T(LOG_ERR, OUTER_INTERFACE, "Start to init jpush interface...\n");
	Py_Initialize();
	PyObject *pModule = NULL;
	PyObject *pFunc = NULL;
	PyObject *pReturn = NULL;
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('/home/openair/xiao-zhi-app-service/outer_interface/jpush_api/')");
	// create and set 2 float args(all args format is tuple type)
	PyObject *pArgs = PyTuple_New(1);
	PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", push_info));
	pModule = PyImport_ImportModule("jpush_api");
	if (!pModule)
	{
		PRT_LOG_T(LOG_ERR, OUTER_INTERFACE, "Import python module error\n");
		return -1;
	}
	else
	{
		pFunc = PyObject_GetAttrString(pModule, "jpush_push");
		if (!pFunc)
		{
			PRT_LOG_T(LOG_ERR, OUTER_INTERFACE, "Get python function error\n");
			return -1;
		}
		else
		{
			pReturn = PyEval_CallObject(pFunc, pArgs);
			if (!pReturn)
			{
				PRT_LOG_T(LOG_ERR, OUTER_INTERFACE, "Perform python function error\n");
				return -1;
			}
			else
			{
				// convert python return result to int
				PyArg_Parse(pReturn, "i", &ret);
				PRT_LOG_T(LOG_INFO, OUTER_INTERFACE, "ret=%d\n", ret);
			}
		}
	}
	Py_Finalize();

	return 0;
}


text:
namespace g{namespace Fuse{namespace Themes{struct GraphicsStyle;}}}
namespace g{namespace Fuse{namespace Themes{struct GraphicsStyle__Template2;}}}

namespace g{
namespace Fuse{
namespace Themes{

// public partial sealed class GraphicsStyle.Template2 :66
// {
::g::Uno::UX::Template_type* GraphicsStyle__Template2_typeof();
void GraphicsStyle__Template2__ctor_1_fn(GraphicsStyle__Template2* __this, ::g::Fuse::Themes::GraphicsStyle* parent);
void GraphicsStyle__Template2__New1_fn(::g::Fuse::Themes::GraphicsStyle* parent, GraphicsStyle__Template2** __retval);
void GraphicsStyle__Template2__OnApply_fn(GraphicsStyle__Template2* __this, ::g::Fuse::Controls::Circle* self);

struct GraphicsStyle__Template2 : ::g::Uno::UX::Template
{
    uStrong< ::g::Fuse::Themes::GraphicsStyle*> __parent1;

    void ctor_1(::g::Fuse::Themes::GraphicsStyle* parent);
    static GraphicsStyle__Template2* New1(::g::Fuse::Themes::GraphicsStyle* parent);
};
// }

}}} // ::g::Fuse::Themes


text:
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const util = __importStar(require("../util"));
exports.default = util.createRule({
    name: 'no-parameter-properties',
    meta: {
        type: 'problem',
        docs: {
            description: 'Disallow the use of parameter properties in class constructors',
            category: 'Stylistic Issues',
            recommended: 'error',
        },
        messages: {
            noParamProp: 'Property {{parameter}} cannot be declared in the constructor.',
        },
        schema: [
            {
                type: 'object',
                properties: {
                    allows: {
                        type: 'array',
                        items: {
                            enum: [
                                'readonly',
                                'private',
                                'protected',
                                'public',
                                'private readonly',
                                'protected readonly',
                                'public readonly',
                            ],
                        },
                        minItems: 1,
                    },
                },
                additionalProperties: false,
            },
        ],
    },
    defaultOptions: [
        {
            allows: [],
        },
    ],
    create(context, [{ allows }]) {
        /**
         * Gets the modifiers of `node`.
         * @param node the node to be inspected.
         */
        function getModifiers(node) {
            const modifiers = [];
            if (node.accessibility) {
                modifiers.push(node.accessibility);
            }
            if (node.readonly) {
                modifiers.push('readonly');
            }
            return modifiers.filter(Boolean).join(' ');
        }
        return {
            TSParameterProperty(node) {
                const modifiers = getModifiers(node);
                if (allows.indexOf(modifiers) === -1) {
                    // HAS to be an identifier or assignment or TSC will throw
                    if (node.parameter.type !== experimental_utils_1.AST_NODE_TYPES.Identifier &&
                        node.parameter.type !== experimental_utils_1.AST_NODE_TYPES.AssignmentPattern) {
                        return;
                    }
                    const name = node.parameter.type === experimental_utils_1.AST_NODE_TYPES.Identifier
                        ? node.parameter.name
                        : // has to be an Identifier or TSC will throw an error
                            node.parameter.left.name;
                    context.report({
                        node,
                        messageId: 'noParamProp',
                        data: {
                            parameter: name,
                        },
                    });
                }
            },
        };
    },
});
//# sourceMappingURL=no-parameter-properties.js.map