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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>The ModuleAutoloader — Zend Framework 2 2.3.0dev documentation</title>

    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="top" title="Zend Framework 2 2.3.0dev documentation" href="../index.html" />
    <link rel="next" title="The SplAutoloader Interface" href="zend.loader.spl-autoloader.html" />
    <link rel="prev" title="The ClassMapAutoloader" href="zend.loader.class-map-autoloader.html" />

Navigation

          index

          next |

          previous |

Zend Framework 2 2.3.0dev documentation »

The ModuleAutoloader¶

Overview¶

<tt class="docutils literal">Zend\Loader\ModuleAutoloader</tt> is a special implementation of the Zend\Loader\SplAutoloader interface, used by Zend\ModuleManager to
autoload <tt class="docutils literal">Module</tt> classes from different sources.

Apart from being able to autoload modules from directories, the <tt class="docutils literal">ModuleAutoloader</tt> can also autoload modules
packaged as Phar archives, which allows for packaging your modules in a single file for easier distribution.
Supported archive formats are: <tt class="docutils literal">.phar</tt>, <tt class="docutils literal">.phar.gz</tt>, <tt class="docutils literal">.phar.bz2</tt>, <tt class="docutils literal">.phar.tar</tt>, <tt class="docutils literal">.phar.tar.gz</tt>,
<tt class="docutils literal">.phar.tar.bz2</tt>, <tt class="docutils literal">.phar.zip</tt>, <tt class="docutils literal">.tar</tt>, <tt class="docutils literal">tar.gz</tt>, <tt class="docutils literal">.tar.bz2</tt> and <tt class="docutils literal">.zip</tt>. It is, however, recommended
to avoid compressing your packages (be it either gz, bz2 or zip compression), as it introduces additional
CPU overhead to every request.

Quickstart¶

As the <tt class="docutils literal">ModuleAutoloader</tt> is meant to be used with the <tt class="docutils literal">ModuleManager</tt>, for examples of it’s usage and
how to configure it, please see the Module Autoloader Usage section of the <tt class="docutils literal">ModuleManager</tt> documentation.

Configuration Options¶

The <tt class="docutils literal">ModuleAutoloader</tt> defines the following options.

ModuleAutoloader Options

$options

The <tt class="docutils literal">ModuleAutoloader</tt> expects an array of options, where each option is either a path to scan for modules,
or a key/value pair of explicit module paths. In the case of explicit module paths, the key is the module’s
name, and the value is the path to that module.

1
2
3
4
5

$options = array(
    '/path/to/modules',
    '/path/to/other/modules',
    'MyModule' => '/explicit/path/mymodule-v1.2'
);

Available Methods¶

__construct

Initialize and configure the object
<tt class="docutils literal">__construct($options = null)</tt>

Constructor
Used during instantiation of the object. Optionally, pass options, which may be either an array or
<tt class="docutils literal">Traversable</tt> object; this argument will be passed to setOptions().

setOptions

Configure the module autoloader
<tt class="docutils literal">setOptions($options)</tt>

setOptions()
Configures the state of the autoloader, registering paths to modules. Expects an array or <tt class="docutils literal">Traversable</tt>
object; the argument will be passed to registerPaths().

autoload

Attempt to load a <tt class="docutils literal">Module</tt> class.
<tt class="docutils literal">autoload($class)</tt>

autoload()
Attempts to load the specified <tt class="docutils literal">Module</tt> class. Returns a boolean <tt class="docutils literal">false</tt> on failure, or a string indicating
the class loaded on success.

register

Register with spl_autoload.
<tt class="docutils literal">register()</tt>

register()
Registers the <tt class="docutils literal">autoload()</tt> method of the current instance with <tt class="docutils literal">spl_autoload_register()</tt>.

unregister

Unregister with spl_autoload.
<tt class="docutils literal">unregister()</tt>

unregister()
Unregisters the <tt class="docutils literal">autoload()</tt> method of the current instance with <tt class="docutils literal">spl_autoload_unregister()</tt>.

registerPaths

Register multiple paths with the autoloader.
<tt class="docutils literal">registerPaths($paths)</tt>

registerPaths()
Register a paths to modules. Expects an array or <tt class="docutils literal">Traversable</tt> object. For an example array, please see the
Configuration options section.

registerPath

Register a single path with the autoloader.
<tt class="docutils literal">registerPath($path, $moduleName=false)</tt>

registerPath()
Register a single path with the autoloader. The first parameter, <tt class="docutils literal">$path</tt>, is expected to be a string. The
second parameter, <tt class="docutils literal">$moduleName</tt>, is expected to be a module name, which allows for registering an explicit
path to that module.

getPaths

Get all paths registered with the autoloader.
<tt class="docutils literal">getPaths()</tt>

getPaths()
Returns an array of all the paths registered with the current instance of the autoloader.

Examples¶

Please review the examples in the quick start for usage.

Table Of Contents

The ModuleAutoloader

Overview

Quickstart

Configuration Options

Available Methods

Examples

Previous topic

The ClassMapAutoloader

Next topic

The SplAutoloader Interface

This Page

        Show Source

Edit Source

            Note: You need to stay logged into your GitHub account to contribute to the documentation.

Quick search

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

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

Zend Framework 2 2.3.0dev documentation »

        © Copyright 2013, Zend Technologies Ltd..
      Created using Sphinx 1.2b3.

Edit this document

        The source code of this file is hosted on GitHub. Everyone can
        update and fix errors in this document with few clicks -
        no downloads needed.

            Login with your GitHub account.

            Go to

                The ModuleAutoloader
             on GitHub.

            Edit file contents using GitHub's text editor in your web browser

            Fill in the Commit message text box at the end of the page telling why
            you did the changes. Press Propose file change button next to it when done.

            On Send a pull request page you don't need to fill in text anymore. Just
            press Send pull request button.

            Your changes are now queued for review under project's Pull requests tab on GitHub.


text:
<?php
/**
 * Created by PhpStorm.
 * User: 王晶
 * Date: 2015/12/30
 * Time: 11:11
 */

namespace ZPHP\Session;
use ZPHP\Core\Config as ZConfig;
use ZPHP\Protocol\Request;
use ZPHP\Protocol\Response;

class Swoole
{

    private static $_sid = null;
    private static $_sessionType = null;
    private static $_config = null;

    public static function start($sessionType, $config)
    {
        if(null !== self::$_sid) {
            return;
        }
        //判断参数里是否有sessid
        if(empty($config)) {
            $config = ZConfig::get('session');
        }

        if(!empty($config['adapter'])) {
            $sessionType = $config['adapter'];
        }

        self::$_config = $config;
        self::$_sessionType = $sessionType;
        $request = Request::getRequest();

        $sessionName = empty($config['session_name']) ? 'ZPHPSESSID' : $config['session_name'];
        $sid = null;
        if(!empty($request->cookie[$sessionName])) {
            $sid = $request->cookie[$sessionName];
        }
        if(!$sid && !empty($request->get[$sessionName])) {
            $sid = $request->get[$sessionName];
        }
        if(!$sid && !empty($request->post[$sessionName])) {
            $sid = $request->post[$sessionName];
        }
        if($sid) {
            $handler = Factory::getInstance($sessionType, $config);
            $data = $handler->read($sid);
            if(!empty($data)) {
                $_SESSION = unserialize($data);
            } else {
                $_SESSION = array();
            }
        } else {
            $sid = sha1($request->header['user-agent'].$request->server['remote_addr'].uniqid(Request::getSocket()->worker_pid.'_', true));
            $path = empty($config['path']) ? '/' : $config['path'];
            $domain = empty($config['domain']) ? '' : $config['domain'];
            $secure = empty($config['secure']) ? false : $config['secure'];
            $httponly = !isset($config['httponly']) ? true : $config['httponly'];
            $lifetime = 0;
            if(!empty($config['cache_expire'])) {
                $lifetime = time() + $config['cache_expire'] * 60;
            }
            Response::getResponse()->cookie($sessionName, $sid, $lifetime, $path, $domain, $secure, $httponly);
            $_SESSION = array();
        }
        self::$_sid = $sid;
    }

    public static function save()
    {
        if(self::$_sid) {
            $handler = Factory::getInstance(self::$_sessionType, self::$_config);
            if (!isset($_SESSION) || empty($_SESSION)) {  //session清空
                $handler->destroy(self::$_sid);
            } else {
                $handler->write(self::$_sid, serialize($_SESSION));
                unset($_SESSION);
            }
            self::$_sid = null;
            self::$_config = null;
            self::$_sessionType = null;
        }
    }

