text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="rest" default="compile" basedir=".">
    <description>Project Build File</description>

    <property environment="env" />
    <property name="gwt.sdk.home" value="${env.GWT_HOME}" />
    <property name="ant.build.javac.source" value="1.6" />
    <property name="ant.build.javac.target" value="1.6" />

    <property name="javac.encoding" value="UTF-8" />
    <property name="java.file.encoding" value="UTF-8" />

    <property name="src.rel-dir" value="src" />
    <property name="build.rel-dir" value="build" />
    <property name="lib.rel-dir" value="../lib" />

    <property name="main.src.rel-dir" value="${src.rel-dir}/main" />

    <property name="dml.filename" value="domain.dml" />

    <property name="java.main.src.rel-dir" value="${main.src.rel-dir}/java" />
    <property name="dml.src.rel-dir" value="${main.src.rel-dir}/dml" />
    <property name="generated-src.build.rel-dir" value="${build.rel-dir}/src" />
    <property name="classes.build.rel-dir" value="${build.rel-dir}/classes" />

    <property name="test.src.rel-dir" value="${src.rel-dir}/test" />
    <property name="java.test.src.rel-dir" value="${test.src.rel-dir}/java" />

    <property name="dml.rel-file" value="${dml.src.rel-dir}/${dml.filename}" />

    <property name="sql.driver" value="com.mysql.jdbc.Driver" />
    <property name="sql.db" value="restdb" />
    <property name="sql.url" value="jdbc:mysql://localhost:3306" />
    <property name="sql.user" value="rest" />
    <property name="sql.pass" value="r3st" />

    <property name="gwt.war.rel-dir" value="war" />
    <property name="gwt.war.classes.rel-dir" value="${gwt.war.rel-dir}/WEB-INF/classes" />
    <property name="gwt.war.lib.rel-dir" value="${gwt.war.rel-dir}/WEB-INF/lib" />
    <!--  Arguments to gwtc and devmode targets  -->
    <property name="gwt.args" value="" />
    <property name="startUpURL" value="http://127.0.0.1:8888/RestGWT.html?gwt.codesvr=127.0.0.1:9997"/>
    <property name="startUpURLOnline" value="http://127.0.0.1:8888/RestGWTOnline.html?gwt.codesvr=127.0.0.1:9997"/>
    <path id="project.classpath">
        <pathelement location="${classes.build.rel-dir}" />
        <fileset dir="${lib.rel-dir}">
            <include name="**/*.jar" />
        </fileset>
        <fileset dir="${gwt.sdk.home}">
            <include name="**/*.jar" />
        </fileset>
    </path>

    <taskdef resource="dml-ant.xml" classpathref="project.classpath" />

    <target name="prepare">
        <echo message="Preparing the project for build..." />
        <mkdir dir="${classes.build.rel-dir}" />
    </target>

    <target name="generate-domain" depends="prepare">
        <echo message="Generating base domain classes..." />
        <echo message="Using: ${dml.rel-file}" />
        <dml-domain-generator destDirectory="${java.main.src.rel-dir}" destDirectoryBase="${generated-src.build.rel-dir}">
            <fileset file="${dml.rel-file}" />
        </dml-domain-generator>
    </target>

    <target name="compile-domain" depends="generate-domain, prepare">
        <echo message="Compiling sources..." />
        <javac destdir="${classes.build.rel-dir}" debug="true" debuglevel="lines,vars,source" optimize="true" deprecation="true" verbose="false" includeantruntime="false">
            <classpath refid="project.classpath" />
            <src>
                <pathelement path="${generated-src.build.rel-dir}:${java.main.src.rel-dir}" />
            </src>
            <compilerarg line="" />
        </javac>
    </target>

    <target name="instrument-classes" depends="compile-domain, compile-tests">
        <echo message="Injecting FenixFramework Voodoo Magic..." />
        <dml-post-processor dir="${classes.build.rel-dir}">
            <fileset file="${dml.rel-file}" />
            <classpath refid="project.classpath" />
        </dml-post-processor>
    </target>

    <target name="populate" depends="compile" description="Populates  the initial data">
        <java classname="pt.ist.rest.RestSetup" fork="true">
            <classpath>
                <path refid="project.classpath" />
            </classpath>
        </java>
    </target>

    <target name="compile" depends="instrument-classes" description="Compiles the whole project" />

    <target name="run" depends="compile" description="Runs the program">
        <!-- Fork alterado para true para suportar asserts -->
        <java classname="pt.ist.rest.presentationserver.PresentationServer" fork="true">
            <classpath>
                <path refid="project.classpath" />
            </classpath>
            <jvmarg value="-ea" />
        </java>
    </target>

    <target name="clean" description="Cleans the compiled classes and generated sources">
        <delete dir="${build.rel-dir}" />
        <delete dir="${gwt.war.classes.rel-dir}" />
    </target>

    <target name="clean-db" description="Recreated project's database">
        <echo message="Creating SQL database '${sql.db}'" />
        <sql driver="${sql.driver}" url="${sql.url}" userid="${sql.user}" password="${sql.pass}">
            <classpath refid="project.classpath" />
            DROP DATABASE IF EXISTS ${sql.db};
        </sql>
        <sql driver="${sql.driver}" url="${sql.url}" userid="${sql.user}" password="${sql.pass}">
            <classpath refid="project.classpath" />
            CREATE DATABASE IF NOT EXISTS ${sql.db};
        </sql>
    </target>

    <target name="clean-gwt" >
        <delete file="${gwt.war.rel-dir}/phonebook.log" />
        <delete  dir="${gwt.war.rel-dir}/src" />
        <delete  dir="${gwt.war.classes.rel-dir}" />
        <delete  dir="${gwt.war.web-inf.rel-dir}/images" />
        <delete  dir="${gwt.war.web-inf.rel-dir}/deploy" />
        <delete  dir="${gwt.war.rel-dir}/phonebook" />
        <delete  dir="gwt-UnitCache" />
      </target>

    <target name="populate-run" depends="clean, clean-db, populate" description="Cleans everything, compiles again and runs.">
        <java classname="pt.ist.rest.presentationserver.PresentationServer" fork="false">
            <classpath>
                <path refid="project.classpath" />
            </classpath>
        </java>
    </target>

    <target name="compile-tests" depends="compile-domain" description="Compile  the
    tests">
        <javac destdir="${classes.build.rel-dir}" debug="true" verbose="false" debuglevel="lines,vars,source" optimize="true" deprecation="true" includeantruntime="false" encoding="${javac.encoding}">
            <classpath refid="project.classpath" />
            <src>
                <pathelement path="${java.test.src.rel-dir}" />
            </src>
        </javac>
    </target>

    <target name="test" depends="compile" description="Run  the  tests">
        <junit fork="yes" forkmode="once">
            <classpath refid="project.classpath" />
            <formatter type="brief" usefile="false" />
            <test name="EsvaziarTabuleiroServiceTest" />
            <test name="ProcurarPratoServiceTest" />
            <test name="AdicionaItemTabuleiroTest" />
			<test name="PrecoMaximoTest" />
        	<test name="ObterTabuleiroDeComprasServiceTest" />
        </junit>
    </target>

    <target name="gwtc" depends="compile" description="GWT compile to JavaScript (production mode)">
        <java failonerror="true" fork="true" classname="com.google.gwt.dev.Compiler">
            <classpath>
                <pathelement location="${java.main.src.rel-dir}" />
                <path refid="project.classpath" />
            </classpath>
            <!--
     add jvmarg -Xss16M or similar if you see a StackOverflowError
    -->
            <jvmarg value="-Xmx256M" />
            <arg line="-war" />
            <arg value="${gwt.war.rel-dir}" />
            <!--
     Additional arguments like -style PRETTY or -logLevel DEBUG
    -->
            <arg line="${gwt.args}" />
            <arg value="pt.ist.rest.RestGWT" />
        </java>
    </target>
    <target name="gwt-devmode" depends="compile">
        <echo message="Running GWT in devmode with URL='${startUpURL}'" />
        <mkdir dir="${gwt.war.classes.rel-dir}" />
        <copy todir="${gwt.war.classes.rel-dir}">
            <fileset dir="${classes.build.rel-dir}" includes="**/*.class" />
        </copy>
        <copy todir="${gwt.war.classes.rel-dir}">
            <fileset dir="${java.main.src.rel-dir}" excludes="**/*.java" />
        </copy>
        <copy todir="${gwt.war.classes.rel-dir}" file="log4j.properties" />
        <copy todir="${gwt.war.rel-dir}/src/main/dml" file="${dml.rel-file}" />
        <copy todir="${gwt.war.classes.rel-dir}/src/main/dml" file="${dml.rel-file}" />
        <java failonerror="true" fork="true" classname="com.google.gwt.dev.DevMode">
            <classpath>
                <path refid="project.classpath" />
                <pathelement location="${java.main.src.rel-dir}" />
            </classpath>
            <jvmarg value="-Xmx256M" />
            <arg value="-startupUrl" />
            <arg value="${startUpURL}" />
            <arg line="-war" />
            <arg value="${gwt.war.rel-dir}" />
            <!--
            Additional arguments like -style PRETTY or -logLevel DEBUG
            -->
            <arg line="${gwt.args}" />
            <arg value="pt.ist.rest.RestGWT" />
        </java>
    </target>
    <target name="devmode-local" description="Runs GWT in development mode with local configuration">
        <antcall target="gwt-devmode">
            <param name="startUpURL" value="RestGWT.html" />
        </antcall>
    </target>
    <target name="devmode-remote" description="Runs GWT in development mode with remote configuration">
        <antcall target="gwt-devmode">
            <param name="startUpURL" value="RestGWTOnline.html" />
        </antcall>
    </target>
    <target name="print-env-vars" description="Prints all environment variables">
        <propertyset id="environment">
            <propertyref prefix="env." />
        </propertyset>
        <property name="env_prop" refid="environment" />
        <echo>${env_prop}</echo>
    </target>
</project>


text:
#include "src/core/lib/iomgr/sockaddr.h"

#include "test/core/util/passthru_endpoint.h"

#include <inttypes.h>
#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>

#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/slice/slice_internal.h"

#define WRITE_BUFFER_SIZE (2 * 1024 * 1024)

typedef struct {
  grpc_endpoint base;
  double bytes_per_second;
  grpc_endpoint* wrapped;
  gpr_timespec last_write;

  gpr_mu mu;
  grpc_slice_buffer write_buffer;
  grpc_slice_buffer writing_buffer;
  grpc_error* error;
  bool writing;
  grpc_closure* write_cb;
} trickle_endpoint;

static void te_read(grpc_endpoint* ep, grpc_slice_buffer* slices,
                    grpc_closure* cb, bool urgent) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  grpc_endpoint_read(te->wrapped, slices, cb, urgent);
}

static void maybe_call_write_cb_locked(trickle_endpoint* te) {
  if (te->write_cb != nullptr &&
      (te->error != GRPC_ERROR_NONE ||
       te->write_buffer.length <= WRITE_BUFFER_SIZE)) {
    grpc_core::ExecCtx::Run(DEBUG_LOCATION, te->write_cb,
                            GRPC_ERROR_REF(te->error));
    te->write_cb = nullptr;
  }
}

static void te_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
                     grpc_closure* cb, void* /*arg*/) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  gpr_mu_lock(&te->mu);
  GPR_ASSERT(te->write_cb == nullptr);
  if (te->write_buffer.length == 0) {
    te->last_write = gpr_now(GPR_CLOCK_MONOTONIC);
  }
  for (size_t i = 0; i < slices->count; i++) {
    grpc_slice_buffer_add(&te->write_buffer,
                          grpc_slice_copy(slices->slices[i]));
  }
  te->write_cb = cb;
  maybe_call_write_cb_locked(te);
  gpr_mu_unlock(&te->mu);
}

static void te_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  grpc_endpoint_add_to_pollset(te->wrapped, pollset);
}

static void te_add_to_pollset_set(grpc_endpoint* ep,
                                  grpc_pollset_set* pollset_set) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  grpc_endpoint_add_to_pollset_set(te->wrapped, pollset_set);
}

static void te_delete_from_pollset_set(grpc_endpoint* ep,
                                       grpc_pollset_set* pollset_set) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  grpc_endpoint_delete_from_pollset_set(te->wrapped, pollset_set);
}

static void te_shutdown(grpc_endpoint* ep, grpc_error* why) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  gpr_mu_lock(&te->mu);
  if (te->error == GRPC_ERROR_NONE) {
    te->error = GRPC_ERROR_REF(why);
  }
  maybe_call_write_cb_locked(te);
  gpr_mu_unlock(&te->mu);
  grpc_endpoint_shutdown(te->wrapped, why);
}

static void te_destroy(grpc_endpoint* ep) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  grpc_endpoint_destroy(te->wrapped);
  gpr_mu_destroy(&te->mu);
  grpc_slice_buffer_destroy_internal(&te->write_buffer);
  grpc_slice_buffer_destroy_internal(&te->writing_buffer);
  GRPC_ERROR_UNREF(te->error);
  gpr_free(te);
}

static grpc_resource_user* te_get_resource_user(grpc_endpoint* ep) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  return grpc_endpoint_get_resource_user(te->wrapped);
}

static absl::string_view te_get_peer(grpc_endpoint* ep) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  return grpc_endpoint_get_peer(te->wrapped);
}

static absl::string_view te_get_local_address(grpc_endpoint* ep) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  return grpc_endpoint_get_local_address(te->wrapped);
}

static int te_get_fd(grpc_endpoint* ep) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  return grpc_endpoint_get_fd(te->wrapped);
}

static bool te_can_track_err(grpc_endpoint* /*ep*/) { return false; }

static void te_finish_write(void* arg, grpc_error* /*error*/) {
  trickle_endpoint* te = static_cast<trickle_endpoint*>(arg);
  gpr_mu_lock(&te->mu);
  te->writing = false;
  grpc_slice_buffer_reset_and_unref(&te->writing_buffer);
  gpr_mu_unlock(&te->mu);
}

static const grpc_endpoint_vtable vtable = {te_read,
                                            te_write,
                                            te_add_to_pollset,
                                            te_add_to_pollset_set,
                                            te_delete_from_pollset_set,
                                            te_shutdown,
                                            te_destroy,
                                            te_get_resource_user,
                                            te_get_peer,
                                            te_get_local_address,
                                            te_get_fd,
                                            te_can_track_err};

grpc_endpoint* grpc_trickle_endpoint_create(grpc_endpoint* wrap,
                                            double bytes_per_second) {
  trickle_endpoint* te =
      static_cast<trickle_endpoint*>(gpr_malloc(sizeof(*te)));
  te->base.vtable = &vtable;
  te->wrapped = wrap;
  te->bytes_per_second = bytes_per_second;
  te->write_cb = nullptr;
  gpr_mu_init(&te->mu);
  grpc_slice_buffer_init(&te->write_buffer);
  grpc_slice_buffer_init(&te->writing_buffer);
  te->error = GRPC_ERROR_NONE;
  te->writing = false;
  return &te->base;
}

static double ts2dbl(gpr_timespec s) {
  return static_cast<double>(s.tv_sec) + 1e-9 * static_cast<double>(s.tv_nsec);
}

size_t grpc_trickle_endpoint_trickle(grpc_endpoint* ep) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  gpr_mu_lock(&te->mu);
  if (!te->writing && te->write_buffer.length > 0) {
    gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
    double elapsed = ts2dbl(gpr_time_sub(now, te->last_write));
    size_t bytes = static_cast<size_t>(te->bytes_per_second * elapsed);
    // gpr_log(GPR_DEBUG, "%lf elapsed --> %" PRIdPTR " bytes", elapsed, bytes);
    if (bytes > 0) {
      grpc_slice_buffer_move_first(&te->write_buffer,
                                   GPR_MIN(bytes, te->write_buffer.length),
                                   &te->writing_buffer);
      te->writing = true;
      te->last_write = now;
      grpc_endpoint_write(
          te->wrapped, &te->writing_buffer,
          GRPC_CLOSURE_CREATE(te_finish_write, te, grpc_schedule_on_exec_ctx),
          nullptr);
      maybe_call_write_cb_locked(te);
    }
  }
  size_t backlog = te->write_buffer.length;
  gpr_mu_unlock(&te->mu);
  return backlog;
}

size_t grpc_trickle_get_backlog(grpc_endpoint* ep) {
  trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
  gpr_mu_lock(&te->mu);
  size_t backlog = te->write_buffer.length;
  gpr_mu_unlock(&te->mu);
  return backlog;
}

redpajama_set_name: RedPajamaGithub


text:
package system.file;

/**
 * The device configuration parser exception class.
 */
public class DeviceConfigParserException extends Exception
{
 /** The serialVersionUID. */
 private static final long serialVersionUID = 1L;
 /** The error message. */
 private String message;

 /**
  * Instantiates a new device configuration parser exception.
  *
  * @param s the error message.
  */
 public DeviceConfigParserException(String s)
 {
  message = s;
 }

 /**
  * Returns the error message.
  *
  * @return the error message.
  * @see java.lang.Throwable#getMessage()
  */
 public String getMessage()
 {
  return message;
 }
}


text:
layout: post
title:  "Markdown Resources"
date:   2015-01-12 10:30:00
comments: true
---

A list of Markdown resources.

## Syntax

[Markdown Syntax Cheat Sheet](http://stationinthemetro.com/wp-content/uploads/2013/04/Markdown_Cheat_Sheet_v1-1.pdf)

[Another Cheat](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Governance / Some monitoring guys</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="shortcut icon" href="/theme/favicon16.png" />
    <link rel="apple-touch-icon" href="/theme/favicon32.png.png" />
    <link rel="apple-touch-icon" sizes="72x72" href="/theme/favicon48.png" />
    <link rel="apple-touch-icon" sizes="114x114" href="/theme/favicon64.png" />
    <link rel="apple-touch-icon" sizes="144x144" href="/theme/favicon64.png" />
    <link href='http://fonts.googleapis.com/css?family=Lato:400,700,300italic,300' rel='stylesheet' type='text/css'>

      <link rel="stylesheet" href="/theme/css/bootstrap.css">

      <link rel="stylesheet" href="/theme/css/colorbox.css">
      <link rel="stylesheet" href="/theme/css/main.css">

shinken-solutions.com

<tiny>Business-centric monitoring</tiny>

shinken-monitoring.org

Shinken framework project

shinken.io

Shinken packages platform

shinkenlab.io

Let's discuss about monitoring

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>

              Home

              Download

              Docs

                Some monitoring guys

                  /

<time datetime="2015-02-11T10:20:00">
11
 Feb 2015 </time>

Governance

	    Gabès Jean

Hi :)

Just a small post to let you know that now we have a vision and governance text now. This give us a clear and common view on where we are going and how code and contribution can be evaluated :)

I hope this will allow us to know on what to focus, what can be accepted in the project, and what can't be without hurting the whole project.

If I must reduce the governance into a single line, it will be that I'll always keep both the project but also the code accessible for its main users, the admins. It is what base the project and why is can answer to its users, so I'll keep it that way :)

You can have a look at the vision and governance file here :)

I'll also set the same governance on the kunai project ^^

 jean gabès

Posted in: Project

Tagged as: shinken / governance

Wanna tell me what you think? Get in touch.

    Please enable JavaScript to view the comments powered by Disqus.
    comments powered by Disqus

Posted in: Project

Tagged as: shinken / governance

Search

          <gcse:search></gcse:search>

Archives

23 Oct 2017 :

              WebUI 2.7 is out

05 Oct 2015 :

              2.4.2 release

22 Sep 2015 :

              WebUI 2 release

15 Jul 2015 :

              2.4.1 release

06 May 2015 :

              About tests

04 May 2015 :

              2.4 release

20 Feb 2015 :

              Smart agent solution

12 Feb 2015 :

              kernel.shinken.io

11 Feb 2015 :

              Governance

30 Jan 2015 :

              PEP8 compatibility

19 Jan 2015 :

              2.2 release

13 Jan 2015 :

              Some news and announcements for 2015

08 Sep 2014 :

              Online course 6: LAN scalability, adding pollers

07 Aug 2014 :

              Online course 5: Monitoring Plugins

16 Apr 2014 :

              2.0 release

08 Apr 2014 :

              2.0 RC: last patch to test :)

19 Mar 2014 :

              Online course 4: High Availability

11 Mar 2014 :

              Online course 3: 1.4 to 2.0 migration

07 Mar 2014 :

              Online course 2: installing WebUI

04 Mar 2014 :

              Online course 1: installing shinken 2.0

17 Feb 2014 :

              The 2.0 RC version and the project

16 Feb 2014 :

              Byebye wordpress

            Home

            Download

            Docs

            Contact Us


text:
'use strict';

describe('myApp.storia module', function() {

  beforeEach(module('myApp.storia'));

  describe('storia controller', function(){

    it('should ....', inject(function($controller) {
      //spec body
      var storiaCtrl = $controller('storiaCtrl');
      expect(storiaCtrl).toBeDefined();
    }));

  });
});


text:
/**
 * @license Licensed under the Apache License, Version 2.0 (the "License"):
 *          http://www.apache.org/licenses/LICENSE-2.0
 */

/**
 * @fileoverview Arduino blocks for the Servo library.
 *     The Arduino Servo functions can be found in
 *     http://arduino.cc/en/reference/servo
 *
 * TODO: Add angle selector instead of block input.
 */
'use strict';

goog.provide('Blockly.Blocks.servo');

goog.require('Blockly.Blocks');
goog.require('Blockly.Types');

/** Common HSV hue for all blocks in this category. */
Blockly.Blocks.servo.HUE = 60;