    public static function getSid()
    {
        return self::$_sid;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!--

   Copyright 2003  The Apache Software Foundation

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

-->
<!-- ========================================================================= -->
<!-- This file contains the set of tests that should be run for basic and/or   -->
<!-- detailed tests, and that require manual interactivity. In other words,    -->
<!-- these tests require a manual operator.                                    -->
<!--                                                                           -->
<!-- @author vincent.hardy@eng.sun.com                                         -->
<!-- @version $Id$  -->
<!-- ========================================================================= -->
<testRun id="regard" name="Batik Standard Regression Test Run">
    <testReportProcessor class="org.apache.batik.test.xml.XMLTestReportProcessor" >
        <arg class="org.apache.batik.test.xml.XSLXMLReportConsumer">
            <!-- Stylesheet -->
        <arg class="java.lang.String" value="file:test-resources/org/apache/batik/test/svg/HTMLReport.xsl" />
            <!-- Ouput Directory -->
        <arg class="java.lang.String" value="html" />
            <!-- Output file name -->
        <arg class="java.lang.String" value="regardReport.html" />
        </arg>
    </testReportProcessor>

    <!-- ================================================================== -->
    <!--                     Scripting and Interactivity                    -->
    <!-- ================================================================== -->

    <testSuite href="file:test-resources/org/apache/batik/test/interactiveSamples.xml" />

</testRun>


text:
popline
============

Popline is a non-intrusive WYSIWYG editor that shows up only after selecting a piece of text on the page, inspired by popclip.

## Usage

Load jQuery and popline:

```html
<script type="text/javascript" src="../scripts/jquery.min.js"></script>
<script type="text/javascript" src="../scripts/jquery.popline.min.js"></script>
```

Or Load the popline plugins which you want:

```html
<script type="text/javascript" src="../scripts/jquery.popline.js"></script>
<script type="text/javascript" src="../scripts/plugins/jquery.popline.link.js"></script>
<script type="text/javascript" src="../scripts/plugins/jquery.popline.decoration.js"></script>
...
```

Load font-awesome and popline theme:
```html
<link rel="stylesheet" type="text/css" href="../font-awesome/css/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="../themes/default.css" />
```

Add a editable div to page:

```html
<div class='editor' contenteditable='true'></div>
```

Initialize you popline for you editor:

```js
$(".editor").popline();
```

## View Mode

Popline also support `View Mode`, you can send a twitter, a facebook message, pin an image to pinterst, search with google in `View Mode`

```js
$(".editor").popline({mode: 'view'});
```

## Popup Position

Popline can popup at top of the paragraph which you selected (like Medium) or popup on the mouse pointer position.

```js
$(".editor").popline({position: 'fixed'});
$(".editor").popline({position: 'relative'});
```

The default option is 'fixed'.

## Enable / Disable / Reorder plugins

You can enable/disable/reorder plugins when popline initialize.

```js
$(".editor").popline({enable: ["link", ["justify", ["justifyCenter", "indent"]] , "orderedList", "unOrderedList"]});
$(".editor").popline({disable: ["link", "blockquote"]});
```

## Extension

Todo

## Theme customize

#### default

![default](https://raw.github.com/kenshin54/popline/master/img/default.png "default")

#### popclip

![popclip](https://raw.github.com/kenshin54/popline/master/img/popclip.png "popclip")

Hack the theme css and create yours.

## Example

<http://kenshin54.github.io/popline/>

## Compatibility

Tested on Chrome 27.0+, Safari 6.0.4+, Firefox 21.0+, Opera 15.0+, IE 8+

## Sponsorer

A Sepcial thanks to [Artlogic](http://www.artlogic.net/)'s sponsor for IE8+ browsers compatibility support.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

License
-------

Copyright (c) 2014 kenshin54. Distributed under the MIT License. See LICENSE.txt for further details.

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/kenshin54/popline/trend.png)](https://bitdeli.com/free "Bitdeli Badge")


text:
import futureStates from './states.json!';

function routingConfig($locationProvider, $urlRouterProvider, $httpProvider, $futureStateProvider) {
    futureStates.forEach((state) => $futureStateProvider.futureState(state));
    $httpProvider.useApplyAsync(true);
    $locationProvider.html5Mode(false);
    $urlRouterProvider.otherwise('/index');
    $urlRouterProvider.when('/', '/index');
}

export default [
    '$locationProvider',
    '$urlRouterProvider',
    '$httpProvider',
    '$futureStateProvider',
    routingConfig
];


text:
package morbrian.mormessages.rest;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.PasswordAuthentication;
import java.util.List;
import java.util.Map;

public class SimpleClient {

  private final Client client;
  private final WebTarget target;
  private final String baseUrl;

  public SimpleClient(String baseUrl, PasswordAuthentication auth) {
    this.baseUrl = baseUrl;
    client = ClientBuilder.newClient().register(new PasswordAuthenticator(auth));
    target = client.target(baseUrl);
  }

  public Response get(List<Object> path, Map<String, Object> params) {
    WebTarget targetGet = applyPath(target, path);
    targetGet = applyParams(targetGet, params);
    return targetGet.request(MediaType.APPLICATION_JSON).get();
  }

  public Response post(Object data, List<Object> path, Map<String, Object> params) {
    WebTarget targetPost = applyPath(target, path);
    targetPost = applyParams(targetPost, params);
    return targetPost.request(MediaType.APPLICATION_JSON).post(Entity.json(data));
  }

  public Response put(Object data, List<Object> path, Map<String, Object> params) {
    WebTarget targetPost = applyPath(target, path);
    targetPost = applyParams(targetPost, params);
    return targetPost.request(MediaType.APPLICATION_JSON).put(Entity.json(data));
  }

  public Response delete(List<Object> path, Map<String, Object> params) {
    WebTarget targetPost = applyPath(target, path);
    targetPost = applyParams(targetPost, params);
    return targetPost.request(MediaType.APPLICATION_JSON).delete();
  }

  private WebTarget applyParams(WebTarget target, Map<String, Object> params) {
    if (params != null) {
      for (String key : params.keySet()) {
        target = target.queryParam(key, params.get(key));
      }
    }
    return target;
  }

  private WebTarget applyPath(WebTarget target, List<Object> path) {
    if (path != null) {
      for (Object p : path) {
        target = target.path(p.toString());
      }
    }
    return target;
  }
}


text:
This example shows how to write a simple Node.js program using nodejs rules from source and user managed npm dependencies.

## npm dependencies

In this example, we do the opposite of the `e2e/bazel_managed_deps`. Instead, the dependencies
are managed explicitly by the user. While we typically prefer to have Bazel manage dependencies, this
option could be useful if you vendor the dependencies into your repository, or use a custom package
manager that's not integrated with Bazel.

`index.js` is the trivial program. You can run it like:

```sh
$ bazel run :example 1
Running program
increment 1 is 2
```

`index.spec.js` is a test. Run it with:

```sh
$ bazel test :test

//:test PASSED in 0.2s

Executed 1 out of 1 test: 1 test passes.
```

## WORKSPACE dependencies from source

When using user managed npm dependencies it is not possible to use the npm to install
Bazel rules from npm packages such as `@bazel/jasmine` or `@bazel/typescript`. Instead,
you'll use the rules_nodejs package from sources (the more typical way Bazel rules are used).

This means you'll be exposed to the dev dependencies of rules_nodejs, and will need to load
and call a function in your WORKSPACE file.

```
load("@build_bazel_rules_nodejs//:package.bzl", "rules_nodejs_dev_dependencies")
rules_nodejs_dev_dependencies()
```

You then load rules from the source locations like
`load("@build_bazel_rules_nodejs//packages/jasmine:index.bzl", ...)`
rather than
`load("@npm//@bazel/jasmine:index.bzl", ...)`


text:
package com.intellij.diagnostic;

import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector;
import com.intellij.internal.DebugAttachDetector;
import com.intellij.internal.statistic.eventLog.EventLogGroup;
import com.intellij.internal.statistic.eventLog.events.EventFields;
import com.intellij.internal.statistic.eventLog.events.EventId1;
import com.intellij.internal.statistic.eventLog.events.EventId2;
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.util.concurrency.AppExecutorUtil;
import com.sun.management.OperatingSystemMXBean;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

final class IdeHeartbeatEventReporter implements Disposable {
  private static final int UI_RESPONSE_LOGGING_INTERVAL_MS = 100_000;
  private static final int TOLERABLE_UI_LATENCY = 100;

  @Nullable
  private final ScheduledExecutorService myExecutor;
  @Nullable
  private final ScheduledFuture<?> myThread;

  private volatile long myPreviousLoggedUIResponse = 0;

  IdeHeartbeatEventReporter() {
    boolean isDebugEnabled = DebugAttachDetector.isDebugEnabled();
    ApplicationManager.getApplication().getMessageBus().connect(this)
      .subscribe(IdePerformanceListener.TOPIC, new IdePerformanceListener() {
        @Override
        public void uiFreezeFinished(long durationMs, @Nullable File reportDir) {
          if (!isDebugEnabled) {
            LifecycleUsageTriggerCollector.onFreeze(durationMs);
          }
        }

        @Override
        public void uiResponded(long latencyMs) {
          final long currentTime = System.currentTimeMillis();
          if (currentTime - myPreviousLoggedUIResponse >= UI_RESPONSE_LOGGING_INTERVAL_MS) {
            myPreviousLoggedUIResponse = currentTime;
            UILatencyLogger.LATENCY.log(latencyMs);
          }
          if (latencyMs >= TOLERABLE_UI_LATENCY && !isDebugEnabled) {
            UILatencyLogger.LAGGING.log(latencyMs);
          }
        }
      });

    boolean isEap = ApplicationManager.getApplication().isEAP();
    if (isEap) {
      myExecutor = AppExecutorUtil.createBoundedScheduledExecutorService("IDE Heartbeat", 1);
      myThread = myExecutor.scheduleWithFixedDelay(
        IdeHeartbeatEventReporter::recordHeartbeat,
        0, UI_RESPONSE_LOGGING_INTERVAL_MS, TimeUnit.MILLISECONDS
      );
    }
    else {
      myExecutor = null;
      myThread = null;
    }
  }

  private static void recordHeartbeat() {
    OperatingSystemMXBean mxBean = (OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();

    int systemCpuLoad = (int)Math.round(mxBean.getSystemCpuLoad() * 100);
    systemCpuLoad = systemCpuLoad >= 0 ? systemCpuLoad : -1;

    double swapSize = mxBean.getTotalSwapSpaceSize();
    int swapLoad = swapSize > 0 ? (int)((1 - mxBean.getFreeSwapSpaceSize() / swapSize) * 100) : 0;

    UILatencyLogger.HEARTBEAT.log(systemCpuLoad, swapLoad);
  }

  @Override
  public void dispose() {
    if (myThread != null) {
      myThread.cancel(true);
    }
    if (myExecutor != null) {
      myExecutor.shutdownNow();
    }
  }

  public static final class UILatencyLogger extends CounterUsagesCollector {
    private static final EventLogGroup GROUP = new EventLogGroup("performance", 60);

    private static final EventId2<Integer, Integer> HEARTBEAT = GROUP.registerEvent(
      "heartbeat", EventFields.Int("system_cpu_load"), EventFields.Int("swap_load"));
    private static final EventId1<Long> LATENCY = GROUP.registerEvent("ui.latency", EventFields.DurationMs);
    private static final EventId1<Long> LAGGING = GROUP.registerEvent("ui.lagging", EventFields.DurationMs);

    @Override
    public EventLogGroup getGroup() {
      return GROUP;
    }
  }
}


text:
package org.apache.isis.core.metamodel.facets;

import org.apache.isis.core.metamodel.facetapi.Facet;

public interface MultipleValueFacet extends Facet {

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<XMLDB PATH="lib/ddl/tests/fixtures" VERSION="20120122" COMMENT="This is an invalid xml file used for testing.">
  <TABLES>
    <TABLE NAME="test_table1" COMMENT="Just a test table">
      <FIELDS>
        <FIELD NAME="id" LENGTH="10" NOTNULL="true" SEQUENCE="true" NEXT="incorrect_next_field"/> <!-- missing TYPE -->
        <FIELD NAME="course" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" PREVIOUS="id" NEXT="name"/>
        <FIELD NAME="name" TYPE="char" LENGTH="30" NOTNULL="false" SEQUENCE="false" DEFAULT="Moodle" PREVIOUS="course" NEXT="secondname"/>
        <FIELD NAME="secondname" TYPE="char" LENGTH="30" NOTNULL="true" SEQUENCE="false" PREVIOUS="name" NEXT="intro"/>
        <FIELD NAME="intro" TYPE="text" LENGTH="medium" NOTNULL="true" SEQUENCE="false" PREVIOUS="secondname" NEXT="avatar"/>
        <FIELD NAME="avatar" TYPE="binary" LENGTH="medium" NOTNULL="false" SEQUENCE="false" PREVIOUS="intro" NEXT="grade"/>
        <FIELD NAME="grade" TYPE="number" LENGTH="20" DECIMALS="10" NOTNULL="false" SEQUENCE="false" PREVIOUS="avatar"/>
      </FIELDS>
      <KEYS>
        <KEY NAME="primary" TYPE="primary" FIELDS="id" />
      </KEYS>
    </TABLE>
  </TABLES>
</XMLDB>


text:
package com.alcedomoreno.sirme.business.data;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alcedomoreno.sirme.business.data.Month.MonthE;
import com.alcedomoreno.sirme.business.transform.CustomerTransform;
import com.alcedomoreno.sirme.business.transform.Transformator;

public class Customer implements BusinessObject,Cloneable{

	private int idCustomer;
	private String cifCustomer;
	private String nameCustomer;	// Razon Social
	private String codeCustomer;	// NIF Cliente

	private String mainAddress;
	private String mainProv;
	private String mainPobl;
	private String mainPostalCode;
	private String mainMail;
	private String mainPhone;
	private String observations;
	private Boolean active;

	private Date dateCreated;

	// Los siguientes datos son de la direccion donde se realiza el servicio
	private String serviceLocation;
	private String serviceAddress;
	private String serviceProv;
	private String servicePobl;
	private String servicePostalCode;

	private TypeCustomer typeCustomer;
	private Collection<Contact> contacts;
	private Collection<Address> address;
	private Collection<Work> works;

	private Manager manager;
	private User commercial;

	public int getIdCustomer() {
		return idCustomer;
	}
	public void setIdCustomer(int idCustomer) {
		this.idCustomer = idCustomer;
	}
	public String getNameCustomer() {
		return nameCustomer;
	}
	public void setNameCustomer(String nameCustomer) {
		this.nameCustomer = nameCustomer;
	}
	public String getCifCustomer() {
		return cifCustomer;
	}
	public void setCifCustomer(String cifCustomer) {
		this.cifCustomer = cifCustomer;
	}
	public String getCodeCustomer() {
		return codeCustomer;
	}
	public void setCodeCustomer(String codeCustomer) {
		this.codeCustomer = codeCustomer;
	}
	public String getServiceLocation() {
		return serviceLocation;
	}
	public void setServiceLocation(String serviceLocation) {
		this.serviceLocation = serviceLocation;
	}
	public String getServiceAddress() {
		return serviceAddress;
	}
	public void setServiceAddress(String serviceAddress) {
		this.serviceAddress = serviceAddress;
	}
	public String getServiceProv() {
		return serviceProv;
	}
	public void setServiceProv(String serviceProv) {
		this.serviceProv = serviceProv;
	}
	public String getServicePobl() {
		return servicePobl;
	}
	public void setServicePobl(String servicePobl) {
		this.servicePobl = servicePobl;
	}
	public String getServicePostalCode() {
		return servicePostalCode;
	}
	public void setServicePostalCode(String servicePostalCode) {
		this.servicePostalCode = servicePostalCode;
	}
	public String getMainAddress() {
		return mainAddress;
	}
	public void setMainAddress(String mainAddress) {
		this.mainAddress = mainAddress;
	}
	public String getMainMail() {
		return mainMail;
	}
	public void setMainMail(String mainMail) {
		this.mainMail = mainMail;
	}
	public String getMainPhone() {
		return mainPhone;
	}
	public void setMainPhone(String mainPhone) {
		this.mainPhone = mainPhone;
	}
	public Manager getManager() {
		return manager;
	}
	public void setManager(Manager manager) {
		this.manager = manager;
	}
	public User getCommercial() {
		return commercial;
	}
	public void setCommercial(User commercial) {
		this.commercial = commercial;
	}
	public Collection<Contact> getContacts() {
		return contacts;
	}
	public void setContacts(Collection<Contact> contacts) {
		this.contacts = contacts;
	}
	public String getMainPobl() {
		return mainPobl;
	}
	public void setMainPobl(String mainPobl) {
		this.mainPobl = mainPobl;
	}
	public String getMainProv() {
		return mainProv;
	}
	public TypeCustomer getTypeCustomer() {
		return typeCustomer;
	}
	public void setTypeCustomer(TypeCustomer typeCustomer) {
		this.typeCustomer = typeCustomer;
	}
	public void setMainProv(String mainProv) {
		this.mainProv = mainProv;
	}
	public String getMainPostalCode() {
		return mainPostalCode;
	}
	public void setMainPostalCode(String mainPostalCode) {
		this.mainPostalCode = mainPostalCode;
	}
	public Collection<Address> getAddress() {
		return address;
	}
	public void setAddress(Collection<Address> address) {
		this.address = address;
	}
	public String getObservations() {
		return observations;
	}
	public void setObservations(String observations) {
		this.observations = observations;
	}
	public Boolean getActive() {
		return active;
	}
	public void setActive(Boolean active) {
		this.active = active;
	}
	public Collection<Work> getWorks() {
		return works;
	}
	public void setWorks(Collection<Work> works) {
		this.works = works;
	}

	public Customer(){}

	public Customer(String cif){
		this.cifCustomer = cif;
	}

	public String getServicesAddress(){
		StringBuilder sb = new StringBuilder();

		if ( address!=null && !address.isEmpty() )
			for ( Address a:address )
			sb.append( a.getMainAddress() ).append("\r\n");

		return sb.toString();
	}

	public String getServicesAddressMin(){
		int l = 25;
		String str = getServicesAddress();
		return str.substring(0, l<str.length()?l:str.length() );
	}

	public String getMonthsStr(){
		StringBuilder sb = new StringBuilder();

		Map<MonthE,MonthE> months = new HashMap<MonthE,MonthE>();

		if ( address != null )
			for ( Address a : address )
				if ( a.getMonths() != null )
					for ( MonthE m : a.getMonths() )
						months.put(m, m);

		if ( months.containsKey(MonthE.ENERO) )
			sb.append("Ene,");
		if ( months.containsKey(MonthE.FEBRERO) )
			sb.append("Feb,");
		if ( months.containsKey(MonthE.MARZO) )
			sb.append("Mar,");
		if ( months.containsKey(MonthE.ABRIL) )
			sb.append("Abr,");
		if ( months.containsKey(MonthE.MAYO) )
			sb.append("May,");
		if ( months.containsKey(MonthE.JUNIO) )
			sb.append("Jun,");
		if ( months.containsKey(MonthE.JULIO) )
			sb.append("Jul,");
		if ( months.containsKey(MonthE.AGOSTO) )
			sb.append("Ago,");
		if ( months.containsKey(MonthE.SEPTIEMBRE) )
			sb.append("Sep,");
		if ( months.containsKey(MonthE.OCTUBRE) )
			sb.append("Oct,");
		if ( months.containsKey(MonthE.NOVIEMBRE) )
			sb.append("Nov,");
		if ( months.containsKey(MonthE.DICIEMBRE) )
			sb.append("Dic,");

		return (sb.length()==0?"":sb.toString().substring( 0,sb.length()-1) );
	}

	public Double getAmount() {
		Double d = 0d;

		if ( address != null )
			for ( Address a : address )
				try{
					d += a.getAmountNumber();
				} catch ( Exception e ){}

		return d;
	}

	@Override
	public String toString(){
		return idCustomer + "," + nameCustomer + "," + cifCustomer + "," + codeCustomer;
	}

	@Override
	public Class<? extends Transformator> getTransformator() {
		return CustomerTransform.class;
	}
	public Date getDateCreated() {
		return dateCreated;
	}
	public void setDateCreated(Date dateCreated) {
		this.dateCreated = dateCreated;
	}

	@Override
	public int hashCode() {
		return idCustomer;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Customer other = (Customer) obj;
		return this.hashCode() == other.hashCode();
	}

}


text:
package de.wirecard.rxparallel;

import com.jakewharton.rxrelay2.PublishRelay;
import com.jakewharton.rxrelay2.Relay;

import org.junit.Assert;
import org.junit.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import io.reactivex.Maybe;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static org.hamcrest.core.Is.is;

public class MaybeFlowableTest {
    @Test
    public void maybeParallelWithRelay() {
        final Relay<String> source = PublishRelay.create();
        Relay<String> consumer = PublishRelay.create();
        AbsRxTest.AsyncValueAssert<String> valueAssert = new AbsRxTest.AsyncValueAssert<String>("event");
        consumer.subscribe(valueAssert);

        Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Maybe started");
                System.out.println("Sending event");
                source.accept("event");
                return "Im Done";
            }
        })
                .to(MaybeParallel.<String, String>with(source))
                .subscribeParallel(consumer)
                .test()
                .assertValue("Im Done");

        Assert.assertThat("event count", valueAssert.getCount(), is(1));
    }

    @Test
    public void maybeParallelWithRelay_sameSource() {
        final Relay<String> source = PublishRelay.create();
        Relay<String> consumer = PublishRelay.create();
        AbsRxTest.AsyncValueAssert<String> valueAssert = new AbsRxTest.AsyncValueAssert<String>("event", "event2");
        consumer.subscribe(valueAssert);

        Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Maybe started");
                System.out.println("Sending event");
                source.accept("event");
                return "Im Done";
            }
        }).to(MaybeParallel.<String, String>with(source))
                .subscribeParallel(consumer)
                .test()
                .assertValue("Im Done");

        Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Maybe 2 started");
                System.out.println("Sending event2");
                source.accept("event2");
                return "Im Done";
            }
        }).to(MaybeParallel.<String, String>with(source))
                .subscribeParallel(consumer)
                .test()
                .assertValue("Im Done");

        Assert.assertThat("event count", valueAssert.getCount(), is(2));
    }

    @Test
    public void maybeParallelWithRelay_twoSources() {
        final Relay<String> source = PublishRelay.create();
        final Relay<String> source2 = PublishRelay.create();

        Relay<String> consumer = PublishRelay.create();
        AbsRxTest.AsyncValueAssert<String> valueAssert = new AbsRxTest.AsyncValueAssert<String>("event", "event2");
        consumer.subscribe(valueAssert);

        Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Maybe started");
                System.out.println("Sending event");
                source.accept("event");
                return "Im Done";
            }
        }).to(MaybeParallel.<String, String>with(source))
                .subscribeParallel(consumer)
                .test()
                .assertValue("Im Done");

        Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Maybe 2 started");
                System.out.println("Sending event2");
                source2.accept("event2");
                return "Im Done";
            }
        }).to(MaybeParallel.<String, String>with(source2))
                .subscribeParallel(consumer)
                .test()
                .assertValue("Im Done");

        Assert.assertThat("event count", valueAssert.getCount(), is(2));
    }

    @Test
    public void maybeParallelWithRelay_error() {
        final Relay<String> source = PublishRelay.create();
        Relay<String> consumer = PublishRelay.create();
        AbsRxTest.AsyncValueAssert<String> valueAssert = new AbsRxTest.AsyncValueAssert<String>("event");
        consumer.subscribe(valueAssert);

        Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Maybe started");
                System.out.println("Sending event");
                source.accept("event");
                return throwMe();
            }
        }).to(MaybeParallel.<String, String>with(source))
                .subscribeParallel(consumer)
                .test()
                .assertError(RuntimeException.class);

        Assert.assertThat("event count", valueAssert.getCount(), is(1));
    }

    private String throwMe() {
        throw new RuntimeException("Maybe failed");
    }

    @Test
    public void maybeParallelWithRelay_sameSource_error() {
        final Relay<String> source = PublishRelay.create();
        Relay<String> consumer = PublishRelay.create();
        AbsRxTest.AsyncValueAssert<String> valueAssert = new AbsRxTest.AsyncValueAssert<String>("event", "event2");
        consumer.subscribe(valueAssert);

        Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Maybe started");
                System.out.println("Sending event");
                source.accept("event");
                throwMe();
                return null;
            }
        }).to(MaybeParallel.<String, String>with(source))
                .subscribeParallel(consumer)
                .test()
                .assertError(RuntimeException.class);

        Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Maybe 2 started");
                System.out.println("Sending event2");
                source.accept("event2");
                return "Im Done";
            }
        }).to(MaybeParallel.<String, String>with(source))
                .subscribeParallel(consumer)
                .test()
                .assertValue("Im Done");

        Assert.assertThat("event count", valueAssert.getCount(), is(2));
    }

    @Test
    public void maybeParallelWithRelay_multiParallelSub() {
        final Relay<String> source = PublishRelay.create();
        AbsRxTest.AsyncValueAssert<String> valueAssert = new AbsRxTest.AsyncValueAssert<String>("event", "event2");
        AbsRxTest.AsyncValueAssert<String> valueAssert2 = new AbsRxTest.AsyncValueAssert<String>("event", "event2");

        Relay<String> consumer = PublishRelay.create();
        consumer.subscribe(valueAssert);
        Relay<String> consumer2 = PublishRelay.create();
        consumer2.subscribe(valueAssert2);

        MaybeParallel<String, String> parallel = Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Maybe started");
                System.out.println("Sending event");
                source.accept("event");
                return "Im Done";
            }
        }).to(MaybeParallel.<String, String>with(source));
        parallel.subscribeParallel(consumer);
        parallel.subscribeParallel(consumer2);
        parallel.test()
                .assertComplete();

        Assert.assertThat("event count", valueAssert.getCount(), is(1));
        Assert.assertThat("event count", valueAssert2.getCount(), is(1));
    }

    @Test
    public void maybeParallelWithRelay_multiParallelSub_sameSource() {
        final Relay<String> source = PublishRelay.create();
        AbsRxTest.AsyncValueAssert<String> valueAssert = new AbsRxTest.AsyncValueAssert<String>("event", "event2");
        AbsRxTest.AsyncValueAssert<String> valueAssert2 = new AbsRxTest.AsyncValueAssert<String>("event", "event2");

        Relay<String> consumer = PublishRelay.create();
        consumer.subscribe(valueAssert);
        Relay<String> consumer2 = PublishRelay.create();
        consumer2.subscribe(valueAssert2);

        MaybeParallel<String, String> parallel = Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Maybe started");
                System.out.println("Sending event");
                source.accept("event");
                return "Im Done";
            }
        }).to(MaybeParallel.<String, String>with(source));
        parallel.subscribeParallel(consumer);
        parallel.subscribeParallel(consumer2);
        parallel.test()
                .assertComplete();

        MaybeParallel<String, String> parallel2 = Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Maybe started");
                System.out.println("Sending event");
                source.accept("event2");
                return "Im Done";
            }
        }).to(MaybeParallel.<String, String>with(source));
        parallel2.subscribeParallel(consumer);
        parallel2.subscribeParallel(consumer2);
        parallel2.test()
                .assertComplete();

        Assert.assertThat("event count", valueAssert.getCount(), is(2));
        Assert.assertThat("event count", valueAssert2.getCount(), is(2));
    }

    @Test
    public void maybeParallelWithoutSub() {
        final Relay<String> source = PublishRelay.create();

        Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Starting maybe");
                System.out.println("Sending event");
                source.accept("event");
                return "Im Done";
            }
        }).to(MaybeParallel.<String, String>with(source))
                .map(new Function<String, String>() {
                    @Override
                    public String apply(String s) {
                        return s.toUpperCase();
                    }
                }).test()
                .assertComplete()
                .assertValue("IM DONE");

    }

    @Test
    public void maybeParallelWithoutMultipleEventInChain() {
        final Relay<String> source = PublishRelay.create();
        Relay<String> consumer = PublishRelay.create();
        final AbsRxTest.AsyncValueAssert<String> valueAssert = new AbsRxTest.AsyncValueAssert<String>("event", "event2", "event3", "event4");
        consumer.subscribe(valueAssert);

        Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Starting maybe");
                System.out.println("Sending event");
                source.accept("event");
                return "Im Done";
            }
        }).to(MaybeParallel.<String, String>with(source))
                .subscribeParallel(consumer)
                .map(new Function<String, String>() {
                    @Override
                    public String apply(String s) {
                        System.out.println("Sending event2");
                        source.accept("event2");
                        return s.toUpperCase();
                    }
                }).test()
                .assertComplete()
                .assertValue("IM DONE");

        Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() {
                System.out.println("Starting maybe");
                System.out.println("Sending event3");
                source.accept("event3");
                return "Im Done";
            }
        }).to(MaybeParallel.<String, String>with(source))
                .subscribeParallel(consumer)
                .map(new Function<String, String>() {
                    @Override
                    public String apply(String s) {
                        System.out.println("Sending event4");
                        source.accept("event4");
                        return s.toUpperCase();
                    }
                }).test()
                .assertComplete()
                .assertValue("IM DONE");

        Assert.assertThat("event count", valueAssert.getCount(), is(4));
    }

    @Test
    public void maybeParallelDispose() throws InterruptedException {
        final Relay<String> source = PublishRelay.create();
        final Relay<String> consumer = PublishRelay.create();
        AbsRxTest.AsyncValueAssert<String> valueAssert = new AbsRxTest.AsyncValueAssert<String>("2", "1");
        consumer.subscribe(valueAssert);

        Disposable d = Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() throws Exception {
                source.accept("2");
                TimeUnit.SECONDS.sleep(3);
                return "Im Done";
            }
        })
                .to(MaybeParallel.<String, String>with(source))
                .subscribeParallel(consumer)
                .subscribeOn(Schedulers.single())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) {
                        //swallow
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable s) {
                        //swallow
                    }
                });
        TimeUnit.SECONDS.sleep(1);
        d.dispose();

        Maybe.just(1)
                .doOnSuccess(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) {
                        consumer.accept(String.valueOf(integer));
                    }
                })
                .to(MaybeParallel.<Integer, String>with(source))
                .subscribeParallel(consumer)
                .test()
                .assertValue(1);

        Assert.assertThat("event count", valueAssert.getCount(), is(2));
    }

    @Test
    public void maybeParallelEventInSubscribe() {
        final Relay<String> source = PublishRelay.create();
        final Relay<String> consumer = PublishRelay.create();
        AbsRxTest.AsyncValueAssert<String> valueAssert = new AbsRxTest.AsyncValueAssert<String>("Just", "Just do it!");
        consumer.subscribe(valueAssert);

        Maybe.just("Just")
                .doOnSuccess(new Consumer<String>() {
                    @Override
                    public void accept(String s) {
                        source.accept(s);
                    }
                }).map(new Function<String, String>() {
            @Override
            public String apply(String s) {
                return s.concat(" do it!");
            }
        }).to(MaybeParallel.<String, String>with(source))
                .subscribeParallel(consumer)
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) {
                        source.accept(s);
                    }
                });

        Assert.assertThat("event count", valueAssert.getCount(), is(2));
    }

    @Test
    public void maybeWithoutEmission() {
        final Relay<String> source = PublishRelay.create();
        final Relay<String> consumer = PublishRelay.create();
        AbsRxTest.AsyncValueAssert<String> valueAssert = new AbsRxTest.AsyncValueAssert<String>("First");
        consumer.subscribe(valueAssert);

        Maybe.fromAction(new Action() {
            @Override
            public void run() {
                System.out.println("Some maybe action");
                System.out.println("Sending first event");
                source.accept("First");
            }
        }).to(MaybeParallel.with(source))
                .subscribeParallel(consumer)
                .subscribe();

        Assert.assertThat("event count", valueAssert.getCount(), is(1));
    }
}