Blockly.Blocks['servo_write'] = {
  /**
   * Block for writing an angle value into a servo pin.
   * @this Blockly.Block
   */
  init: function() {
    this.setHelpUrl('http://arduino.cc/en/Reference/ServoWrite');
    this.setColour(Blockly.Blocks.servo.HUE);
    this.appendDummyInput()
        .appendField(Blockly.Msg.ARD_SERVO_WRITE)
        .appendField(new Blockly.FieldDropdown(
            Blockly.Arduino.Boards.selected.digitalPins), 'SERVO_PIN');
    this.setInputsInline(false);
    this.appendValueInput('SERVO_ANGLE')
        .setCheck(Blockly.Types.NUMBER.checkList)
        .appendField(Blockly.Msg.ARD_SERVO_WRITE_TO);
    this.appendDummyInput()
        .appendField(Blockly.Msg.ARD_SERVO_WRITE_DEG_180);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setTooltip(Blockly.Msg.ARD_SERVO_WRITE_TIP);
  },
  /**
   * Updates the content of the the pin related fields.
   * @this Blockly.Block
   */
  updateFields: function() {
    Blockly.Arduino.Boards.refreshBlockFieldDropdown(
        this, 'SERVO_PIN', 'digitalPins');
  }
};

Blockly.Blocks['servo_read'] = {
  /**
   * Block for reading an angle value of a servo pin.
   * @this Blockly.Block
   */
  init: function() {
    this.setHelpUrl('http://arduino.cc/en/Reference/ServoRead');
    this.setColour(Blockly.Blocks.servo.HUE);
    this.appendDummyInput()
        .appendField(Blockly.Msg.ARD_SERVO_READ)
        .appendField(new Blockly.FieldDropdown(
            Blockly.Arduino.Boards.selected.digitalPins), 'SERVO_PIN');
    this.setOutput(true, Blockly.Types.NUMBER.output);
    this.setTooltip(Blockly.Msg.ARD_SERVO_READ_TIP);
  },
  /** @return {string} The type of return value for the block, an integer. */
  getBlockType: function() {
    return Blockly.Types.NUMBER;
  },
  /**
   * Updates the content of the the pin related fields.
   * @this Blockly.Block
   */
  updateFields: function() {
    Blockly.Arduino.Boards.refreshBlockFieldDropdown(
        this, 'SERVO_PIN', 'digitalPins');
  }
};


text:
<?php
namespace VideoPublisher\Security;

use VideoPublisher\Exception\TokenCacheNotWritableException;
use VideoPublisher\Exception\TokenNotFoundException;

/**
 * Class TokenVault.
 *
 * @author Bart Malestein <bart@isset.nl>
 */
class TokenVault
{
    /**
     * @var string
     */
    private $tokenCacheLocation;

    /**
     * TokenVault constructor.
     * @param $tokenCacheLocation
     * @throws TokenCacheNotWritableException
     */
    public function __construct($tokenCacheLocation)
    {
        $this->tokenCacheLocation = rtrim($tokenCacheLocation, '/') . '/';
        if (false === is_writable($tokenCacheLocation)) {
            throw new TokenCacheNotWritableException('token cache location isn\'t writable: ' . $tokenCacheLocation);
        }
    }

    /**
     * @param string $consumerKey
     * @param Token $token
     */
    public function addToken($consumerKey, Token $token)
    {
        file_put_contents($this->getPathForToken($consumerKey), $token->getValue());
    }

    /**
     * @param string $consumerKey
     */
    public function removeToken($consumerKey)
    {
        $location = $this->getPathForToken($consumerKey);
        if (file_exists($location)) {
            unlink($location);
        }
    }

    /**
     * @param string $consumerKey
     * @return bool
     */
    public function hasToken($consumerKey)
    {
        $location = $this->getPathForToken($consumerKey);

        return file_exists($location);
    }

    /**
     * @param string $consumerKey
     * @return Token
     * @throws TokenNotFoundException
     */
    public function getToken($consumerKey)
    {
        $location = $this->getPathForToken($consumerKey);
        if (false === file_exists($location)) {
            throw new TokenNotFoundException();
        }
        return new Token(file_get_contents($location));
    }

    /**
     * @param string $consumerKey
     * @return string
     */
    public function getPathForToken($consumerKey)
    {
        return $this->tokenCacheLocation . sha1($consumerKey);
    }
}


text:
package tests;

import javax.annotation.Generated;
import javax.inject.Inject;
import tests.MultipleFactoriesImplementingInterface.Base.Factory;

@Generated("com.google.auto.factory.processor.AutoFactoryProcessor")
final class MultipleFactoriesImplementingInterfaceAFactory implements Factory {
  @Inject
  MultipleFactoriesImplementingInterfaceAFactory() {}

  MultipleFactoriesImplementingInterface.MultipleFactoriesImplementingInterfaceA create() {
    return new MultipleFactoriesImplementingInterface.MultipleFactoriesImplementingInterfaceA();
  }

  @Override
  public MultipleFactoriesImplementingInterface.MultipleFactoriesImplementingInterfaceA
      abstractNonDefaultCreate() {
    return create();
  }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE415_Double_Free__malloc_free_char_61a.c
Label Definition File: CWE415_Double_Free__malloc_free.label.xml
Template File: sources-sinks-61a.tmpl.c
*/
/*
 * @description
 * CWE: 415 Double Free
 * BadSource:  Allocate data using malloc() and Deallocate data using free()
 * GoodSource: Allocate data using malloc()
 * Sinks:
 *    GoodSink: do nothing
 *    BadSink : Deallocate data using free()
 * Flow Variant: 61 Data flow: data returned from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifndef OMITBAD

/* bad function declaration */
char * CWE415_Double_Free__malloc_free_char_61b_badSource(char * data);

void CWE415_Double_Free__malloc_free_char_61_bad()
{
    char * data;
    /* Initialize data */
    data = NULL;
    data = CWE415_Double_Free__malloc_free_char_61b_badSource(data);
    /* POTENTIAL FLAW: Possibly freeing memory twice */
    free(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
char * CWE415_Double_Free__malloc_free_char_61b_goodG2BSource(char * data);

static void goodG2B()
{
    char * data;
    /* Initialize data */
    data = NULL;
    data = CWE415_Double_Free__malloc_free_char_61b_goodG2BSource(data);
    /* POTENTIAL FLAW: Possibly freeing memory twice */
    free(data);
}

/* goodB2G uses the BadSource with the GoodSink */
char * CWE415_Double_Free__malloc_free_char_61b_goodB2GSource(char * data);

static void goodB2G()
{
    char * data;
    /* Initialize data */
    data = NULL;
    data = CWE415_Double_Free__malloc_free_char_61b_goodB2GSource(data);
    /* do nothing */
    /* FIX: Don't attempt to free the memory */
    ; /* empty statement needed for some flow variants */
}

void CWE415_Double_Free__malloc_free_char_61_good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE415_Double_Free__malloc_free_char_61_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE415_Double_Free__malloc_free_char_61_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
import os

import pytest

class TestExhibitor:

    def test_permissions(self) -> None:
        """
        ZooKeeper data files are not accessible
        """
        # Verify that a parent directory exists
        assert os.path.isdir('/var/lib/dcos/exhibitor/zookeeper')
        # Verify that snapshots and transaction logs are not accessible
        with pytest.raises(PermissionError):
            os.listdir('/var/lib/dcos/exhibitor/zookeeper/snapshot')
        with pytest.raises(PermissionError):
            os.listdir('/var/lib/dcos/exhibitor/zookeeper/transactions')


text:
let story = require('storyboard').mainStory;

let plugged = require('../client');

module.exports = {
    event: plugged.SOCK_CLOSED,
    handler:  () =>{
        story.info('Socket', 'Socket was closed. Restarting...');
        process.exit(1);
    }
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using VRGIN.Core;
using XInputDotNetPure;

namespace VookaRaylee
{
    public class RayleeInterpreter : GameInterpreter
    {
        private readonly string[] FX_BLACKLIST = new string[] { "DepthOfField" };

        // Not used
        public override IEnumerable<IActor> Actors
        {
            get
            {
                yield break;
            }
        }

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

            // Make sure those are rendered
            VR.Camera.gameObject.AddComponent<QuillieCameraUpdate>();
        }

        public override bool IsAllowedEffect(MonoBehaviour effect)
        {
            return !FX_BLACKLIST.Contains(effect.GetType().Name) && base.IsAllowedEffect(effect);
        }

    }

}


text:
package org.apache.jackrabbit.spi.commons.nodetype;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.jackrabbit.spi.QItemDefinition;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.QNodeDefinition;
import org.apache.jackrabbit.spi.commons.conversion.NamePathResolver;
import org.apache.jackrabbit.spi.commons.name.NameConstants;

import javax.jcr.nodetype.NodeDefinition;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.NamespaceException;

/**
 * This class implements the NodeDefinition interface.
 * All method calls are delegated to the wrapped {@link QNodeDefinition},
 * performing the translation from Names to JCR names
 * where necessary.
 */
public class NodeDefinitionImpl extends ItemDefinitionImpl implements NodeDefinition {

    /**
     * logger instance
     */
    private static final Logger log = LoggerFactory.getLogger(NodeDefinitionImpl.class);

    /**
     * Constructor to create a definition that is based on a template.
     *
     * @param itemDef  item definition
     * @param resolver
     */
    public NodeDefinitionImpl(QItemDefinition itemDef, NamePathResolver resolver) {
        super(itemDef, resolver);
    }

    /**
     * Constructor to create a definition that is based on an
     * existing node type.
     *
     * @param itemDef  item definition
     * @param resolver
     */
    public NodeDefinitionImpl(QItemDefinition itemDef, AbstractNodeTypeManager ntMgr, NamePathResolver resolver) {
        super(itemDef, ntMgr, resolver);
    }

    /**
     * Returns the wrapped node definition.
     *
     * @return the wrapped node definition.
     */
    public QNodeDefinition unwrap() {
        return (QNodeDefinition) itemDef;
    }

    //-------------------------------------------------------< NodeDefinition >

    /**
     * {@inheritDoc}
     */
    public boolean allowsSameNameSiblings() {
        return ((QNodeDefinition) itemDef).allowsSameNameSiblings();
    }

    /**
     * @see NodeDefinition#getDefaultPrimaryTypeName()
     * @since JCR 2.0
     */
    public String getDefaultPrimaryTypeName() {
        Name ntName = ((QNodeDefinition) itemDef).getDefaultPrimaryType();
        if (ntName == null) {
            return null;
        }
        try {
            return resolver.getJCRName(ntName);
        } catch (NamespaceException e) {
            // should never get here
            log.error("invalid default node type " + ntName, e);
            return null;
        }
    }

    /**
     * {@inheritDoc}
     */
    public NodeType getDefaultPrimaryType() {
        if (ntMgr == null) {
            // not attached to an existing node type
            return null;
        }
        Name ntName = ((QNodeDefinition) itemDef).getDefaultPrimaryType();
        if (ntName == null) {
            return null;
        }
        try {
            return ntMgr.getNodeType(ntName);
        } catch (NoSuchNodeTypeException e) {
            // should never get here
            log.error("invalid default node type " + ntName, e);
            return null;
        }
    }

    /**
     * {@inheritDoc}
     */
    public NodeType[] getRequiredPrimaryTypes() {
        if (ntMgr == null) {
            // not attached to an existing node type
            return null;
        }
        Name[] ntNames = ((QNodeDefinition) itemDef).getRequiredPrimaryTypes();
        try {
            if (ntNames == null || ntNames.length == 0) {
                // return "nt:base"
                return new NodeType[] { ntMgr.getNodeType(NameConstants.NT_BASE) };
            } else {
                NodeType[] nodeTypes = new NodeType[ntNames.length];
                for (int i = 0; i < ntNames.length; i++) {
                    nodeTypes[i] = ntMgr.getNodeType(ntNames[i]);
                }
                return nodeTypes;
            }
        } catch (NoSuchNodeTypeException e) {
            // should never get here
            log.error("required node type does not exist", e);
            return new NodeType[0];
        }
    }

    /**
     * @see NodeDefinition#getRequiredPrimaryTypeNames()
     * @since JCR 2.0
     */
    public String[] getRequiredPrimaryTypeNames() {
        Name[] ntNames = ((QNodeDefinition) itemDef).getRequiredPrimaryTypes();
        try {
            if (ntNames == null || ntNames.length == 0) {
                // return "nt:base"
                return new String[] { resolver.getJCRName(NameConstants.NT_BASE) };
            } else {
                String[] jcrNames = new String[ntNames.length];
                for (int i = 0; i < ntNames.length; i++) {
                    jcrNames[i] = resolver.getJCRName(ntNames[i]);
                }
                return jcrNames;
            }
        } catch (NamespaceException e) {
            // should never get here
            log.error("required node type does not exist", e);
            return new String[0];
        }
    }
}


text:
package com.intellij.codeInsight.daemon.impl.quickfix;

import com.intellij.codeInsight.BlockUtils;
import com.intellij.codeInsight.daemon.impl.actions.IntentionActionWithFixAllOption;
import com.intellij.codeInspection.CommonQuickFixBundle;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.JavaPsiPatternUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.siyeh.ig.psiutils.*;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;
import java.util.stream.Collectors;

public class ConvertSwitchToIfIntention implements IntentionActionWithFixAllOption {
  private final PsiSwitchStatement mySwitchStatement;

  public ConvertSwitchToIfIntention(@NotNull PsiSwitchStatement switchStatement) {
    mySwitchStatement = switchStatement;
  }

  @NotNull
  @Override
  public String getText() {
    return CommonQuickFixBundle.message("fix.replace.x.with.y", PsiKeyword.SWITCH, PsiKeyword.IF);
  }

  @NotNull
  @Override
  public String getFamilyName() {
    return getText();
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    return isAvailable(mySwitchStatement);
  }

  public static boolean isAvailable(PsiSwitchStatement switchStatement) {
    final PsiCodeBlock body = switchStatement.getBody();
    return body != null && !body.isEmpty() && BreakConverter.from(switchStatement) != null && !mayFallThroughNonTerminalDefaultCase(body);
  }

  private static boolean mayFallThroughNonTerminalDefaultCase(PsiCodeBlock body) {
    List<PsiSwitchLabelStatementBase> labels = PsiTreeUtil.getChildrenOfTypeAsList(body, PsiSwitchLabelStatementBase.class);
    return StreamEx.of(labels).pairMap((prev, next) -> {
        if (SwitchUtils.isDefaultLabel(prev)) {
          Set<PsiSwitchLabelStatementBase> targets = getFallThroughTargets(body);
          return targets.contains(prev) || targets.contains(next);
        }
        return false;
      }).has(true);
  }

  @Override
  public void invoke(@NotNull Project project, Editor editor, PsiFile file) {
    doProcessIntention(mySwitchStatement);
  }

  @NotNull
  @Override
  public PsiElement getElementToMakeWritable(@NotNull PsiFile file) {
    return mySwitchStatement;
  }

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

  public static void doProcessIntention(@NotNull PsiSwitchStatement switchStatement) {
    final PsiExpression switchExpression = switchStatement.getExpression();
    if (switchExpression == null) {
      return;
    }
    final PsiType switchExpressionType = RefactoringUtil.getTypeByExpressionWithExpectedType(switchExpression);
    if (switchExpressionType == null) {
      return;
    }
    CommentTracker commentTracker = new CommentTracker();
    final boolean isSwitchOnString = switchExpressionType.equalsToText(CommonClassNames.JAVA_LANG_STRING);
    boolean useEquals = isSwitchOnString;
    if (!useEquals) {
      final PsiClass aClass = PsiUtil.resolveClassInType(switchExpressionType);
      String fqn;
      useEquals = aClass != null && !aClass.isEnum() && ((fqn = aClass.getQualifiedName()) == null || !TypeConversionUtil.isPrimitiveWrapper(fqn));
    }
    PsiCodeBlock body = switchStatement.getBody();
    if (body == null) {
      return;
    }
    // Should execute getFallThroughTargets and statementMayCompleteNormally before converting breaks
    Set<PsiSwitchLabelStatementBase> fallThroughTargets = getFallThroughTargets(body);
    boolean mayCompleteNormally = ControlFlowUtils.statementMayCompleteNormally(switchStatement);
    BreakConverter converter = BreakConverter.from(switchStatement);
    if (converter == null) return;
    converter.process();
    final List<SwitchStatementBranch> allBranches = extractBranches(body, fallThroughTargets);

    final String declarationString;
    final boolean hadSideEffects;
    final String expressionText;
    final Project project = switchStatement.getProject();
    int totalCases = allBranches.stream().mapToInt(br -> br.getCaseElements().size()).sum();
    if (totalCases > 0) {
      commentTracker.markUnchanged(switchExpression);
    }
    if (totalCases > 1 && RemoveUnusedVariableUtil.checkSideEffects(switchExpression, null, new ArrayList<>())) {
      hadSideEffects = true;

      final String variableName = new VariableNameGenerator(switchExpression, VariableKind.LOCAL_VARIABLE)
        .byExpression(switchExpression).byType(switchExpressionType).byName(isSwitchOnString ? "s" : "i").generate(true);
      expressionText = variableName;
      declarationString = switchExpressionType.getCanonicalText() + ' ' + variableName + " = " + switchExpression.getText() + ';';
    }
    else {
      hadSideEffects = false;
      declarationString = null;
      expressionText = ParenthesesUtils.getPrecedence(switchExpression) > ParenthesesUtils.EQUALITY_PRECEDENCE
                       ? '(' + switchExpression.getText() + ')'
                       : switchExpression.getText();
    }

    final StringBuilder ifStatementBuilder = new StringBuilder();
    boolean firstBranch = true;
    SwitchStatementBranch defaultBranch = null;
    for (SwitchStatementBranch branch : allBranches) {
      if (branch.isDefault()) {
        defaultBranch = branch;
      }
      else {
        dumpBranch(branch, expressionText, firstBranch, useEquals, ifStatementBuilder, commentTracker);
        firstBranch = false;
      }
    }
    boolean unwrapDefault = false;
    if (defaultBranch != null) {
      unwrapDefault = defaultBranch.isAlwaysExecuted() || (switchStatement.getParent() instanceof PsiCodeBlock && !mayCompleteNormally);
      if (!unwrapDefault && defaultBranch.hasStatements()) {
        ifStatementBuilder.append("else ");
        dumpBody(defaultBranch, ifStatementBuilder, commentTracker);
      }
    }
    String ifStatementText = ifStatementBuilder.toString();
    if (ifStatementText.isEmpty()) {
      if (!unwrapDefault) return;
      ifStatementText = ";";
    }
    final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
    PsiCodeBlock parent = ObjectUtils.tryCast(switchStatement.getParent(), PsiCodeBlock.class);
    if (unwrapDefault || hadSideEffects) {
      if (parent == null) {
        commentTracker.grabComments(switchStatement);
        switchStatement = BlockUtils.expandSingleStatementToBlockStatement(switchStatement);
        parent = (PsiCodeBlock)(switchStatement.getParent());
      }
    }
    JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
    if (hadSideEffects) {
      final PsiStatement declarationStatement = factory.createStatementFromText(declarationString, switchStatement);
      javaCodeStyleManager.shortenClassReferences(parent.addBefore(declarationStatement, switchStatement));
    }
    final PsiStatement ifStatement = factory.createStatementFromText(ifStatementText, switchStatement);
    if (unwrapDefault) {
      PsiElement addedIf = parent.addBefore(ifStatement, switchStatement);
      StringBuilder sb = new StringBuilder();
      dumpBody(defaultBranch, sb, commentTracker);
      PsiBlockStatement defaultBody = (PsiBlockStatement)factory.createStatementFromText(sb.toString(), switchStatement);
      if (!BlockUtils.containsConflictingDeclarations(Objects.requireNonNull(switchStatement.getBody()), parent)) {
        commentTracker.grabComments(switchStatement);
        BlockUtils.inlineCodeBlock(switchStatement, defaultBody.getCodeBlock());
      }
      else {
        commentTracker.replace(switchStatement, defaultBody);
      }
      commentTracker.insertCommentsBefore(addedIf);
      if (ifStatementText.equals(";")) {
        addedIf.delete();
      }
      else {
        javaCodeStyleManager.shortenClassReferences(addedIf);
      }
    }
    else {
      javaCodeStyleManager.shortenClassReferences(commentTracker.replaceAndRestoreComments(switchStatement, ifStatement));
    }
  }

  @NotNull
  private static List<SwitchStatementBranch> extractBranches(PsiCodeBlock body,
                                                             Set<PsiSwitchLabelStatementBase> fallThroughTargets) {
    final List<SwitchStatementBranch> openBranches = new ArrayList<>();
    final Set<PsiElement> declaredElements = new HashSet<>();
    final List<SwitchStatementBranch> allBranches = new ArrayList<>();
    SwitchStatementBranch currentBranch = null;
    final PsiElement[] children = body.getChildren();
    List<PsiSwitchLabelStatementBase> labels = PsiTreeUtil.getChildrenOfTypeAsList(body, PsiSwitchLabelStatementBase.class);
    boolean defaultAlwaysExecuted = !labels.isEmpty() &&
                                    SwitchUtils.isDefaultLabel(ContainerUtil.getLastItem(labels)) &&
                                    fallThroughTargets.containsAll(labels.subList(1, labels.size()));
    for (int i = 1; i < children.length - 1; i++) {
      final PsiElement statement = children[i];
      if (statement instanceof PsiSwitchLabelStatement) {
        final PsiSwitchLabelStatement label = (PsiSwitchLabelStatement)statement;
        if (currentBranch == null || !fallThroughTargets.contains(statement)) {
          openBranches.clear();
          currentBranch = new SwitchStatementBranch();
          currentBranch.addPendingDeclarations(declaredElements);
          allBranches.add(currentBranch);
          openBranches.add(currentBranch);
        }
        else if (currentBranch.hasStatements()) {
          currentBranch = new SwitchStatementBranch();
          allBranches.add(currentBranch);
          openBranches.add(currentBranch);
        }
        if (SwitchUtils.isDefaultLabel(label) && defaultAlwaysExecuted) {
          openBranches.retainAll(Collections.singleton(currentBranch));
        }
        currentBranch.addCaseValues(label, defaultAlwaysExecuted);
      }
      else if (statement instanceof PsiSwitchLabeledRuleStatement) {
        openBranches.clear();
        PsiSwitchLabeledRuleStatement rule = (PsiSwitchLabeledRuleStatement)statement;
        currentBranch = new SwitchStatementBranch();

        PsiStatement ruleBody = rule.getBody();
        if (ruleBody != null) {
          currentBranch.addStatement(ruleBody);
        }
        currentBranch.addCaseValues(rule, defaultAlwaysExecuted);
        openBranches.add(currentBranch);
        allBranches.add(currentBranch);
      }
      else {
        if (statement instanceof PsiStatement) {
          if (statement instanceof PsiDeclarationStatement) {
            final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement)statement;
            Collections.addAll(declaredElements, declarationStatement.getDeclaredElements());
          }
          for (SwitchStatementBranch branch : openBranches) {
            branch.addStatement((PsiStatement)statement);
          }
        }
        else {
          for (SwitchStatementBranch branch : openBranches) {
            if (statement instanceof PsiWhiteSpace) {
              branch.addWhiteSpace(statement);
            }
            else {
              branch.addComment(statement);
            }
          }
        }
      }
    }
    return allBranches;
  }

  private static Set<PsiSwitchLabelStatementBase> getFallThroughTargets(PsiCodeBlock body) {
    return StreamEx.of(body.getStatements())
      .pairMap((s1, s2) -> s2 instanceof PsiSwitchLabelStatement && !(s1 instanceof PsiSwitchLabeledRuleStatement) &&
                           ControlFlowUtils.statementMayCompleteNormally(s1) ? (PsiSwitchLabelStatement)s2 : null)
      .nonNull().collect(Collectors.toSet());
  }

  private static void dumpBranch(SwitchStatementBranch branch,
                                 String expressionText,
                                 boolean firstBranch,
                                 boolean useEquals,
                                 @NonNls StringBuilder out,
                                 CommentTracker commentTracker) {
    if (!firstBranch) {
      out.append("else ");
    }
    dumpCaseValues(expressionText, branch.getCaseElements(), useEquals, commentTracker, out);
    dumpBody(branch, out, commentTracker);
  }

  private static void dumpCaseValues(String expressionText,
                                     List<PsiElement> caseElements,
                                     boolean useEquals,
                                     CommentTracker commentTracker,
                                     @NonNls StringBuilder out) {
    out.append("if(");
    boolean firstCaseValue = true;
    for (PsiElement caseElement : caseElements) {
      if (!firstCaseValue) {
        out.append("||");
      }
      firstCaseValue = false;
      if (caseElement instanceof PsiExpression) {
        PsiExpression caseExpression = (PsiExpression)caseElement;
        String caseValue = getCaseValueText(caseExpression, commentTracker);
        if (useEquals && !ExpressionUtils.isNullLiteral(caseExpression)) {
          out.append(caseValue).append(".equals(").append(expressionText).append(')');
        }
        else if (caseValue.equals("true")) {
          out.append(expressionText);
        }
        else if (caseValue.equals("false")) {
          out.append("!(").append(expressionText).append(")");
        }
        else {
          out.append(expressionText).append("==").append(caseValue);
        }
      }
      else if (caseElement instanceof PsiPattern) {
        String patternCondition = createIfCondition((PsiPattern)caseElement, expressionText, commentTracker);
        if (patternCondition != null) {
          out.append(patternCondition);
        } else {
          //incomplete/red code
          out.append(caseElement.getText());
        }
      }
    }
    out.append(')');
  }

  private static @Nullable String createIfCondition(PsiPattern pattern, String expressionText, CommentTracker commentTracker){
    PsiPattern normalizedPattern = JavaPsiPatternUtil.skipParenthesizedPatternDown(pattern);
    if (normalizedPattern instanceof PsiTypeTestPattern) {
      return createIfCondition((PsiTypeTestPattern)normalizedPattern, expressionText, commentTracker);
    }
    else if (normalizedPattern instanceof PsiGuardedPattern) {
      PsiGuardedPattern guardedPattern = (PsiGuardedPattern)normalizedPattern;
      PsiPattern primaryPattern = JavaPsiPatternUtil.skipParenthesizedPatternDown(guardedPattern.getPrimaryPattern());
      if (!(primaryPattern instanceof PsiTypeTestPattern)) return null;
      String primaryCondition = createIfCondition((PsiTypeTestPattern)primaryPattern, expressionText, commentTracker);
      PsiExpression guardingExpression = guardedPattern.getGuardingExpression();
      if (guardingExpression == null) return null;
      return primaryCondition + "&&" + commentTracker.textWithComments(guardingExpression);
    }
    return null;
  }

  private static @Nullable String createIfCondition(PsiTypeTestPattern typeTestPattern, String expressionText, CommentTracker commentTracker) {
    PsiTypeElement checkType = typeTestPattern.getCheckType();
    if (checkType == null) return null;
    String typeText = commentTracker.textWithComments(checkType);
    PsiPatternVariable variable = typeTestPattern.getPatternVariable();
    if (variable == null) return null;
    PsiElement context = PsiTreeUtil.getParentOfType(variable, PsiSwitchStatement.class);
    boolean isUsedPatternVariable = context != null && VariableAccessUtils.variableIsUsed(variable, context);
    PsiIdentifier identifier = variable.getNameIdentifier();
    String variableName = isUsedPatternVariable ? commentTracker.textWithComments(identifier) : commentTracker.commentsBefore(identifier);
    return expressionText + " instanceof " + typeText + " " + variableName;
  }

  private static String getCaseValueText(PsiExpression value, CommentTracker commentTracker) {
    value = PsiUtil.skipParenthesizedExprDown(value);
    if (value == null) {
      return "";
    }
    if (!(value instanceof PsiReferenceExpression)) {
      return commentTracker.text(value);
    }
    final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)value;
    final PsiElement target = referenceExpression.resolve();

    if (!(target instanceof PsiEnumConstant)) {
      return commentTracker.text(value);
    }
    final PsiEnumConstant enumConstant = (PsiEnumConstant)target;
    final PsiClass aClass = enumConstant.getContainingClass();
    if (aClass == null) {
      return commentTracker.text(value);
    }

    String qualifiedName = ObjectUtils.notNull(aClass.getQualifiedName(), Objects.requireNonNull(aClass.getName()));
    return qualifiedName + '.' + commentTracker.text(referenceExpression);
  }

  private static void dumpBody(SwitchStatementBranch branch, @NonNls StringBuilder out, CommentTracker commentTracker) {
    final List<PsiElement> bodyStatements = branch.getBodyElements();
    out.append('{');
    if (!bodyStatements.isEmpty()) {
      PsiElement firstBodyElement = bodyStatements.get(0);
      PsiElement prev = PsiTreeUtil.skipWhitespacesAndCommentsBackward(firstBodyElement);
      if (prev instanceof PsiSwitchLabelStatementBase) {
        PsiCaseLabelElementList values = ((PsiSwitchLabelStatementBase)prev).getCaseLabelElementList();
        if (values != null) {
          out.append(CommentTracker.commentsBetween(values, firstBodyElement));
        }
      }
    }
    for (PsiElement element : branch.getPendingDeclarations()) {
      if (ReferencesSearch.search(element, new LocalSearchScope(bodyStatements.toArray(PsiElement.EMPTY_ARRAY))).findFirst() != null) {
        if (element instanceof PsiVariable) {
          PsiVariable var = (PsiVariable)element;
          out.append(var.getType().getCanonicalText()).append(' ').append(var.getName()).append(';');
        } else {
          // Class
          out.append(element.getText());
        }
      }
    }

    for (PsiElement bodyStatement : bodyStatements) {
      if (bodyStatement instanceof PsiBlockStatement) {
        final PsiBlockStatement blockStatement = (PsiBlockStatement)bodyStatement;
        final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
        PsiElement start = PsiTreeUtil.skipWhitespacesForward(codeBlock.getFirstBodyElement());
        PsiElement end = PsiTreeUtil.skipWhitespacesBackward(codeBlock.getLastBodyElement());
        if (start != null && end != null && start != codeBlock.getRBrace()) {
          for (PsiElement child = start; child != null; child = child.getNextSibling()) {
            out.append(commentTracker.text(child));
            if (child == end) break;
          }
        }
      }
      else {
        out.append(commentTracker.text(bodyStatement));
      }
    }
    out.append("\n").append("}");
  }
}


text:
<?php

/** PHPExcel root directory */
if (!defined('PHPEXCEL_ROOT')) {
	/**
	 * @ignore
	 */
	define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
	require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
}

/**
 *	PHPExcel_Reader_OOCalc
 *
 *	@category	PHPExcel
 *	@package	PHPExcel_Reader
 *	@copyright	Copyright (c) 2006 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel)
 */
class PHPExcel_Reader_OOCalc implements PHPExcel_Reader_IReader
{
	/**
	 *	Read data only?
	 *	Identifies whether the Reader should only read data values for cells, and ignore any formatting information;
	 *		or whether it should read both data and formatting
	 *
	 *	@var	boolean
	 */
	private $_readDataOnly = false;