text:
[![GoDoc](https://pkg.go.dev/badge/github.com/bmbstack/ripple?status.svg)](https://pkg.go.dev/github.com/bmbstack/ripple?tab=doc)
[![Release](https://img.shields.io/github/release/bmbstack/ripple.svg?style=flat-square)](https://github.com/bmbstack/ripple/releases)

# Ripple

a lightweight web framework for Go(base on [Echo](https://github.com/labstack/echo))

## Installation

```shell
go get github.com/bmbstack/ripple@latest
go install github.com/bmbstack/ripple/cmd/ripple@latest
go install github.com/bmbstack/ripple/protoc/protoc-gen-gofast@latest
ripple new rippleApp
cd $GOPATH/src/rippleApp
go mod init
go mod tidy
go mod vendor
go run cmd/main.go --env dev s
```

## Upgrade

```shell
go get github.com/bmbstack/ripple@latest
go install github.com/bmbstack/ripple/cmd/ripple@latest
go install github.com/bmbstack/ripple/protoc/protoc-gen-gofast@latest
go mod tidy
go mod vendor
go run cmd/main.go --env dev s
```

If you use nacos, we recommend you:

```shell
go get github.com/smallnest/rpcx@v1.7.3
```

Then, Open the url: [http://127.0.0.1:8090](http://127.0.0.1:8090)

## Command

```
NAME:
   ripple - Command line tool to managing your Ripple application

USAGE:
   ripple [global options] command [command options] [arguments...]

VERSION:
   1.2.2

AUTHOR:
   wangmingjob <wangmingjob@icloud.com>

COMMANDS:
   new      Create a Ripple application
            desc: ripple new appName, however this appName can be empty, will be generated in the current directory
            ripple new
            ripple new app
   run, r   Run the Ripple application
   gen, g   Auto generate code, *.proto => *.pb.go *.rpc.go rpc.client.go; *.dto.go => *.controller.go && *.service.go
            desc: ripple g path component name/pbPath (path: dir/file; component: ''/proto/controller/service, name: component name, pbPath: *.pb.go path)
            ripple g
            ripple g packages/app
            ripple g packages/app proto
            ripple g packages/app controller
            ripple g packages/app service
            ripple g packages/app service product
            ripple g packages/app ecode
            ripple g packages/app/proto/user.proto
            ripple g packages/app/internal/dto/user.dto.go
            ripple g packages/app2 rpc.client packages/app1/proto/user.pb.go
   help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --env value    执行环境 (开发环境dev(只有ripple作者会使用)、线上环境prod) (default: prod)
   --help, -h     show help (default: false)
   --version, -v  print the version (default: false)
```

Note: `ripple g` or `ripple g path` or `ripple g path component` will generate some code, and the path must be the parent directory of go.mod, that is, the main directory of the project. For example, the demo project `fixtures/form`, and you will execute command:

```shell
ripple g fixture/form
```

or

```shell
cd fixture/form
ripple g
```

* *.proto => \*.pb.go, *.rpc.go(internal/rpc)
* *.dto.go => *.controller.go(internal/controllers/v1), *.service.go(internal/service)

*.proto example

```protobuf
syntax = "proto3";

// @RippleRpc
// @NacosGroup DEFAULT_GROUP
// @NacosCluster ripple
package proto;

// The Student service definition.
service Student {
  rpc Learn (LearnReq) returns (LearnReply) {}
}

message LearnReq {
  uint64 id = 1;
}

message LearnReply {
  string name = 1;
}

```

`Note`: @RippleRpc, @NacosGroup, @NacosCluster

`*.dto.go` example:

```go
// ReqStudentLearn
// @RippleApi
// @Uri /student/learn
// @Method POST
type ReqStudentLearn struct {
    ID uint64 `form:"id" json:"id" binding:"required"`
}

type RespStudentLearn struct {
    Name string `json:"name"`
}

```

`Note`: @RippleApi, @Uri, @Method

## Command: ripple g

```shell
# generate all files, contains *.pb.go, *.controller.go, *.service.go, *.rpc.go(source file: *.dto.go, *.proto)
ripple g
# generate all files in this directory, contains *.pb.go, *.controller.go, *.service.go, *.rpc.go(source file: *.dto.go, *.proto)
ripple g packages/app
# just generate *.pb.go(source file: *.proto)
ripple g packages/app proto
# just generate *.controller.go(source file: *.dto.go)
ripple g packages/app controller
# just generate *.service.go(source file: *.dto.go)
ripple g packages/app service
# just generate *.service.go(source: serviceName, this product is a serviceName)
ripple g packages/app service product
# just generate *.ecode.go
ripple g packages/app ecode
# just generate *.pb.go(souce file: *.proto)
ripple g packages/app/proto/user.proto
# just generate *.controller.go, *.service.go(souce file: *.dto.go)
ripple g packages/app/internal/dto/user.dto.go
# just generate rpcclient/rpc.client.go in app2(souce file: app1's *.pb.go)
ripple g packages/app2 rpc.client packages/app1/proto/user.pb.go
```

This is the structure of the `rippleApp` list application that will showcase how you can build web apps with `ripple`:

```shell
.
├── Makefile
├── cmd                               // 程序入口
│   └── main.go
├── config                            // 配置文件
│   ├── config.dev.yaml
│   ├── config.prod.yaml
│   └── config.test.yaml
├── frontend                          // 前端页面
│   ├── static
│   └── templates
├── go.mod
├── go.sum
├── internal
│   ├── controllers                  // `ripple gen`固定输出目录 controllers/v1
│   ├── dto                          // `ripple gen`的输入源 *.dto.go
│   ├── helper
│   ├── initial
│   ├── rpc                          // `ripple gen`固定输出目录
│   ├── rpcclient                    // `ripple gen`固定输出目录
│   ├── scripts
│   └── services                     // `ripple gen`固定输出目录
└── proto                            // `ripple gen`固定输入源 *.proto
    ├── user.pb.go
    └── user.proto

```

## Rpc client call, eg (fixture/form):

```go
sc := services.GetStudentClient()
reply, _ := sc.Learn(context.Background(), &proto.LearnReq{Id: 1})
```

## Rpc server register, eg (fixture/form):

```go
ripple.Default().RegisterRpc(proto.ServiceNameOfStudent, &rpc.StudentRpc{}, "")
ripple.Default().RunRpc()

// service impl
type StudentRpc struct {
}

// Learn is server rpc method as defined
func (this *StudentRpc) Learn(ctx context.Context, req *proto.LearnReq, reply *proto.LearnReply) (err error) {
	// TODO: add some code
	*reply = proto.LearnReply{}
	reply.Name = "student learn function"
	return nil
}
```

## Cache (Redis)

```go
cache := ripple.Default().GetCache("cacheAlias")
result, err := cache.HGetAll(context.Background(), "key").Result()
```

or

```go
cache := ripple.Default().GetCache("cacheAlias")
client := cache.Client().(*redis.Client)
result, err := client.HGetAll(context.Background(), "key").Result()
```

## Logger

### SLS(aliyun log)
```go
ripple.Default().AddLogType(ripple.LogTypeSLS)
```
or
### CLS(tecent cloud log)
```go
ripple.Default().AddLogType(ripple.LogTypeCLS)
```

Use logger like this
```go
import "github.com/bmbstack/ripple/logger"

logger.With(map[string]interface{}{
    "userId": 101,
    "traceId": "lskajdfouiaadgvv",
}).Info("hello, tom")

logger.Info("hello, jack")
```
## Please close Resource, when the program exits

```go
rpcclient.CloseAll()
ripple.Default().StopRpc()
ripple.Default().CloseOrm()
ripple.Default().CloseCache()
```

## Which features to include in a framework

A framework has 3 parts. A router receiving a request and directing it to a handler, a middleware system to add reusable pieces of software before and after the handler, and the handler processing the request and writing the response.

- Router
- Middlewares
- Handler processing

<img src="https://raw.githubusercontent.com/bmbstack/ripple/master/screenshots/framework.png" width="720" height="576" />

Middlewares handle:

- error/panic
- logging
- security
- sessions
- cookies
- body parsing

## Features

* [x] MySQL and Foundation database support
* [x] Modular (you can choose which components to use)
* [x] Middleware support, compatible Middleware works out of the box
* [x] Lightweight
* [x] Multiple configuration files support (currently ```.env```)

## Overview

`ripple` is a lightweight framework. It is based on the principles of simplicity, relevance and elegance.

- Simplicity. The design is simple, easy to understand and doesn't introduce many layers between you and the standard library. It is a goal of the project that users should be able to understand the whole framework in a single day.
- Relevance. `ripple` doesn't assume anything. We focus on things that matter, this way we are able to ensure easy maintenance and keep the system well-organized, well-planned and sweet.
- Elegance. `ripple` uses golang best practises. We are not afraid of heights, it's just that we need a parachute in our backpack. The source code is heavily documented, any functionality should be well explained and well tested.

## Configurations

ripple support .env configurations files. In our rippleApp app, we put the configuration files in the current project directory. I have included all three formats for clarity, you can be just fine with either one of them.

ripple searches for a file named .env in the config directory. The first to be found is the one to be used.

This is the content of ```config.dev.yaml/config.test.yaml/config.prod.yaml``` file:

```shell
domain: "127.0.0.1:8090"
static: "frontend/static"
templates: "frontend/templates"
autoMigrate: false
bindAllTag: false
databases: [
  {
    "alias": "one",
    "dialect": "mysql",
    "host": "127.0.0.1",
    "port": 3306,
    "name": "one",
    "username": "root",
    "password": "123456"
    "maxIdleConns": 200,
    "maxOpenConns": 1000
  },
  {
    "alias": "two",
    "dialect": "mysql",
    "host": "127.0.0.1",
    "port": 3306,
    "name": "two",
    "username": "root",
    "password": "123456"
    "maxIdleConns": 200,
    "maxOpenConns": 1000
  }
]
caches: [
  {
    "alias": "one",
    "section": "one",
    "adapter": "redis",
    "host": "127.0.0.1",
    "port": 6379,
    "password": "123456"
  },
  {
    "alias": "two",
    "section": "two",
    "adapter": "redis",
    "host": "127.0.0.1",
    "port": 6379,
    "password": "123456"
  }
]
nacos:
  host: "my.nacos.com"
  port: 8848
  namespaceId: "public"
  cluster: "ripple_user"
  group: "DEFAULT_GROUP"
  failMode: "failover"
  selectMode: "roundRobin"
  clientPoolSize: 10
  cacheDir: "./cache"
  logDir: "./log"
  server: "127.0.0.1:18090"
sls:
  accessKeyId: "xxxxxxx"
  accessKeySecret: "xxxxxxx"
  endpoint: "cn-beijing-intranet.log.aliyuncs.com"
  allowLogLevel: "info"  # debug,info,warn,error
  closeStdout: false
  project: "xxxxxxx"
  logstore: "xxxxxxx"
  topic: "topic"
  source: "source"
cls:
  accessKeyId: "xxxxxxx"
  accessKeySecret: "xxxxxxx"
  endpoint: "ap-beijing.cls.tencentcs.com"
  allowLogLevel: "info"  # debug,info,warn,error
  closeStdout: false
  topic: "b246af67-dab3-408b-b802-ba150488ffbf"
```

## Models

ripple uses the [gorm](https://gorm.io/gorm) library as its Object Relational Mapper, so you won't need to learn anything fancy. In our rippleApp app, we need to define a User model that will be used to store our todo details.

In the file models/user.go we define our rippleApp model like this

```go
package models

import (
	"github.com/bmbstack/ripple"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Login       string `sql:"size:255;not null"`
	Password    string `sql:"size:255;not null"`
	Email       string `sql:"size:255"`
	Avatar      string `sql:"size:255"`
	Github      string `gorm:"column:github"`
	QQ          string `gorm:"column:qq"`
	Weibo       string `gorm:"column:weibo"`
	Weixin      string `gorm:"column:weixin"`
	HomePage    string `gorm:"column:home_page"`
	Tagline     string
	Description string
	Location    string
}

func init() {
	ripple.Default().RegisterModels(&User{})
}

```

Notice that we need to register our model by calling ripple.RegisterModels(&User{}) in the init function otherwise ripple won't be aware of the model.

ripple will automatically create the table users if it doesn't exist.

Don't be confused by the schema tag, I just added them since we will use the schema package to decode form values(this has nothing to do with ripple, you can use whatever form library you fancy.)

## Controllers

ripple controllers are structs that implement the Controller interface. To help make ripple usable, Structs must implement the Controller interface.

```go
type Controller interface {
Path() string
}
```

This creates a new Echo group at the Controller#Path, in our example /posts, with all the defined actions.

```shell
 GET /posts     => #ActionIndex
 GET /posts/:id => #ActionShow
```

Our rippleApp Controller is in the controllers/home.go

```go
package controllers

import (
	"net/http"
	"github.com/bmbstack/ripple"
	"github.com/labstack/echo/v4"
)

type HomeController struct {
	Index  echo.HandlerFunc `controller:"GET /"`
	Html   echo.HandlerFunc `controller:"GET html"`
	String echo.HandlerFunc `controller:"GET string"`
}

func init() {
	ripple.Default().RegisterController(&HomeController{})
}

func (this HomeController) Path() string {
	return "/"
}

func (this HomeController) ActionIndex(ctx echo.Context) error {
	return ctx.Render(http.StatusOK, "home/index.html", map[string]interface{}{
		"title": "Hello, forum is a Ripple application ",
	})
}

func (this HomeController) ActionHtml(ctx echo.Context) error {
	return ctx.Render(http.StatusOK, "home/html.html", map[string]interface{}{
		"title": "Hello, this is a html template",
	})
}

func (this HomeController) ActionString(ctx echo.Context) error {
	return ctx.String(http.StatusOK, "Hello, this is a string")
}

```

Note that we registered our controller by calling ripple.RegisterController($HomeController{}) in the init function so as to make ripple aware of our controller. See Routing section below for more explanation of what the controller is doing.

## Templates

ripple templates are golang templates(use [pongo2](https://github.com/flosch/pongo2)). This is the content of frontend/templates/home/index.html:

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h3>{{title}}</h3>

<h3>Routes</h3>
<ul>
    <li>
        <a href="http://localhost:8090/html" target="_blank">Html template Page</a>
    </li>
    <li>
        <a href="http://localhost:8090/string" target="_blank">String Page</a>
    </li>
</ul>
</body>
</html>
```


text:
using System;
using System.Runtime.Caching;
using System.Threading;
using Autofac;
using CachingServiceWithAOP.CachingServices;
using CachingServiceWithAOP.Tests.Infrastructure;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CachingServiceWithAOP.Tests
{
    [TestClass]
    public class DynamicProxyBehavior
    {
        [TestMethod]
        public void CanExecuteBaseInputWithoutErroring()
        {
            SimpleTestingHelpers.ClearKeysFromMemcache();

            const int input = 5;

            var container = AutofacTestModule.BuildContainer();

            var service = container.Resolve<IExampleService>();

            var result = service.ReturnIntThatWasPassedIn(input);

            Assert.AreEqual(input, result);
        }

        [TestMethod]
        public void CanRetrieveAnOldValueFromTheCache()
        {
            SimpleTestingHelpers.ClearKeysFromMemcache();

            var builder = new ContainerBuilder();

            builder.RegisterModule<AutofacTestModule>();
            builder.RegisterType<MemoryCacheService>()
                .WithParameter("expiration", new TimeSpan(0, 0, 1))
                .As<ICacheService>();

            var container = builder.Build();

            var service = container.Resolve<IExampleService>();

            var firstResult = service.GetCurrentTime();

            Thread.Sleep(1);

            var secondResult = service.GetCurrentTime();

            Assert.AreEqual(firstResult.Ticks, secondResult.Ticks);
        }

        [TestMethod]
        public void CannotRetrieveAnOldValueFromTheCacheAfterTime()
        {
            SimpleTestingHelpers.ClearKeysFromMemcache();

            var builder = new ContainerBuilder();

            builder.RegisterModule<AutofacTestModule>();

            var cachePeriod = new TimeSpan(1);

            builder.RegisterType<MemoryCacheService>()
                .WithParameter("expiration", cachePeriod)
                .As<ICacheService>();

            var container = builder.Build();

            var service = container.Resolve<IExampleService>();

            var firstResult = service.GetCurrentTime().Ticks;

            Thread.Sleep(1);

            var secondResult = service.GetCurrentTime().Ticks;

            Assert.AreNotEqual(firstResult, secondResult);
        }
    }
}


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

// Node.js API
//
// This is what you get when you `require('traceur')`.
// It's suppose to be used by custom scripts or tools such as Grunt or Karma.

'use strict';

var path = require('path');
var traceur = require('./traceur.js');
var util = require('./file-util.js');
var writeFile = util.writeFile;

var Compiler = traceur.Compiler;

function NodeCompiler() {
  Compiler.call(this);
  this.cwd = process.cwd();
}

NodeCompiler.prototype = {
  __proto__: Compiler.prototype,
  resolveModuleName: function(filename) {
    if (!filename)
      return;
    var moduleName = filename.replace(/\.js$/, '');
    return path.relative(this.cwd, moduleName).replace(/\\/g,'/');
  },
  sourceRootForFilename: function(filename) {
    return path.relative(path.dirname(filename), '.');
  }
};

function compile(content, options) {
  return new NodeCompiler().stringToString(content,
      Compiler.commonJSOptions(options));
}

/**
 * Use Traceur to Compile ES6 module source code to commonjs format.
 *
 * @param  {string} content ES6 source code.
 * @param  {Object=} options Traceur options.
 * @return {{js: string, errors: Array, sourceMap: string} Transpiled code.
 */
function moduleToCommonJS(content) {
  return new NodeCompiler().stringToString(content,
      Compiler.commonJSOptions({}));
}
/**
 * Use Traceur to Compile ES6 module source code to amd format.
 *
 * @param  {string} content ES6 source code.
 * @param  {Object=} options Traceur options.
 * @return {{js: string, errors: Array, sourceMap: string} Transpiled code.
 */
function moduleToAmd(content) {
  return new NodeCompiler().stringToString(content,
      Compiler.amdOptions({}));
}

function treeToString(input) {
  return new NodeCompiler().treeToString(input);
}

function getSourceMapFileName(name) {
  return name.replace(/\.js$/, '.map');
}

function writeCompiledCodeToFile(compiledCode, filename, sourcemap) {
  var sourceMapFilePath;
  if (sourcemap) {
    sourceMapFilePath = getSourceMapFileName(filename);
    compiledCode += '\n//# sourceMappingURL=' +
        path.basename(sourceMapFilePath) + '\n';
  }
  writeFile(filename, compiledCode);
  if (sourcemap)
    writeFile(sourceMapFilePath, sourcemap);
}

module.exports = {
  compile: compile,
  moduleToCommonJS: moduleToCommonJS,
  moduleToAmd: moduleToAmd,
  treeToString: treeToString,
  writeCompiledCodeToFile: writeCompiledCodeToFile,
};


text:
This plugin provides completion and useful aliases for [MicroK8s](https://microk8s.io/).

To use it, add `microk8s` to the plugins array in your zshrc file.

```zsh
plugins=(... microk8s)
```

## Aliases

| Alias | Command          | Description                                                                                |
|-------|------------------|----------------------------------------------------------------------------------------------------------|
| mco   | microk8s.config  | Shows the Kubernetes config file.                                                                        |
| mct   | microk8s.ctr     | Interact with containerd CLI.                                                                            |
| mdi   | microk8s.disable | Disables an addon.                                                                                |
| me    | microk8s.enable  | Enables an addon.                                                                                |
| mh    | microk8s.helm    | Interact with Helm CLI.                                                                                |
| mis   | microk8s.istio   | Interact with Istio CLI.                                                                                |
| mk    | microk8s.kubectl | Interact with Kubernetes CLI.                                                                            |
| msp   | microk8s.stop    | Stops all Kubernetes services.                                                                           |
| mst   | microk8s.start   | Starts MicroK8s after it is being stopped.                                                               |
| msts  | microk8s.status  | Provides an overview of the MicroK8s state (running / not running) as well as the set of enabled addons. |


text:
using Difi.SikkerDigitalPost.Klient.Domene.Entiteter.Post;
using Difi.SikkerDigitalPost.Klient.Domene.Exceptions;
using Difi.SikkerDigitalPost.Klient.Tester.Utilities;
using Xunit;

namespace Difi.SikkerDigitalPost.Klient.Tester
{
    public class DokumentpakkeTests
    {
        public class Validering
        {
            [Fact]
            public void LeggFilerTilDokumentpakkeAntallStemmer()
            {
                var dokumentpakke = DomainUtility.GetDokumentpakkeWithMultipleVedlegg(5);

                Assert.Equal(DomainUtility.GetVedleggFilesPaths().Length, dokumentpakke.Vedlegg.Count);
                Assert.NotNull(dokumentpakke);
            }

            [Fact]
            public void LeggTilVedleggOgSjekkIdNummer()
            {
                var dokumentpakke = DomainUtility.GetDokumentpakkeWithoutAttachments();

                dokumentpakke.LeggTilVedlegg(new Dokument("Dokument 1", new byte[] {0x00}, "text/plain"));
                dokumentpakke.LeggTilVedlegg(new Dokument("Dokument 2", new byte[] {0x00}, "text/plain"));
                dokumentpakke.LeggTilVedlegg(new Dokument("Dokument 3", new byte[] {0x00}, "text/plain"),
                    new Dokument("Dokument 4", new byte[] {0x00}, "text/plain"));

                Assert.Equal(dokumentpakke.Hoveddokument.Id, "Id_2");
                for (var i = 0; i < dokumentpakke.Vedlegg.Count; i++)
                {
                    var vedlegg = dokumentpakke.Vedlegg[i];
                    Assert.Equal(vedlegg.Id, "Id_" + (i + Dokumentpakke.VEDLEGG_START_ID));
                }
            }
        }

        public class Exceptions
        {
            [Fact]
            public void LeggTilVedleggSammeFilnavnKasterException()
            {
                var dokumentpakke = DomainUtility.GetDokumentpakkeWithoutAttachments();

                dokumentpakke.LeggTilVedlegg(new Dokument("DokumentUnikt", new byte[] {0x00}, "text/plain", "NO",
                    "Filnavn.txt"));

                Assert.Throws<KonfigurasjonsException>(() =>
                    dokumentpakke.LeggTilVedlegg(new Dokument("DokumentDuplikat", new byte[] {0x00}, "text/plain", "NO",
                        "Filnavn.txt"))
                    );
            }

            [Fact]
            public void LeggTilVedleggSammeNavnSomHoveddokumentKasterException()
            {
                var dokumentpakke = DomainUtility.GetDokumentpakkeWithoutAttachments();

                Assert.Throws<KonfigurasjonsException>(() =>
                    dokumentpakke.LeggTilVedlegg(new Dokument("DokumentSomHoveddokument", new byte[] {0x00}, "text/plain", "NO", dokumentpakke.Hoveddokument.Filnavn))
                    );
            }
        }
    }
}


text:
<?php

namespace Acme\FormBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class AcmeFormBundle extends Bundle
{
}


text:
package io.zucchiniui.backend.testrun.views;

import com.google.common.collect.Sets;
import io.zucchiniui.backend.scenario.views.ScenarioListItemView;
import io.zucchiniui.backend.scenario.views.ScenarioStats;
import io.zucchiniui.backend.scenario.views.ScenarioViewAccess;
import io.zucchiniui.backend.support.ddd.morphia.MorphiaUtils;
import io.zucchiniui.backend.testrun.dao.TestRunDAO;
import io.zucchiniui.backend.testrun.domain.TestRun;
import io.zucchiniui.backend.testrun.domain.TestRunQuery;
import io.zucchiniui.backend.testrun.domain.TestRunRepository;
import ma.glasnost.orika.BoundMapperFacade;
import org.springframework.stereotype.Component;

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

@Component
public class TestRunViewAccess {

    private final TestRunRepository testRunRepository;

    private final TestRunDAO testRunDAO;

    private final ScenarioViewAccess scenarioViewAccess;

    private final BoundMapperFacade<TestRun, TestRunListItem> testRunToListItemMapper;

    public TestRunViewAccess(
        final TestRunRepository testRunRepository,
        final TestRunDAO testRunDAO,
        final ScenarioViewAccess scenarioViewAccess
    ) {
        this.testRunRepository = testRunRepository;
        this.testRunDAO = testRunDAO;
        this.scenarioViewAccess = scenarioViewAccess;

        final TestRunMapper mapper = new TestRunMapper();
        testRunToListItemMapper = mapper.dedicatedMapperFor(TestRun.class, TestRunListItem.class, false);
    }

    public List<TestRunListItem> getTestRunListItems(final Consumer<TestRunQuery> preparator, final boolean withStats) {
        return MorphiaUtils.streamQuery(testRunDAO.prepareTypedQuery(preparator))
            .map(testRun -> {
                final TestRunListItem item = testRunToListItemMapper.map(testRun);
                if (withStats) {
                    final ScenarioStats stats = scenarioViewAccess.getStats(q -> q.withTestRunId(item.getId()));
                    item.setStats(stats);
                }
                return item;
            })
            .collect(Collectors.toList());
    }

    public TestRunScenarioDiff getScenarioDiff(final String leftTestRunId, final String rightTestRunId) {
        final TestRun leftTestRun = testRunRepository.getById(leftTestRunId);
        final TestRun rightTestRun = testRunRepository.getById(rightTestRunId);

        final Map<String, ScenarioListItemView> leftScenarii = scenarioViewAccess.getScenarioListItemsGroupedByScenarioKey(q -> q.withTestRunId(leftTestRunId));
        final Map<String, ScenarioListItemView> rightScenarii = scenarioViewAccess.getScenarioListItemsGroupedByScenarioKey(q -> q.withTestRunId(rightTestRunId));

        final Set<String> newScenarioFeatureKeys = Sets.difference(rightScenarii.keySet(), leftScenarii.keySet());
        final List<ScenarioListItemView> newScenarii = newScenarioFeatureKeys.stream()
            .map(rightScenarii::get)
            .sorted(Comparator.comparing(item -> item.getInfo().getName()))
            .collect(Collectors.toList());

        final Set<String> deletedScenarioFeatureKeys = Sets.difference(leftScenarii.keySet(), rightScenarii.keySet());
        final List<ScenarioListItemView> deletedScenarii = deletedScenarioFeatureKeys.stream()
            .map(leftScenarii::get)
            .sorted(Comparator.comparing(item -> item.getInfo().getName()))
            .collect(Collectors.toList());

        final Set<String> commonFeatureKeys = Sets.intersection(leftScenarii.keySet(), rightScenarii.keySet());

        final List<TestRunScenarioDiff.ScenarioDiff> scenarioDiffs = commonFeatureKeys.stream()
            .map(scenarioKey -> {
                final ScenarioListItemView leftScenario = leftScenarii.get(scenarioKey);
                final ScenarioListItemView rightScenario = rightScenarii.get(scenarioKey);

                if (leftScenario.getStatus() != rightScenario.getStatus()) {
                    return new TestRunScenarioDiff.ScenarioDiff(leftScenario, rightScenario);
                }

                return null;
            })
            .filter(Objects::nonNull)
            .sorted(Comparator.comparing(d -> d.getLeft().getInfo().getName()))
            .collect(Collectors.toList());

        final TestRunScenarioDiff diff = new TestRunScenarioDiff();
        diff.setLeftTestRun(leftTestRun);
        diff.setRightTestRun(rightTestRun);
        diff.setNewScenarii(newScenarii);
        diff.setDeletedScenarii(deletedScenarii);
        diff.setDifferentScenarii(scenarioDiffs);
        return diff;
    }

}


text:
import sys
import threading
from time import sleep

from PyQt4.QtGui import *
from PyQt4.QtCore import *

from demo_ui import Ui_MainWindow

from fgpio import GPIO
from fgpio.boards.nanopi import Config

class Demo(QMainWindow, Ui_MainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setGeometry(QApplication.desktop().availableGeometry())
        self.setFixedSize(320, 240)
        self.setupUi(self)
        self._init_events()
        self._g = GPIO(Config())
        self._init_buttons()
        self._init_leds()
        self._pin_servo = 26
        self._servo_dc = 50
        self._pin_dimmer = 22
        self._dimmer_dc = 50
        self._g.pwm_init(self._pin_servo, 20000000, 1500000)
        self._g.pwm_init(self._pin_dimmer, 1000000, 500000)

    def _exit(self):
        self._close_servo()
        self._close_dimmer()
        self._close_leds()
        self._close_buttons()
        exit()

    def _init_events(self):
        self.tab_demo.currentChanged.connect(self._tab_changer)
        self.btn_exit.clicked.connect(self._exit)
        self.dial_servo.valueChanged.connect(self._servo_dial)
        self.dial_dimmer.valueChanged.connect(self._dimmer_dial)
        self.rbox_1.clicked.connect(self._rbox1_handler)
        self.rbox_2.clicked.connect(self._rbox2_handler)
        self.rbox_3.clicked.connect(self._rbox3_handler)

    def _tab_changer(self, index):
        if index == 0:
            pass
        elif index == 1:
            self._g.pwm_stop(self._pin_servo)
            self._init_dimmer()
            self.dial_dimmer.setValue(self._dimmer_dc)

        elif index == 2:
            self._g.pwm_stop(self._pin_dimmer)
            # See above comment about setting period in ns.
            self._init_servo()
            self.dial_servo.setValue(self._servo_dc)

    def _init_leds(self):
        self._toggling = False
        self._l1 = 11
        self._l2 = 13
        self._g.gpio_init(self._l1, 'out')
        self._g.gpio_init(self._l2, 'out')
        self._g.gpio_write(self._l1, 1)

    def _rbox1_handler(self):
        self._toggling = False
        self._g.gpio_write(self._l2, 0)
        self._g.gpio_write(self._l1, 1)

    def _rbox2_handler(self):
        self._toggling = False
        self._g.gpio_write(self._l1, 0)
        self._g.gpio_write(self._l2, 1)

    def _rbox3_handler(self):
        self._toggling = True
        r3 = threading.Thread(target=self._led_toggler)
        r3.daemon = True
        r3.start()

    def _led_toggler(self):
        led = False
        while self._toggling:
            led = not led
            if led :
                self._g.gpio_write(self._l1, 0)
                self._g.gpio_write(self._l2, 1)
            else:
                self._g.gpio_write(self._l2, 0)
                self._g.gpio_write(self._l1, 1)
            sleep(1)

    def _close_leds(self):
        self._toggling = False
        sleep(.2)
        self._g.gpio_close(self._l1)
        self._g.gpio_close(self._l2)

    def _init_buttons(self):
        self._button_running = True
        b1 = threading.Thread(target=self._button_press, args=(29, self.lbl_btn_1))
        b1.daemon = True
        b1.start()
        b2 = threading.Thread(target=self._button_press, args=(15, self.lbl_btn_2))
        b2.daemon = True
        b2.start()

    def _button_press(self, pin, btn):
        self._g.eint_init(pin, 'high')
        btn_on = False

        while self._button_running:
            if self._g.eint_event(pin):
                self._g.eint_clear(pin)
                if not btn_on:
                    btn.setText('ON')
                    btn_on = True
            else:
                if btn_on:
                    btn.setText('OFF')
                    btn_on = False
            sleep(.05)

        self._g.eint_close(pin)

    def _close_buttons(self):
        self._button_running = False
        sleep(.2)

    def _init_dimmer(self):
        self.dial_dimmer.setEnabled(True)
        self._g.pwm_period(self._pin_dimmer, 1000000)
        self._g.pwm_start(self._pin_dimmer)

    def _close_dimmer(self):
        self.dial_dimmer.setEnabled(False)
        try:
            self._g.pwm_close(self._pin_dimmer)
        except:
            pass

    def _dimmer_dial(self, value):
        base_dc = 0
        max_dc  = 1000000
        new_dc = base_dc + (value*10000)

        if new_dc > max_dc:
            new_dc = max_dc

        self._dimmer_dc = value
        self._g.pwm_duty_cycle(self._pin_dimmer, new_dc)

    def _init_servo(self):
        self.dial_servo.setEnabled(True)
        self._g.pwm_period(self._pin_servo, 20000000)
        self._g.pwm_start(self._pin_servo)

    def _close_servo(self):
        self.dial_servo.setEnabled(False)
        try:
            self._g.pwm_close(self._pin_servo)
        except:
            pass

    def _servo_dial(self, value):
        base_dc = 1000000
        max_dc  = 2000000
        new_dc = base_dc + (value*(base_dc/100))

        if new_dc > max_dc:
            new_dc = max_dc

        self._servo_dc = value
        self._g.pwm_duty_cycle(self._pin_servo, new_dc)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    d = Demo()
    d.show()
    sys.exit(app.exec_())


text:
import Ember from 'ember';
import layout from './template';

export default Ember.Component.extend({
  layout,
  didInsertElement: function () {
    Ember.$('.flexslider').flexslider({
      animation: "fade",
      slideshow: true,
      slideshowSpeed: 7000,
      animationDuration: 600,
      prevText: "",
      nextText: "",
      controlNav: false
    });
  }
});


text:
namespace bp = boost::python;

struct ColorRange_wrapper : osgSim::ColorRange, bp::wrapper< osgSim::ColorRange > {

    ColorRange_wrapper(float min, float max )
    : osgSim::ColorRange( min, max )
      , bp::wrapper< osgSim::ColorRange >(){
        // constructor

    }

    ColorRange_wrapper(float min, float max, ::std::vector< osg::Vec4f > const & colors )
    : osgSim::ColorRange( min, max, boost::ref(colors) )
      , bp::wrapper< osgSim::ColorRange >(){
        // constructor

    }

    virtual ::osg::Vec4 getColor( float scalar ) const  {
        if( bp::override func_getColor = this->get_override( "getColor" ) )
            return func_getColor( scalar );
        else{
            return this->osgSim::ColorRange::getColor( scalar );
        }
    }

    ::osg::Vec4 default_getColor( float scalar ) const  {
        return osgSim::ColorRange::getColor( scalar );
    }

    virtual void setThreadSafeRefUnref( bool threadSafe ) {
        if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
            func_setThreadSafeRefUnref( threadSafe );
        else{
            this->osg::Referenced::setThreadSafeRefUnref( threadSafe );
        }
    }

    void default_setThreadSafeRefUnref( bool threadSafe ) {
        osg::Referenced::setThreadSafeRefUnref( threadSafe );
    }

};

void register_ColorRange_class(){

    bp::class_< ColorRange_wrapper, bp::bases< osgSim::ScalarsToColors >, osg::ref_ptr< ColorRange_wrapper >, boost::noncopyable >( "ColorRange", "\nColorRange is a ScalarsToColors object to define a color spectrum\nfor a scalar range. An optional vector of colors may be passed in at\nconstruction time. The range of colors will be mapped to the scalar range,\nand interpolation between the colors will be performed as necessary.\nBy default, the color range will run Red-Yellow-Green-Cyan-Blue.\n", bp::init< float, float >(( bp::arg("min"), bp::arg("max") ), "\n Constructor for a ColorRange with a default list of colors set to Red-Yellow-Green-Blue-Cyan\n    @param min:      minimum scalar value\n    @param max:      maximum scalar value\n") )
        .def( bp::init< float, float, std::vector< osg::Vec4f > const & >(( bp::arg("min"), bp::arg("max"), bp::arg("colors") ), "\n Constructor for a ColorRange\n    @param min:      minimum scalar value\n    @param max:      maximum scalar value\n    @param colors:   optional range of colors,\n") )
        .def(
            "getColor"
            , (::osg::Vec4 ( ::osgSim::ColorRange::* )( float )const)(&::osgSim::ColorRange::getColor)
            , (::osg::Vec4 ( ColorRange_wrapper::* )( float )const)(&ColorRange_wrapper::default_getColor)
            , ( bp::arg("scalar") ) )
        .def(
            "getColors"
            , (::std::vector< osg::Vec4f > const & ( ::osgSim::ColorRange::* )(  )const)( &::osgSim::ColorRange::getColors )
            , bp::return_internal_reference< >()
            , " Get the range of colors" )
        .def(
            "setColors"
            , (void ( ::osgSim::ColorRange::* )( ::std::vector< osg::Vec4f > const & ))( &::osgSim::ColorRange::setColors )
            , ( bp::arg("colors") )
            , " Set the range of colors." );

}


text: asserted.some(assertedMsg => msg.toString().indexOf(assertedMsg) > -1);


text:
<?php

namespace Lime\Highlighter\Node;

class Node implements NodeInterface {

    protected $type;
    protected $value;
    protected $attributes = [];

    /**
     * Create an attribute with the specified type & value
     *
     * @param string $type
     * @param mixed $value
     */
    public function __construct($type, $value)
    {
        $this->type = $type;
        $this->value = $value;
    }

    /**
     * Set an attribute for the node
     *
     * @param string $attr_name Attribute name
     * @param mixed $attr_value Attribute value
     * @return $this
     */
    public function setAttribute($attr_name, $attr_value)
    {
        $this->attributes[$attr_name] = $attr_value;
        return $this;
    }

    /**
     * Set multiple attributes for the node
     *
     * @param \Traversable|array $attributes
     * @returns $this
     */
    public function setAttributes(\Traversable $attributes)
    {
        foreach ($attributes as $attr_name => $attr_value) {
            $this->setAttribute($attr_name, $attr_value);
        }
        return $this;
    }

    /**
     * Check if the node has an attribute set
     *
     * @param $attr_name Attribute name
     * @return bool
     */
    public function hasAttribute($attr_name)
    {
        return isset($this->attributes[$attr_name]);
    }

    /**
     * Return the value of an attribute
     *
     * @param $attr_name Attribute name
     * @return mixed
     */
    public function getAttribute($attr_name)
    {
        return false === $this->hasAttribute($attr_name) ? null :  $this->attributes[$attr_name];
    }

    /**
     * Return all attributes set
     * @return array
     */
    public function getAttributes()
    {
        return $this->attributes;
    }

}


text:
/**
* OWASP Benchmark Project v1.3alpha
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* https://www.owasp.org/index.php/Benchmark.
*
* The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Nick Sanidas Aspect Security
* @created 2015
*/

package sqlInjection.benchmarktest;

import java.io.IOException;

import javax.servlet.ServletException;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@WebServlet(value="/sqli-06/BenchmarkTest02735")
public class BenchmarkTest02735 extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");

		helpers.SeparateClassRequest scr = new helpers.SeparateClassRequest( request );
		String param = scr.getTheValue("BenchmarkTest02735");

		String bar = doSomething(param);

		String sql = "SELECT TOP 1 userid from USERS where USERNAME='foo' and PASSWORD='" + bar + "'";
		try {
			Long results = helpers.DatabaseHelper.JDBCtemplate.queryForLong(sql);
			response.getWriter().println(
				"Your results are: "
			);

	//		System.out.println("your results are");
			response.getWriter().println(
				results.toString()
			);
	//		System.out.println(results);
		} catch (org.springframework.dao.EmptyResultDataAccessException e) {
			response.getWriter().println(
				"No results returned for query: " + org.owasp.esapi.ESAPI.encoder().encodeForHTML(sql)
			);
		} catch (org.springframework.dao.DataAccessException e) {
			if (helpers.DatabaseHelper.hideSQLErrors) {
        		response.getWriter().println(
					"Error processing request."
				);
        	}
			else throw new ServletException(e);
		}
	}  // end doPost

	private static String doSomething(String param) throws ServletException, IOException {

		String bar;
		String guess = "ABC";
		char switchTarget = guess.charAt(1); // condition 'B', which is safe

		// Simple case statement that assigns param to bar on conditions 'A', 'C', or 'D'
		switch (switchTarget) {
		  case 'A':
		        bar = param;
		        break;
		  case 'B':
		        bar = "bob";
		        break;
		  case 'C':
		  case 'D':
		        bar = param;
		        break;
		  default:
		        bar = "bob's your uncle";
		        break;
		}

		return bar;
	}
}


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

    <artifactId>appengine-mapreduce-jruby</artifactId>
    <packaging>jar</packaging>

    <parent>
        <groupId>com.jetthoughts.appengine.tools</groupId>
        <artifactId>appengine-mapreduce-jruby-parent</artifactId>
        <version>0.0.5-SNAPSHOT</version>
    </parent>

    <properties>
        <gae.sdk.version>
            1.4.0
        </gae.sdk.version>
        <jruby.plugin.version>
            0.22.0
        </jruby.plugin.version>
    </properties>

    <url>http://github.com/pftg/appengine-mapreduce/</url>
    <inceptionYear>2010</inceptionYear>
    <licenses>
        <license>
            <name>Apache 2</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <dependencies>
        <dependency>
            <groupId>org.jruby</groupId>
            <artifactId>jruby-complete</artifactId>
            <version>${jruby.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-mapper</artifactId>
            <version>0.0.5-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-testing</artifactId>
            <version>${gae.sdk.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-api-stubs</artifactId>
            <version>${gae.sdk.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-api-1.0-sdk</artifactId>
            <version>${gae.sdk.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-api-labs</artifactId>
            <version>${gae.sdk.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <version>2.5.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymockclassextension</artifactId>
            <version>2.5.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-core</artifactId>
            <version>0.20.2-appengine</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>de.saumya.mojo</groupId>
                <artifactId>gemify-maven-plugin</artifactId>
                <version>${jruby.plugin.version}</version>
            </plugin>

            <plugin>
                <groupId>de.saumya.mojo</groupId>
                <artifactId>gem-maven-plugin</artifactId>
                <version>${jruby.plugin.version}</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <!--outputDirectory>${project.build.directory}</outputDirectory -->
                            <includeScope>compile</includeScope>
                            <excludeScope>test</excludeScope>
                            <excludeArtifactIds>
                                appengine-api-labs,appengine-api-1.0-sdk,jruby-complete,jetty,easymock,easymockclassextension
                            </excludeArtifactIds>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>bootstrap</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-scm-plugin</artifactId>
                        <groupId>org.apache.maven.plugins</groupId>
                        <executions>
                            <execution>
                                <id>resolve-appengine-mapper</id>
                                <phase>initialize</phase>
                                <goals>
                                    <goal>bootstrap</goal>
                                </goals>
                                <configuration>
                                    <goals>install</goals>
                                    <goalsDirectory>../../../appengine-mapreduce</goalsDirectory>
                                    <connectionUrl>
                                        scm:svn:http://appengine-mapreduce.googlecode.com/svn/trunk/java
                                    </connectionUrl>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>