	/**
	 *	Restrict which sheets should be loaded?
	 *	This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded.
	 *
	 *	@var	array of string
	 */
	private $_loadSheetsOnly = null;

	/**
	 * Formats
	 *
	 * @var array
	 */
	private $_styles = array();

	/**
	 * PHPExcel_Reader_IReadFilter instance
	 *
	 * @var PHPExcel_Reader_IReadFilter
	 */
	private $_readFilter = null;

	/**
	 *	Read data only?
	 *		If this is true, then the Reader will only read data values for cells, it will not read any formatting information.
	 *		If false (the default) it will read data and formatting.
	 *
	 *	@return	boolean
	 */
	public function getReadDataOnly() {
		return $this->_readDataOnly;
	}

	/**
	 *	Set read data only
	 *		Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.
	 *		Set to false (the default) to advise the Reader to read both data and formatting for cells.
	 *
	 *	@param	boolean	$pValue
	 *
	 *	@return	PHPExcel_Reader_OOCalc
	 */
	public function setReadDataOnly($pValue = false) {
		$this->_readDataOnly = $pValue;
		return $this;
	}

	/**
	 *	Get which sheets to load
	 *		Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null
	 *			indicating that all worksheets in the workbook should be loaded.
	 *
	 *	@return mixed
	 */
	public function getLoadSheetsOnly()
	{
		return $this->_loadSheetsOnly;
	}

	/**
	 *	Set which sheets to load
	 *
	 *	@param mixed $value
	 *		This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name.
	 *		If NULL, then it tells the Reader to read all worksheets in the workbook
	 *
	 *	@return PHPExcel_Reader_OOCalc
	 */
	public function setLoadSheetsOnly($value = null)
	{
		$this->_loadSheetsOnly = is_array($value) ?
			$value : array($value);
		return $this;
	}

	/**
	 *	Set all sheets to load
	 *		Tells the Reader to load all worksheets from the workbook.
	 *
	 *	@return PHPExcel_Reader_OOCalc
	 */
	public function setLoadAllSheets()
	{
		$this->_loadSheetsOnly = null;
		return $this;
	}

	/**
	 * Read filter
	 *
	 * @return PHPExcel_Reader_IReadFilter
	 */
	public function getReadFilter() {
		return $this->_readFilter;
	}

	/**
	 * Set read filter
	 *
	 * @param PHPExcel_Reader_IReadFilter $pValue
	 * @return PHPExcel_Reader_OOCalc
	 */
	public function setReadFilter(PHPExcel_Reader_IReadFilter $pValue) {
		$this->_readFilter = $pValue;
		return $this;
	}

	/**
	 * Create a new PHPExcel_Reader_OOCalc
	 */
	public function __construct() {
		$this->_readFilter 	= new PHPExcel_Reader_DefaultReadFilter();
	}

	/**
	 * Can the current PHPExcel_Reader_IReader read the file?
	 *
	 * @param 	string 		$pFileName
	 * @return 	boolean
	 */
	public function canRead($pFilename)
	{
		// Check if zip class exists
		if (!class_exists('ZipArchive')) {
			return false;
		}

		// Check if file exists
		if (!file_exists($pFilename)) {
			throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
		}

		// Load file
		$zip = new ZipArchive;
		if ($zip->open($pFilename) === true) {
			// check if it is an OOXML archive
			$mimeType = $zip->getFromName("mimetype");

			$zip->close();

			return ($mimeType === 'application/vnd.oasis.opendocument.spreadsheet');
		}

		return false;
	}

	/**
	 * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object
	 *
	 * @param 	string 		$pFilename
	 * @throws 	Exception
	 */
	public function listWorksheetNames($pFilename)
	{
		// Check if file exists
		if (!file_exists($pFilename)) {
			throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
		}

		$worksheetNames = array();

		$zip = new ZipArchive;
		if ($zip->open($pFilename) === true) {

			$xml = simplexml_load_string($zip->getFromName("content.xml"));
			$namespacesContent = $xml->getNamespaces(true);

			$workbook = $xml->children($namespacesContent['office']);
			foreach($workbook->body->spreadsheet as $workbookData) {
				$workbookData = $workbookData->children($namespacesContent['table']);
				foreach($workbookData->table as $worksheetDataSet) {
					$worksheetDataAttributes = $worksheetDataSet->attributes($namespacesContent['table']);

					$worksheetNames[] = $worksheetDataAttributes['name'];
				}
			}
		}

		return $worksheetNames;
	}

	/**
	 * Loads PHPExcel from file
	 *
	 * @param 	string 		$pFilename
	 * @return 	PHPExcel
	 * @throws 	Exception
	 */
	public function load($pFilename)
	{
		// Create new PHPExcel
		$objPHPExcel = new PHPExcel();

		// Load into this instance
		return $this->loadIntoExisting($pFilename, $objPHPExcel);
	}

	private static function identifyFixedStyleValue($styleList,&$styleAttributeValue) {
		$styleAttributeValue = strtolower($styleAttributeValue);
		foreach($styleList as $style) {
			if ($styleAttributeValue == strtolower($style)) {
				$styleAttributeValue = $style;
				return true;
			}
		}
		return false;
	}

	/**
	 * Loads PHPExcel from file into PHPExcel instance
	 *
	 * @param 	string 		$pFilename
	 * @param	PHPExcel	$objPHPExcel
	 * @return 	PHPExcel
	 * @throws 	Exception
	 */
	public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
	{
		// Check if file exists
		if (!file_exists($pFilename)) {
			throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
		}

		$timezoneObj = new DateTimeZone('Europe/London');
		$GMT = new DateTimeZone('UTC');

		$zip = new ZipArchive;
		if ($zip->open($pFilename) === true) {
//			echo '
Meta Information
';
			$xml = simplexml_load_string($zip->getFromName("meta.xml"));
			$namespacesMeta = $xml->getNamespaces(true);
//			echo '
';
//			print_r($namespacesMeta);
//			echo '

';

			$docProps = $objPHPExcel->getProperties();
			$officeProperty = $xml->children($namespacesMeta['office']);
			foreach($officeProperty as $officePropertyData) {
				$officePropertyDC = array();
				if (isset($namespacesMeta['dc'])) {
					$officePropertyDC = $officePropertyData->children($namespacesMeta['dc']);
				}
				foreach($officePropertyDC as $propertyName => $propertyValue) {
					switch ($propertyName) {
						case 'title' :
								$docProps->setTitle($propertyValue);
								break;
						case 'subject' :
								$docProps->setSubject($propertyValue);
								break;
						case 'creator' :
								$docProps->setCreator($propertyValue);
								$docProps->setLastModifiedBy($propertyValue);
								break;
						case 'date' :
								$creationDate = strtotime($propertyValue);
								$docProps->setCreated($creationDate);
								$docProps->setModified($creationDate);
								break;
						case 'description' :
								$docProps->setDescription($propertyValue);
								break;
					}
				}
				$officePropertyMeta = array();
				if (isset($namespacesMeta['dc'])) {
					$officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
				}
				foreach($officePropertyMeta as $propertyName => $propertyValue) {
					$propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta']);
					switch ($propertyName) {
						case 'initial-creator' :
								$docProps->setCreator($propertyValue);
								break;
						case 'keyword' :
								$docProps->setKeywords($propertyValue);
								break;
						case 'creation-date' :
								$creationDate = strtotime($propertyValue);
								$docProps->setCreated($creationDate);
								break;
						case 'user-defined' :
								$propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING;
								foreach ($propertyValueAttributes as $key => $value) {
									if ($key == 'name') {
										$propertyValueName = (string) $value;
									} elseif($key == 'value-type') {
										switch ($value) {
											case 'date'	:
												$propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue,'date');
												$propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_DATE;
												break;
											case 'boolean'	:
												$propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue,'bool');
												$propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_BOOLEAN;
												break;
											case 'float'	:
												$propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue,'r4');
												$propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_FLOAT;
												break;
											default :
												$propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING;
										}
									}
								}
								$docProps->setCustomProperty($propertyValueName,$propertyValue,$propertyValueType);
								break;
					}
				}
			}

//			echo '
Workbook Content
';
			$xml = simplexml_load_string($zip->getFromName("content.xml"));
			$namespacesContent = $xml->getNamespaces(true);
//			echo '
';
//			print_r($namespacesContent);
//			echo '

';

			$workbook = $xml->children($namespacesContent['office']);
			foreach($workbook->body->spreadsheet as $workbookData) {
				$workbookData = $workbookData->children($namespacesContent['table']);
				$worksheetID = 0;
				foreach($workbookData->table as $worksheetDataSet) {
					$worksheetData = $worksheetDataSet->children($namespacesContent['table']);
//					print_r($worksheetData);
//					echo '
';
					$worksheetDataAttributes = $worksheetDataSet->attributes($namespacesContent['table']);
//					print_r($worksheetDataAttributes);
//					echo '
';
					if ((isset($this->_loadSheetsOnly)) && (isset($worksheetDataAttributes['name'])) &&
						(!in_array($worksheetDataAttributes['name'], $this->_loadSheetsOnly))) {
						continue;
					}

//					echo '
Worksheet '.$worksheetDataAttributes['name'].'
';
					// Create new Worksheet
					$objPHPExcel->createSheet();
					$objPHPExcel->setActiveSheetIndex($worksheetID);
					if (isset($worksheetDataAttributes['name'])) {
						$worksheetName = (string) $worksheetDataAttributes['name'];
						$objPHPExcel->getActiveSheet()->setTitle($worksheetName);
					}

					$rowID = 1;
					foreach($worksheetData as $key => $rowData) {
//						echo ''.$key.'
';
						switch ($key) {
							case 'table-header-rows':
								foreach ($rowData as $key=>$cellData) {
									$rowData = $cellData;
									break;
								}
							case 'table-row' :
								$columnID = 'A';
								foreach($rowData as $key => $cellData) {
									if (!is_null($this->getReadFilter())) {
										if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) {
											continue;
										}
									}

//									echo ''.$columnID.$rowID.'
';
									$cellDataText = $cellData->children($namespacesContent['text']);
									$cellDataOffice = $cellData->children($namespacesContent['office']);
									$cellDataOfficeAttributes = $cellData->attributes($namespacesContent['office']);
									$cellDataTableAttributes = $cellData->attributes($namespacesContent['table']);

//									echo 'Office Attributes: ';
//									print_r($cellDataOfficeAttributes);
//									echo '
Table Attributes: ';
//									print_r($cellDataTableAttributes);
//									echo '
Cell Data Text';
//									print_r($cellDataText);
//									echo '
';
//
									$type = $formatting = $hyperlink = null;
									$hasCalculatedValue = false;
									$cellDataFormula = '';
									if (isset($cellDataTableAttributes['formula'])) {
										$cellDataFormula = $cellDataTableAttributes['formula'];
										$hasCalculatedValue = true;
									}

									if (isset($cellDataOffice->annotation)) {
//										echo 'Cell has comment
';
										$annotationText = $cellDataOffice->annotation->children($namespacesContent['text']);
										$textArray = array();
										foreach($annotationText as $t) {
											foreach($t->span as $text) {
												$textArray[] = (string)$text;
											}
										}
										$text = implode("\n",$textArray);
//										echo $text,'
';
										$objPHPExcel->getActiveSheet()->getComment( $columnID.$rowID )
//																		->setAuthor( $author )
																		->setText($this->_parseRichText($text) );
									}

									if (isset($cellDataText->p)) {
//										echo 'Value Type is '.$cellDataOfficeAttributes['value-type'].'
';
										switch ($cellDataOfficeAttributes['value-type']) {
											case 'string' :
													$type = PHPExcel_Cell_DataType::TYPE_STRING;
													$dataValue = $cellDataText->p;
													if (isset($dataValue->a)) {
														$dataValue = $dataValue->a;
														$cellXLinkAttributes = $dataValue->attributes($namespacesContent['xlink']);
														$hyperlink = $cellXLinkAttributes['href'];
													}
													break;
											case 'boolean' :
													$type = PHPExcel_Cell_DataType::TYPE_BOOL;
													$dataValue = ($cellDataText->p == 'TRUE') ? True : False;
													break;
											case 'float' :
													$type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
													$dataValue = (float) $cellDataOfficeAttributes['value'];
													if (floor($dataValue) == $dataValue) {
														$dataValue = (integer) $dataValue;
													}
													break;
											case 'date' :
													$type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
												    $dateObj = new DateTime($cellDataOfficeAttributes['date-value'], $GMT);
													$dateObj->setTimeZone($timezoneObj);
													list($year,$month,$day,$hour,$minute,$second) = explode(' ',$dateObj->format('Y m d H i s'));
													$dataValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year,$month,$day,$hour,$minute,$second);
													if ($dataValue != floor($dataValue)) {
														$formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15.' '.PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4;
													} else {
														$formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15;
													}
													break;
											case 'time' :
													$type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
													$dataValue = PHPExcel_Shared_Date::PHPToExcel(strtotime('01-01-1970 '.implode(':',sscanf($cellDataOfficeAttributes['time-value'],'PT%dH%dM%dS'))));
													$formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4;
													break;
										}
//										echo 'Data value is '.$dataValue.'
';
//										if (!is_null($hyperlink)) {
//											echo 'Hyperlink is '.$hyperlink.'
';
//										}
									}

									if ($hasCalculatedValue) {
										$type = PHPExcel_Cell_DataType::TYPE_FORMULA;
//										echo 'Formula: '.$cellDataFormula.'
';
										$cellDataFormula = substr($cellDataFormula,strpos($cellDataFormula,':=')+1);
										$temp = explode('"',$cellDataFormula);
										$tKey = false;
										foreach($temp as &$value) {
											//	Only replace in alternate array entries (i.e. non-quoted blocks)
											if ($tKey = !$tKey) {
												$value = preg_replace('/\[\.(.*):\.(.*)\]/Ui','$1:$2',$value);
												$value = preg_replace('/\[\.(.*)\]/Ui','$1',$value);
												$value = PHPExcel_Calculation::_translateSeparator(';',',',$value,$inBraces);
											}
										}
										unset($value);
										//	Then rebuild the formula string
										$cellDataFormula = implode('"',$temp);
//										echo 'Adjusted Formula: '.$cellDataFormula.'
';
									}

									if (!is_null($type)) {
										$objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $dataValue),$type);
										if ($hasCalculatedValue) {
//											echo 'Forumla result is '.$dataValue.'
';
											$objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setCalculatedValue($dataValue);
										}
										if (($cellDataOfficeAttributes['value-type'] == 'date') ||
											($cellDataOfficeAttributes['value-type'] == 'time')) {
											$objPHPExcel->getActiveSheet()->getStyle($columnID.$rowID)->getNumberFormat()->setFormatCode($formatting);
										}
										if (!is_null($hyperlink)) {
											$objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->getHyperlink()->setUrl($hyperlink);
										}
									}

									//	Merged cells
									if ((isset($cellDataTableAttributes['number-columns-spanned'])) || (isset($cellDataTableAttributes['number-rows-spanned']))) {
										$columnTo = $columnID;
										if (isset($cellDataTableAttributes['number-columns-spanned'])) {
											$columnTo = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($columnID) + $cellDataTableAttributes['number-columns-spanned'] -2);
										}
										$rowTo = $rowID;
										if (isset($cellDataTableAttributes['number-rows-spanned'])) {
											$rowTo = $rowTo + $cellDataTableAttributes['number-rows-spanned'] - 1;
										}
										$cellRange = $columnID.$rowID.':'.$columnTo.$rowTo;
										$objPHPExcel->getActiveSheet()->mergeCells($cellRange);
									}

									if (isset($cellDataTableAttributes['number-columns-repeated'])) {
//										echo 'Repeated '.$cellDataTableAttributes['number-columns-repeated'].' times
';
										$columnID = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($columnID) + $cellDataTableAttributes['number-columns-repeated'] - 2);
									}
									++$columnID;
								}
								++$rowID;
								break;
						}
					}
					++$worksheetID;
				}
			}

		}

		// Return
		return $objPHPExcel;
	}

	private function _parseRichText($is = '') {
		$value = new PHPExcel_RichText();

		$value->createText($is);

		return $value;
	}

}


text:
// @flow
/* global SETTINGS:false */
import React from "react"
import { connect } from "react-redux"
import R from "ramda"
import { Link } from "react-router-dom"
import qs from "query-string"

import { MetaTags, Card } from "ol-util"
import ExternalLogins from "../../components/ExternalLogins"
import AuthEmailForm from "../../components/auth/AuthEmailForm"
import withForm from "../../hoc/withForm"

import { actions } from "../../actions"
import { setBannerMessage } from "../../actions/ui"
import {
  FLOW_REGISTER,
  STATE_REGISTER_CONFIRM_SENT,
  getFormErrorSelector
} from "../../reducers/auth"
import { processAuthResponse } from "../../lib/auth"
import { configureForm } from "../../lib/forms"
import { formatTitle } from "../../lib/title"
import { LOGIN_URL, getNextParam } from "../../lib/url"
import { validateNewEmailForm as validateForm } from "../../lib/validation"
import { mergeAndInjectProps } from "../../lib/redux_props"

import type { Match } from "react-router"
import type { EmailForm, AuthResponse } from "../../flow/authTypes"
import type { FormErrors, WithFormProps } from "../../flow/formTypes"

type RegisterPageProps = {
  match: Match,
  history: Object,
  formError: ?string,
  next: string
} & WithFormProps<EmailForm>

export const RegisterPage = ({
  renderForm,
  formError,
  match,
  next
}: RegisterPageProps) => (

      <Card className="register-card">

Join MIT OPEN for free

        <MetaTags canonicalLink={match?.url}>
          <title>{formatTitle("Register")}</title>
        </MetaTags>
        {renderForm({ formError, submitLabel: "Sign Up" })}
        <ExternalLogins next={next} />

          Already have an account?{" "}
          <Link to={`${LOGIN_URL}?${qs.stringify({ next })}`}>Log in</Link>

      </Card>

)

const newEmailForm = () => ({ email: "" })

export const FORM_KEY = "register:email"
const { getForm, actionCreators } = configureForm(FORM_KEY, newEmailForm)

const onSubmit = (form: EmailForm, next: string) =>
  actions.auth.registerEmail(FLOW_REGISTER, form.email, next, form.recaptcha)

const onSubmitFailure = (): FormErrors<*> => ({
  recaptcha: `Error validating your submission.`
})

const mergeProps = mergeAndInjectProps(
  (stateProps, { setBannerMessage, onSubmit }, { history, location }) => {
    const next = getNextParam(location.search)
    return {
      // Used by withForm()
      useRecaptcha:   true,
      onSubmit:       form => onSubmit(form, next),
      onSubmitResult: (response: AuthResponse) => {
        processAuthResponse(history, response)
        if (response.state === STATE_REGISTER_CONFIRM_SENT && response.email) {
          setBannerMessage(
            `We sent an email to <${response.email}>, please validate your address to continue.`
          )
        }
      },
      next
    }
  }
)

const mapStateToProps = state => {
  const form = getForm(state)
  const formError = getFormErrorSelector(state)

  return {
    form,
    validateForm,
    formError,
    onSubmitFailure
  }
}

export default R.compose(
  connect(
    mapStateToProps,
    {
      setBannerMessage,
      onSubmit,
      ...actionCreators
    },
    mergeProps
  ),
  withForm(AuthEmailForm)
)(RegisterPage)


text:
"""Created on Tue Apr  4 16:09:06 2017

@author: gsutanto
"""

import numpy as np
import tensorflow as tf

class NeuralNetwork:
  'Common base class for a variety of neural network topologies.'

  def __init__(self, name):
    self.name = name


text:
package org.cipango.kaleo.xcap;

import java.util.Map;

import org.cipango.kaleo.xcap.util.XcapUtil;
import org.iso_relax.verifier.Schema;

public class XcapProcessorImpl implements XcapResourceProcessor
{
	private String _auid;
	private String _defaultNamespacePrefix;
	private String _mimeType;
	private Map<String, String> _namespaceContext;
	private Schema _xsdSchema;
	private String _name;

	public boolean validateResource(XcapResource resource) throws XcapException
	{
		return true;
	}

	public String getAuid()
	{
		return _auid;
	}

	public void setAuid(String auid)
	{
		_auid = auid;
	}

	public String getDefaultNamespacePrefix()
	{
		return _defaultNamespacePrefix;
	}

	public void setDefaultNamespacePrefix(String defaultNamespacePrefix)
	{
		_defaultNamespacePrefix = defaultNamespacePrefix;
	}

	public String getMimeType()
	{
		return _mimeType;
	}

	public void setMimeType(String mimeType)
	{
		_mimeType = mimeType;
	}

	public Map<String, String> getNamespaceContext()
	{
		return _namespaceContext;
	}

	public void setNamespaceContext(Map<String, String> namespaceContext)
	{
		_namespaceContext = namespaceContext;
	}

	public Schema getXsdSchema()
	{
		return _xsdSchema;
	}

	public void setXsdSchemaPath(String path)
	{
		_xsdSchema = XcapUtil.getSchema(path);
	}

	public void setXsdSchema(Schema xsdSchema)
	{
		_xsdSchema = xsdSchema;
	}

	public void processResource(XcapResource resource)
	{

	}

	public String getName()
	{
		return _name;
	}

	public void setName(String name)
	{
		_name = name;
	}

	public String toString()
	{
		if (_name != null)
			return _name;
		return _auid;
	}

}


text:
package com.gildedgames.fuzzyjava.api.evaluation;

public interface IProperty<E>
{
	float getMinBound();

	float getMaxBound();

	float convert(Object... params);

	boolean propertySet(Object... params);

	void setProperty(float value, Object... params);

	Object[] tryInferMissing(Object[] params);

	String getName();

	int arity();
}


text:
const config = {
  transform: {
    '^.+\\.ts$': 'ts-jest',
  },
  testEnvironment: 'node',
  testMatch: ['**/test.ts'],
  moduleFileExtensions: ['js', 'ts'],
};

module.exports = config;


text:
import json

class Model:

    def __init__(self, client, data):
        self._client = client
        self._data = data

        for k, v in data.items():
            self.__dict__[k] = self._instantiate_field(k, v)

    def _instantiate_field(self, key, value):
        return value

    def __str__(self):
        t = type(self)
        json_str = json.dumps(self._data, indent=4, sort_keys=True)
        return '<%s.%s> %s' % (t.__module__, t.__name__, json_str)

    def _update_attributes(self, new_object):
        data = new_object._data
        self._data = data
        for k, v in data.items():
            self.__dict__[k] = self._instantiate_field(k, v)


text:
![synx logo](https://raw.githubusercontent.com/venmo/synx/marklarr/dev/docs/images/synx-logo.png?token=760261__eyJzY29wZSI6IlJhd0Jsb2I6dmVubW8vc3lueC9tYXJrbGFyci9kZXYvZG9jcy9pbWFnZXMvc3lueC1sb2dvLnBuZyIsImV4cGlyZXMiOjE0MDE5MzExNDF9--6c8a22318eaafed2185cb16d39189dcadb75c742)

[![Gem Version](https://badge.fury.io/rb/synx.svg)](http://badge.fury.io/rb/synx)
 [![Build Status](https://travis-ci.org/venmo/synx.svg?branch=master)](https://travis-ci.org/venmo/synx)

A command-line tool that reorganizes your Xcode project folder to match your Xcode groups.

![synx gif](https://raw.githubusercontent.com/venmo/synx/marklarr/dev/docs/images/synx.gif?token=760261__eyJzY29wZSI6IlJhd0Jsb2I6dmVubW8vc3lueC9tYXJrbGFyci9kZXYvZG9jcy9pbWFnZXMvc3lueC5naWYiLCJleHBpcmVzIjoxNDAxODU2NzAyfQ%3D%3D--fc7d8546f3d4860df9024b1ee82ea13b86a2da88)

##### Xcode

![synx Xcode](https://raw.githubusercontent.com/venmo/synx/marklarr/dev/docs/images/synx-Xcode.jpg?token=760261__eyJzY29wZSI6IlJhd0Jsb2I6dmVubW8vc3lueC9tYXJrbGFyci9kZXYvZG9jcy9pbWFnZXMvc3lueC1YY29kZS5qcGciLCJleHBpcmVzIjoxNDAxOTMxMDY5fQ%3D%3D--969e312f6ee33430855c495f25d9f5ff78fa9e96)

##### Finder

![synx finder before/after](https://raw.githubusercontent.com/venmo/synx/marklarr/dev/docs/images/synx-finder-before-after.png?token=760261__eyJzY29wZSI6IlJhd0Jsb2I6dmVubW8vc3lueC9tYXJrbGFyci9kZXYvZG9jcy9pbWFnZXMvc3lueC1maW5kZXItYmVmb3JlLWFmdGVyLnBuZyIsImV4cGlyZXMiOjE0MDE5MzEwOTd9--8cff7616e4af2f6f2eed624623092745184c0235)

## Installation

    $ gem install synx

## Usage

### Basic
:warning: **WARNING: Make sure that your project is backed up through source control before doing anything** :warning:

Execute the command on your project to have it reorganize the files on the file system:

     $ synx path/to/my/project.xcodeproj

It may have confused CocoaPods. If you use them, execute this command:

    $ pod install

You're good to go!

### Advanced

Synx supports the following options:

```
  --prune, -p                   remove source files and image resources that are not referenced by the the Xcode project
  --no-color                    removes all color from the output
  --no-default-exclusions       doesn't use the default exclusions of /Libraries, /Frameworks, and /Products
  --no-sort-by-name             disable sorting groups by name
  --quiet, -q                   silence all output
  --exclusion, -e EXCLUSION     ignore an Xcode group while syncing
```

For example, OCMock could have been organized using this command:

    $ synx -p -e "/OCMock/Core Mocks" -e /OCMockTests Source/OCMock.xcodeproj/

if they had wanted not to sync the `/OCMock/Core Mocks` and `/OCMockTests` groups, and also remove (`-p`) any image/source files found by synx that weren't referenced by any groups in Xcode.

## Contributing

We'd love to see your ideas for improving this library! The best way to contribute is by submitting a pull request. We'll do our best to respond to your patch as soon as possible. You can also submit a [new Github issue](https://github.com/venmo/synx/issues/new) if you find bugs or have questions. :octocat:

Please make sure to follow our general coding style and add test coverage for new features!

## Contributors

* [@vrjbndr](https://github.com/vrjbndr), awesome logo!
* [@ayanonagon](https://github.com/ayanonagon) and [@benzguo](https://github.com/benzguo), feedback.


text:
package com.stripe.model;

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

import com.stripe.BaseStripeTest;
import com.stripe.net.ApiResource;
import org.junit.jupiter.api.Test;

public class PersonTest extends BaseStripeTest {
  @Test
  public void testDeserialize() throws Exception {
    final String data = getFixture("/v1/accounts/acct_123/persons/person_123");
    final Person resource = ApiResource.GSON.fromJson(data, Person.class);
    assertNotNull(resource);
    assertNotNull(resource.getId());
  }

  @Test
  public void testDeserializeWithExpansions() throws Exception {
    final String[] expansions = {
      "verification.document.back", "verification.document.front",
    };
    final String data = getFixture("/v1/accounts/acct_123/persons/person_123", expansions);
    final Person resource = ApiResource.GSON.fromJson(data, Person.class);
    assertNotNull(resource);
    assertNotNull(resource.getId());
    assertNotNull(resource.getVerification());

    final Person.Verification.Document verifDoc = resource.getVerification().getDocument();
    assertNotNull(verifDoc);

    final File back = verifDoc.getBackObject();
    assertNotNull(back);
    assertNotNull(back.getId());
    assertEquals(verifDoc.getBack(), back.getId());

    final File front = verifDoc.getFrontObject();
    assertNotNull(front);
    assertNotNull(front.getId());
    assertEquals(verifDoc.getFront(), front.getId());
  }
}


text:
"""
Setup script for PyPi
"""

from distutils.core import setup
setup(
    name='scrapy-mongodb',
    version='0.7.2',
    license='Apache License, Version 2.0',
    description='Pipeline to MongoDB for Scrapy. Supports MongoDB replica sets',
    author='Sebastian Dahlgren',
    author_email='sebastian.dahlgren@gmail.com',
    url='http://sebdah.github.com/scrapy-mongodb/',
    keywords="scrapy mongodb",
    py_modules=['scrapy_mongodb'],
    platforms=['Any'],
    install_requires=[
        'pymongo >= 2.4.1'
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
        'Programming Language :: Python'
    ]
)


text:
<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>./latest.log</file>
        <encoder>
            <pattern>[%d{yyyy.MM.dd HH:mm}] [%level] [%logger{0}] [%t] %msg%n</pattern>
        </encoder>
    </appender>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="stream.flarebot.flarebot.util.errorhandling.Filter" />
        <filter class="stream.flarebot.flarebot.util.errorhandling.ErrorCatcher" />
        <encoder>
            <pattern>[%d{yyyy.MM.dd HH:mm:ss}] [%level] [%logger{0}] [%t] %msg%n</pattern>
        </encoder>
    </appender>
    <appender name="Sentry" class="io.sentry.logback.SentryAppender">
        <filter class="stream.flarebot.flarebot.util.errorhandling.Filter" />
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
    </appender>
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
        <appender-ref ref="Sentry"/>
    </root>
    <logger name="org.apache" level="NONE" />
    <logger name="com.sedmelluq.*" level="INFO" />
    <logger name="httpclient" level="NONE" />
    <logger name="stream.flarebot.flarebot.FlareBot" level="INFO" />
    <logger name="Redis-*" level="NONE" />
</configuration>


text:
package com.hisunpay.redis;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import junit.framework.TestCase;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

public class RedisSentinalTester extends TestCase {

	public void test() {
		Set sentinels = new HashSet();
		sentinels.add(new HostAndPort("10.9.10.117", 16379).toString());
//		sentinels.add(new HostAndPort("192.168.77.135", 26380).toString());
//		sentinels.add(new HostAndPort("192.168.77.135", 26381).toString());

		GenericObjectPoolConfig config = new GenericObjectPoolConfig();
		config.setBlockWhenExhausted(true);
		config.setMaxIdle(20);
		config.setMaxTotal(50);
		config.setMaxWaitMillis(10000);

		JedisSentinelPool sentinelPool = new JedisSentinelPool("AM117", sentinels, config);
		System.out.println("Current master: " + sentinelPool.getCurrentHostMaster().toString());

		Jedis master = sentinelPool.getResource();
		master.set("username", "tangdingzhi");
		master.close();

		Jedis master2 = sentinelPool.getResource();
		String value = master2.get("username");
		System.out.println("username: " + value);
		master2.close();
		sentinelPool.destroy();
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<spring:beans xmlns:spring="http://www.springframework.org/schema/beans" xmlns="http://www.kuali.org/krad/schema"
              xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                                  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
                                  http://www.kuali.org/krad/schema http://www.kuali.org/krad/schema.xsd">

  <mockView id="LabsSchema" headerText="Labs Schema" singlePageView="true">
    <help externalHelpUrl="http://www.kuali.org/"/>
    <page headerText="Page Header">
      <items>
        <verticalSection headerText="Section Header">
          <templateOptions merge="true">
            <entry key="foo" value="soo"/>
            <entry key="to" value="no"/>
          </templateOptions>
        </verticalSection>
        <inc compId="LabsSchema-Section2"/>
        <content>

foo is your time!

        </content>
        <inc compId="LabsSchema-Content"/>
        <inc compId="LabsSchema-Section3"/>
        <inc compId="LabsSchema-Section4"/>
      </items>

        <items>
          <button parent="Uif-SaveAction"/>
        </items>

    </page>
    <property name="header.rightGroup">
      <horizontalGroup style="background-color: lightBlue; padding: 5px;">
        <items>
          <message messageText="RightGroup Content"/>
        </items>
      </horizontalGroup>
    </property>
  </mockView>

  <verticalSection id="LabsSchema-Section2" headerText="Section Header 2">
    <preContent>

Pre Wrapper

    </preContent>
    <postContent>

Post Wrapper

    </postContent>
    <items>
      <input propertyName="field1" label="Field 1"/>
      <input propertyName="field2" label="Field 2" conditionalRefresh="@{#fp.field1 eq 'refresh'}">
        <mediumTextAreaControl/>
      </input>
      <input propertyName="field3" label="Field 3">
        <control>
          <inc compId="LabsSchema-Text"/>
        </control>
      </input>
      <data propertyName="field4" label="Field 4"/>
      <data propertyName="field5" label="Field 5"/>
      <input propertyName="field6" label="Field 6">
        <checkboxControl/>
      </input>
      <input propertyName="field7" label="Field 7">
        <verticalCheckboxesControl>
          <options>
            <keyValuePair key="Opt 1" value="Opt 1"/>
            <keyValuePair key="Opt 2" value="Opt 2"/>
            <keyValuePair key="Opt 3" value="Opt 3"/>
            <keyValuePair key="Opt 4" value="Opt 4"/>
          </options>
        </verticalCheckboxesControl>
      </input>
      <input propertyName="field8" label="Field 8">
        <dateControl/>
      </input>
      <input propertyName="field9" label="Field 9">
        <verticalCheckboxesControl/>
        <optionsFinder>
          <bean class="org.kuali.rice.krad.demo.uif.options.SimpleTestKeyValues"/>
        </optionsFinder>
      </input>
    </items>

      <items>
        <secondaryButton actionLabel="calculate"/>
      </items>

  </verticalSection>

  <verticalSection id="LabsSchema-Section4" parent="LabsSchema-Section2" headerText="Section Header 4">
    <items merge="true">
      <data propertyName="fieldl0" label="Field 10"/>
    </items>
  </verticalSection>

  <content id="LabsSchema-Content">

Another foo!

  </content>

  <tableSection id="LabsSchema-Section3" headerText="Section Header 3" propertyName="collection1">
    <items>
      <input propertyName="field1" label="Field 1"/>
      <input propertyName="field2" label="Field 2"/>
      <input propertyName="field3" label="Field 3"/>
      <input propertyName="field4" label="Field 4"/>
    </items>
  </tableSection>

  <stackedSubCollection-withinSection id="LabsSchema-SubCollection" headerText="Sub-collection"
                                      propertyName="subcollection">
    <items>
      <input propertyName="field1" label="Sub 1"/>
      <input propertyName="field2" label="Sub 2"/>
      <input propertyName="field3" label="Sub 3"/>
      <input propertyName="field4" label="Sub 4"/>
      <input propertyName="field5" label="Sub 5"/>
    </items>
  </stackedSubCollection-withinSection>

  <textControl id="LabsSchema-Text" size="23"/>

</spring:beans>


text:
<!doctype html>

  <title>Magic Remote Auth Thing</title>

  <meta name="mobile-web-app-capable" content="yes">
  <link rel="icon" sizes="196x196" href="img/android.png">
  <link rel="apple-touch-icon" sizes="120x120" href="img/ios.png">

  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no">
  <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, user-scalable=no">

  <link rel="stylesheet" type="text/css" href="css/reset.css">
  <link rel="stylesheet" type="text/css" href="css/auth.css">

  <input id="pass" pattern="[0-9]*"  type="number" autofocus/>

 Authenticate


text:
#include "ImportFuncImpl.h"

namespace psi {

ImportFuncImpl::ImportFuncImpl(
		const std::string				&name,
		IField							*ret,
		const std::vector<IField *>		&parameters) :
				BaseItemImpl(IBaseItem::TypeImportFunc),
				NamedItemImpl(name), m_ret(ret), m_parameters(parameters) {
	m_cb = 0;

}

ImportFuncImpl::~ImportFuncImpl() {
	// TODO Auto-generated destructor stub
}

} /* namespace psi_api */