text:
<!-- @import "[TOC]" {cmd="toc" depthFrom=1 depthTo=6 orderedList=false} -->
<!-- code_chunk_output -->

* [简介](#简介)
* [开发环境](#开发环境)
* [操作步骤](#操作步骤)
* [总结](#总结)
	* [使用的注解](#使用的注解)
    * [引入Vue](#引入vue)
	* [Thymeleaf引擎](#thymeleaf引擎)
	* [打包成war包](#打包成war包http582502041466002fanglewxtagblobmasterdocsproject_assetsspring_for_tomcatmd)
	* [启动工程](#启动工程)
    * [代码示例](#代码示例)

<!-- /code_chunk_output -->

## 简介
文章实现了spring与前端交互 ,读者能够学习spring通过Thymeleaf渲染发送给浏览器,Vue.js获取后端数据在浏览器上动态渲染页面

## 开发环境

* jdk 1.8
* gradle
* eclipse

## 操作步骤

* 新建gradle项目
    ```
    $ mkdir gradle-web

    Administrator@WIN-KH7USRS3HHQ MINGW64 /e
    $ cd gradle-web/

    Administrator@WIN-KH7USRS3HHQ MINGW64 /e/gradle-web
    $ gradle init --type java-application
    :wrapper
    :init

    BUILD SUCCESSFUL in 0s
    2 actionable tasks: 2 executed
    ```

* 导入gradle项目到eclipse,请参考:[文章](http://58.250.204.146:6002/fangle/wxtag/blob/master/docs/project_assets/import_gradle_proj.md);

* 删除默认新建的类和包。
    ![](assets/2017-09-30-11-46-35.png)

* 修改``build.gradle``
    ```
    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.7.RELEASE")
        }
    }

    apply plugin: 'java'
    apply plugin: 'eclipse'
    apply plugin: 'idea'
    apply plugin: 'org.springframework.boot'

    jar {
        baseName = 'gs-serving-web-content'
        version =  '0.1.0'
    }

    repositories {
        mavenCentral()
    }

    sourceCompatibility = 1.8
    targetCompatibility = 1.8

    dependencies {
        compile("org.springframework.boot:spring-boot-starter-thymeleaf")
        compile("org.springframework.boot:spring-boot-devtools")
        testCompile("junit:junit")
    }
    ```

* 点击项目->右键->gradle->refresh...刷新项目

* 创建控制类
    ``src/main/java/hello/GreetingController.java``
    ```java
    package hello;

    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;

    @Controller
    public class GreetingController {

        @RequestMapping("/greeting")
        public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
            model.addAttribute("name", name);
            return "greeting";
        }

    }
    ```
* 新建模板
    ``src/main/resources/templates/greeting.html``
    ```html
    <!DOCTYPE HTML>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Getting Started: Serving Web Content</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
        <p th:text="'Hello, ' + ${name} + '!'" />
    </body>
    </html>
    ```

* 修改eclipse的build path
    ![](assets/2017-09-30-11-37-56.png)

* 添加main类
    ``src/main/java/hello/Application.java``
    ```java
    package hello;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    @SpringBootApplication
    public class Application {

        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }

    }
    ```
* 添加home页面

    ``src/main/resources/static/index.html``
    ```html
    <!DOCTYPE HTML>
    <html>
    <head>
        <title>Getting Started: Serving Web Content</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
        <p>Get your greeting <a href="/greeting">here</a></p>
    </body>
    </html>
    ```

* 编译程序``./gradlew build``

* 执行程序``./gradlew bootRun``

* 查看效果
    * 首页
    ![](assets/2017-09-30-11-49-10.png)
    * 默认欢迎界面
    ![](assets/2017-09-30-11-49-41.png)
    * 指定name
    ![](assets/2017-09-30-11-50-16.png)

## 总结

### 使用的注解
* ``@Controller`` 标记类是Controller,然后使用``@RequestMapping`` 和``@RequestParam`` 等一些注解用以定义URL 请求和Controller 方法之间的映射,这样的Controller 就能被外界访问到
* ``@RestController``:与@Controller用法一致,不需要创建模板,一般用于前后端分离
* ``@RequestMapping`` 使用@RequestMapping 来映射URL 到控制器类,或者是到Controller 控制器的处理方法上。
* ``@RequestParam`` 绑定 HttpServletRequest 请求参数到控制器方法参数
    ```JAVA
        @RequestMapping(value = "/greeting",method = RequestMethod.GET)
        public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name,String password, Model model) throws JsonProcessingException {

            model.addAttribute("name", name);

            Map<String, String>bjson =new HashMap<String, String>();

            bjson.put("pname", name);
            bjson.put("password", password);
            json = mapper.writeValueAsString(bjson);

            System.out.println(json);
            return "greeting";
        }

    ```

### 引入Vue
  * 新建user.html文件 路径:``src/main/resources/template``

    在引入Vue.js
      ![](assets/spring/10.png)
    ```javascript
     <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.min.js"></script>
     <script src="//cdn.bootcss.com/vue-resource/1.0.3/vue-resource.min.js"></script>
    ```

  * Vue 双向数据绑定

     * 完整实例代码
     ```HTML
        <!DOCTYPE HTML>
        <html xmlns:th="http://www.thymeleaf.org">
        <head>
                <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"/>
                <title> Serving boot</title>
                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
                <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.min.js"></script>
                <script src="//cdn.bootcss.com/vue-resource/1.0.3/vue-resource.min.js"></script>
        </head>
            <body>
            <div id="datashow">
                <input v-model="data" />
                {{data}}
            </div>

            </body>
                <script th:inline="javascript">
                var showvm = new Vue({
                    el:'#datashow',
                    data:{
                        data:'',
                    }
                })
                </script>
        </html>
     ```
     * 新建html标签,输入与展示数据,指定id,v-model,v-model输入与展示data绑定一至
     ```html
        <div id="datashow">
        <input v-model="data" />
        {{data}}
        </div>
     ```
     * 在Vue里处理数据,new 一个Vue ,获取id(el:'#datashow'), 用data:{data''} ,响应v-model绑定的data,  用{{data}}展示showvm.data的数据

      ```javascript
        <script th:inline="javascript">
            var showvm = new Vue({
            el:'#datashow',
              data:{
                data:'',
            }
            })
        </script>
      ```

### Thymeleaf引擎

#### 从后端传输数据给前端

* 加配置在pom.xml中
```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
![](assets/spring/11.png)

* 给Model的addAttribut赋值 ``model.addAttribute("name", name);``
  ``src/main/java/hello/GreetingController.java``
    ```java
    package hello;

    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;

    @Controller
    public class GreetingController {

        @RequestMapping("/greeting")
        public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
            model.addAttribute("name", name);
            return "greeting";
        }

    }
    ```
    * 在界面通过Thymeleaf获取值: `` <p th:text="'Hello, ' + ${name} + '!'" /> ``
     ``th:text=${name}``,${name}绑定后台name

    ``src/main/resources/templates/greeting.html``
     ```html
      <!DOCTYPE HTML>
      <html xmlns:th="http://www.thymeleaf.org">
      <head>
            <title>Getting Started: Serving Web Content</title>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        </head>
        <body>
            <p th:text="'Hello, ' + ${name} + '!'" />
        </body>
        </html
     ````

    * 用js变量接收值,在script里添加:``th:inline="javascript"``
            ```
            <script th:inline="javascript">
            ```
    * 变量接收:``var name = [[${name}]]; ``
      示例代码:
      ```javascript
        <script th:inline="javascript">
        var name = [[${name}]];

        </script>
      ```
* 从前端传输数据给后端,写一个点击方法
    ```html
      <button id="logindiv" class="button" v-on:click="loginbtn" style="margin-top:20px">login in</button>
    ```

    ```javascript
        var logindiv = new Vue({
                el: '#logindiv',
                data: {
                    name: 'Vue.js'
                },
                // 在 `methods` 对象中定义loginbtn方法
                methods: {
                    loginbtn: function (event) {
                     this.$http.post("/greeting?",
                     {name:uservm.username,password:pswvm.password}

                    ).then(function (response) {

                    }).catch(function (response)
                    { console.error(response);  });

                    }
                }
            })
    ```

### [打包成war包](http://58.250.204.146:6002/fangle/wxtag/blob/master/docs/project_assets/spring_for_tomcat.md)

### 工程示例

* 工程截图
    ![](assets/spring/1.png)
* 新建控制类,在src/main/java,与启动文件同目录
    ![](assets/spring/2.png)
* 添加注释方法``@Controller``
    ![](assets/spring/3.png)
* url到控制器方法映射``@RequestMapping("/")``
    ```java
    @RequestMapping("/")
        public String index(Model model){
        return "index";
    }
    ````

* 在目录``src/main/resources``内新建``index.html``模板
    ```html
    <!DOCTYPE HTML>
    <html>
        <head>
        <title>Getting Started: Serving Web Content</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        </head>
    <body>
        <p>Get your greeting <a href="/greeting">here</a></p>
        <p>Get your greeting <a href="/user">login</a></p>
    </body>
    </html>
    ```

### 启动工程
   * 启动spring
    ![](assets/spring/7.png)

     右键启动类--> run as --> java Application
     浏览器输入``http://localhost:8080/`` (端口一般为``8080``)
     ![](assets/spring/9.png)

### 代码示例

* 前端完整代码:

```html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"/>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.min.js"></script>
    <script src="//cdn.bootcss.com/vue-resource/1.0.3/vue-resource.min.js"></script>
    <style type="text/css">
    body{
       text-align:center;
    }
    </style>
</head>
<body>
    <h2 style="margin-top:50px">LOGIN IN </h2>

    <div id="datashow">{{datashow}}</div>
    <input type="text" id="username" style="margin-top:30px" v-model="username" /><br></br>
    <input type="password" id="password" style="margin-top:15px" v-model="password"/><br></br>
    <button id="logindiv" class="button" v-on:click="loginbtn" style="margin-top:20px">login in</button>

</body>

	<script th:inline="javascript">

Vue.http.options.emulateJSON = true;
Vue.http.options.emulateHTTP = true;

  	var name = [[${name}]];
  	var user = [[${user}]];
  	<!-- 将后端传输过来的值展示在datashow -->
      var showvm = new Vue({
        el:'#datashow',
          data:{
            datashow:name,
          }
      })

<!-- 接受username值 -->
      var uservm = new Vue({
        el:'#username',
          data:{
              username:'',
          }
      })
<!-- 接受password值 -->
  var pswvm = new Vue({
    el:'#password',
    data:{
        password:'',
    }
  })

      var logindiv = new Vue({
       el: '#logindiv',
       data: {
       name: 'Vue.js'
      },
     // 在 `methods` 对象中定义方法
      methods: {
      loginbtn: function (event) {
      // `this` 在方法里指当前 Vue 实例
       <!-- 打印pswvm.password -->
       console.log(pswvm.password);

    <!-- 将name:uservm.username,password:pswvm.password传输到后台,调用greeting -->
   <!-- Vue post -->
    this.$http.post("/greeting?",
    		{name:uservm.username,password:pswvm.password}
       )
       .then(function (response) {
       }).catch(function (response)
        { console.error(response);
        });

     }
    }
   })
// 也可以用 JavaScript 直接调用方法
// logindiv.loginbtn() // => 'Hello Vue.js!'
  	</script>
</html>
```

* 后端完整代码:

```java
package com.example.springbootsamplehelloworld;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class GreetingController {

	 ObjectMapper mapper = new ObjectMapper();
     String json = "";

    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name,String password) throws JsonProcessingException {

   <!-- 接受前端传递过来的数据 -->
       	Map<String, String>bjson =new HashMap<String, String>();
    	bjson.put("name", name);
     	bjson.put("password", password);
        json = mapper.writeValueAsString(bjson);

   	    System.out.println(json);
        return "greeting";
    }

    @RequestMapping("/user")
    public String user(Model model){

    	User user = new User("nick","nick@qq.com");

    	model.addAttribute("user", user);
    	model.addAttribute("name", "elaine");

        return "user";
    }

    @RequestMapping("/")
    public String index(Model model){
        return "index";
    }

}
```

## 总结


text:
package services.jwt.authenticator

import authentikat.jwt.{JsonWebToken, JwtClaimsSet, JwtHeader}
import com.google.inject.Inject
import models._
import models.token.JwtToken
import org.json4s.DefaultFormats
import play.api.Configuration
import exception.InvalidJwtTokenException
import utils.Time

import scala.util.Try

class AuthentikatJwtAuthenticator @Inject()(configuration: Configuration)
  extends JwtAuthenticator {

  private val Secret = configuration.getString("auth.secret").get
  private val TokenDurationMilliseconds: Long = configuration.getLong("auth.tokendurationmillis").getOrElse(-1)
  private val header = JwtHeader(configuration.getString("auth.algorithm").get)

  private implicit val json4sFormats = DefaultFormats

  override def generateToken(user: User): JwtToken = {
    val issuedAt = Time.getUnixTimestampMilliseconds
    val userId = user.uuid
    val tokenId = UniqueIdGenerator.generate
    val claimsSet = JwtClaimsSet(Map(
      "userId" -> userId.uuid,
      "issuedAt" -> issuedAt,
      "tokenId" -> tokenId.uuid
    ))
    val token = JsonWebToken(header, claimsSet, Secret)
    JwtToken(issuedAt, tokenId, userId, token)
  }

  override def fromString(token: String): JwtToken = {
    val claims = token match {
      case JsonWebToken(_, claimsSet, _) => claimsSet.jvalue
      case _ => throw InvalidJwtTokenException("The given string doesn't seem to be a jwtToken")
    }
    val issuedAt = (claims \ "issuedAt").extractOrElse[Long](
      throw InvalidJwtTokenException("JWT token didn't have a 'issuedAt' field in it")
    )
    val tokenId = (claims \ "tokenId").extractOrElse[String](
      throw InvalidJwtTokenException("JWT token didn't have a 'tokenId' field in it")
    )
    val userId = (claims \ "userId").extractOrElse[String](
      throw InvalidJwtTokenException("JWT token didn't have a userId in it")
    )

    new JwtToken(issuedAt, UniqueId(tokenId), UniqueId(userId), token)
  }

  override def guardIsValid(jwtToken: JwtToken): Try[Unit] = Try {
    JsonWebToken.validate(jwtToken.token, Secret) match {
      case false => throw InvalidJwtTokenException("Invalid JWT Token")
      case true => guardIssuedAt(jwtToken.issuedAt)
    }
  }

  private def guardIssuedAt(issuedAt: Long) = {
    if (TokenDurationMilliseconds > 0L && issuedAt + TokenDurationMilliseconds < Time.getUnixTimestampMilliseconds)
      throw InvalidJwtTokenException("JWT token timed out")
  }
}

redpajama_set_name: RedPajamaGithub


text:
package sk.fei.mobv.pivarci.model;

import java.util.List;
import java.util.Map;

public class LocationEntity {
    private String version;
    private String generator;
    private Map<String, String> osm3s;
    private List<LocationItem> elements;

    public LocationEntity() {
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getGenerator() {
        return generator;
    }

    public void setGenerator(String generator) {
        this.generator = generator;
    }

    public Map<String, String> getOsm3s() {
        return osm3s;
    }

    public void setOsm3s(Map<String, String> osm3s) {
        this.osm3s = osm3s;
    }

    public List<LocationItem> getElements() {
        return elements;
    }

    public void setElements(List<LocationItem> elements) {
        this.elements = elements;
    }
}


text:
namespace Vidyano.WebComponents {
    "use strict";

    export interface IPersistentObjectDialogOptions {
        noHeader?: boolean;
        saveLabel?: string;
        save?: (po: Vidyano.PersistentObject, close: () => void) => void;
        cancel?: (close: () => void) => void;
    }

    @Dialog.register({
        properties: {
            persistentObject: Object,
            tab: {
                type: Object,
                computed: "_computeTab(persistentObject, isAttached)"
            },
            readOnly: {
                type: Boolean,
                computed: "_computeReadOnly(tab)"
            },
            saveLabel: {
                type: String,
                computed: "_computeSaveLabel(app)"
            },
            dialogActions: {
                type: Array,
                computed: "_computeDialogActions(persistentObject, app)"
            }
        },
        forwardObservers: [
            "persistentObject.isBusy"
        ],
        hostAttributes: {
            "dialog": ""
        },
        listeners: {
            "vi-persistent-object-tab-inner-size-changed": "_tabInnerSizeChanged"
        }
    })
    export class PersistentObjectDialog extends Dialog {
        private _saveHook: (po: Vidyano.PersistentObject) => Promise<any>;
        tab: Vidyano.PersistentObjectAttributeTab;

        constructor(public persistentObject: Vidyano.PersistentObject, private _options: IPersistentObjectDialogOptions = {}) {
            super();

            this.noHeader = _options.noHeader;
            persistentObject.beginEdit();
        }

        private async _save() {
            if (this._options.save)
                this._options.save(this.persistentObject, () => this.close(this.persistentObject));
            else {
                const wasNew = this.persistentObject.isNew;
                await this.persistentObject.save();

                if (StringEx.isNullOrWhiteSpace(this.persistentObject.notification) || this.persistentObject.notificationType !== NotificationType.Error) {
                    if (wasNew && this.persistentObject.ownerAttributeWithReference == null && this.persistentObject.stateBehavior.indexOf("OpenAfterNew") !== -1) {
                        try {
                            const po2 = await this.persistentObject.queueWork(() => this.app.service.getPersistentObject(this.persistentObject.parent, this.persistentObject.id, this.persistentObject.objectId));
                            this.app.service.hooks.onOpen(po2, true);
                            this.close(this.persistentObject);
                        }
                        catch (e) {
                            this.close(this.persistentObject);
                            const owner: ServiceObjectWithActions = this.persistentObject.ownerQuery || this.persistentObject.parent;
                            if (!!owner)
                                owner.setNotification(e);
                        }
                    }
                    else
                        this.close(this.persistentObject);
                }
            }
        }

        private _cancel() {
            if (this._options.cancel)
                this._options.cancel(() => this.cancel());
            else if (this.persistentObject) {
                this.persistentObject.cancelEdit();
                this.cancel();
            }
        }

        private _computeSaveLabel(app: Vidyano.WebComponents.App): string {
            if (!app)
                return null;

            return this._options.saveLabel || this.translateMessage("Save");
        }

        private _computeTab(persistentObject: Vidyano.PersistentObject, isAttached: boolean): Vidyano.PersistentObjectAttributeTab {
            if (!persistentObject || !isAttached)
                return null;

            const tab = <Vidyano.PersistentObjectAttributeTab>Enumerable.from(persistentObject.tabs).firstOrDefault(tab => tab instanceof Vidyano.PersistentObjectAttributeTab);
            tab.columnCount = tab.columnCount > 1 ? tab.columnCount : 1;

            const width = parseInt(this.getComputedStyleValue("--vi-persistent-object-dialog-base-width-base")) * tab.columnCount;
            this.customStyle["--vi-persistent-object-dialog-computed-width"] = `${width}px`;
            this.updateStyles();

            return tab;
        }

        private _computeReadOnly(tab: Vidyano.PersistentObjectAttributeTab): boolean {
            return !!tab && !tab.parent.isNew && !tab.attributes.some(attribute => !attribute.isReadOnly && attribute.isVisible);
        }

        private _computeDialogActions(persistentObject: Vidyano.PersistentObject): Vidyano.Action[] {
            return persistentObject.actions.filter(a => a.definition.showedOn.some(s => s === "Dialog"));
        }

        private _executeExtraAction(e: TapEvent) {
            const action = e.model.action as Vidyano.Action;
            if (!action.canExecute)
                return;

            action.execute();
        }

        private _onCaptureTab() {
            // Skip default tab navigation behavior
        }

        private _tabInnerSizeChanged(e: CustomEvent, detail: { size: ISize; }) {
            e.stopPropagation();

            if (!detail.size.height)
                return;

            this.$["main"].style.height = `${detail.size.height}px`;
            this._translateReset();
        }
    }
}


text:
package net.sourceforge.jwbf.mediawiki;

import javax.annotation.CheckForNull;

import net.sourceforge.jwbf.core.actions.ParamTuple;
import net.sourceforge.jwbf.core.actions.RequestBuilder;

public class ApiRequestBuilder extends RequestBuilder {

  public static final ParamTuple<String> NEW_CONTINUE = //
      new ParamTuple<>("continue", MediaWiki.urlEncode("-||"));

  public ApiRequestBuilder() {
    super(MediaWiki.URL_API);
  }

  public ApiRequestBuilder action(String action) {
    param("action", action);
    return this;
  }

  /** @deprecated prefer json format */
  @Deprecated
  public ApiRequestBuilder formatXml() {
    param("format", "xml");
    return this;
  }

  public ApiRequestBuilder formatJson() {
    param("format", "json");
    return this;
  }

  /**
   * https://www.mediawiki.org/wiki/API:Query#Continuing_queries
   *
   * @param version Continuing queries this way will only work with MW1_21 or higher
   */
  public ApiRequestBuilder paramNewContinue(@CheckForNull MediaWiki.Version version) {
    if (version != null && version.greaterEqThen(MediaWiki.Version.MW1_21)) {
      param(NEW_CONTINUE);
    }
    return this;
  }
}


text:
The primary contents of this document and source come from <http://lua-users.org/wiki/ExtensionProposal>.

# osprocess API

Note that all these functions return the standard (nil,"error message") on failure and that, unless otherwise specified, they return (true) on success.

## Environment

### osprocess.getenv(varname)

Returns the value of the process environment variable `varname` or `nil` if the variable is not defined.

    print(osprocess.getenv("PATH"))

### osprocess.setenv(varname, value)

Sets the environment variable `varname` to be `value`.  If `value` is `nil`, the environment variable is removed.  Note: The change occurs only within the currently running osprocess.

	print(osprocess.getenv("foo"))          -- Prints: nil
    print(osprocess.setenv("foo", "bar"))
	print(osprocess.getenv("foo"))          -- Prints: bar
    print(osprocess.setenv("foo", nil))
	print(osprocess.getenv("foo"))          -- Prints: nil

### env = osprocess.environ()

Returns a copy of the environment as a Lua table of key-value pairs.

    env = osprocess.environ()
    print(env.HOME)

-------------------------

### rd, wr = osprocess.pipe()

Create a pipe; 'rd' and 'wr' are Lua file objects.

----------------

## Process control

### osprocess.sleep(seconds)
### osprocess.sleep(interval, unit)

Suspends program execution for interval/unit seconds; 'unit' defaults to 1 and either argument can be floating point. The particular sub-second precision is implementation-defined.

    osprocess.sleep(3.8) -- sleep for 3.8 seconds
    local microseconds = 1e6
    osprocess.sleep(3800000, microseconds) -- sleep for 3800000 µs
    local ticks = 100
    osprocess.sleep(380, ticks) -- sleep for 380 ticks

### proc = osprocess.spawn(filename)
### proc = osprocess.spawn{filename, [args-opts]}
### proc = osprocess.spawn{command=filename, [args-opts]}

Creates a child osprocess.

`filename` names a program. If the (implementation-defined) pathname is not absolute, the program is found through an implementation-defined search method (the PATH environment variable on most systems).

If specified, [args-opts] is one or more of the following keys:

* `[1]..[n]=` - the command line arguments
* `args=` - an array of command line arguments
* `env=` - a table of environment variables
* `stdin=`, `stdout=`, `stderr=` - io.file objects for standard input, output, and error respectively
* `shell=` - Set to `true` if this is a shell application.  Set to `false` if this is a GUI application.  Defaults to `true`.
* `show=` - Set to `true` to show the application.  Set to `false` to hide it.  Defaults to `true`.
* `detach=` - Set to `true` to detach the application from the parent.  Defaults to `true`.
* `suspended=` - Set to `true` to start the spawned application as suspended, requiring a call to `os.resume(process)` to resume the application.  Defaults to `false`.
* `can_terminate=` - Set to `true` to start the application in such a way that it is part of the current process's process tree and can be terminated.  Defaults to `false`.

It is an error if both integer keys and an 'args' key are specified.

An implementation may provide special behavior if a zeroth argument (options.args[0] or options[0]) is provided.

The returned 'proc' userdatum has the method `wait()`.

    -- run the echo command
    proc = osprocess.spawn"/bin/echo"
    proc = osprocess.spawn{"/bin/echo", "hello", "world"}
    proc = osprocess.spawn{command="/bin/echo", "hello", "world"}

    -- run the id command
    vars = { LANG="fr_FR" }
    proc = osprocess.spawn{"/bin/id", "-un", env=vars}
    proc = osprocess.spawn{command="/bin/id", "-un", env=vars)

    -- Useless use of cat
    local rd, wr = assert(osprocess.pipe())
    local proc = assert(osprocess.spawn("/bin/cat", {stdin=rd}))
    rd:close()
    wr:write("Hello world\n")
    wr:close()
    proc:wait()

    -- Run a program with a modified environment
    local env = osprocess.environ()
    env.LUA_PATH = "/usr/share/lib/lua/?.lua"
    env.LUA_CPATH = "/usr/share/lib/lua/?.so"
    local proc = assert(osprocess.spawn("lua", {args = {"-e", 'print"Hello world\n"'}, env=env }))
    proc:wait()

    -- popen2()
    function popen2(...)
        local in_rd, in_wr = osprocess.pipe()
        local out_rd, out_wr = osprocess.pipe()
        local proc, err = osprocess.spawn{stdin = in_rd, stdout = out_wr, ...}
        in_rd:close(); out_wr:close()
        if not proc then
            in_wr:close(); out_rd:close()
            return proc, err
        end
        return proc, out_rd, in_wr
    end

    -- usage:
    local p, i, o = assert(popen2("wc", "-w"))
    o:write("Hello world"); o:close()
    print(i:read"*l"); i:close()
    p:wait()

### osprocess.terminate(process)

Terminates a spawned process, if possible.

If `process` is a number or light userdata, `process` is expected to represent the Windows job the process tree was created under.

Otherwise, `process` should be a table with the entries from `proc:getinfo()`.

### info = proc:getinfo()

Returns information about the spawned osprocess.

On Windows, a table structure is returned with the following members:

* `process_handle` - Light userdata representing the Windows process HANDLE.
* `thread_handle` - Light userdata representing the Windows thread HANDLE.
* `process_id` - An integer representing the Windows process ID.
* `thread_id` - An integer representing the Windows thread ID.
* `job` - Light userdata representing the Windows job HANDLE if the process was created with `can_terminate = true`.

### proc:resume()

Resumes a suspended osprocess.

### exitcode = proc:wait()

Wait for child process termination; 'exitcode' is the code returned by the child osprocess.

### osprocess.collectlines{filename, [args-opts]}
### osprocess.collectlines{command=filename, [args-opts]}

Returns a table of all output from the new process's stdout.

See `osprocess.spawn()` for additional information.

### osprocess.lines{filename, [args-opts]}
### osprocess.lines{command=filename, [args-opts]}

Returns an iterator that reads the new process's stdout line by line.

See `osprocess.spawn()` for additional information.

### proc, input = osprocess.popen{filename, [args-opts]}
### proc, input = osprocess.popen{command=filename, [args-opts]}

Creates a child process with the process's stdout redirected to be read from `input`.

See `osprocess.spawn()` for additional information.

### proc, input, output = osprocess.popen2{filename, [args-opts]}
### proc, input, output = osprocess.popen2{command=filename, [args-opts]}

Creates a child process with the process's stdout redirected to be read from `input` and the process's stdin redirected to be written to through `output`.

See `osprocess.spawn()` for additional information.

### args = osprocess.parsecommandline(commandline)

Parses a single string command line into a table of arguments suitable for passing to `osprocess.spawn`.

    args = osprocess.parsecommandline('dir "c:\\Program Files\\"')


text:
class AngelScript < ZipAndCmakeDLDep
  def initialize(args)
    super('AngelScript', 'angelscript', args, zipType: :p7zip)

    self.HandleStandardCMakeOptions

    # Revision
    @Version ||= 2547

    # Only hashes change with different versions
    case @Version
    when 2482
      @DLHash = '2138306e4a9ec36070b2be9adcb64d39b76aad392a36d1d15bb05a92f516f211'
    when 2547
      @DLHash = '7d1ace2eeabd1554684bfa514e8cbb79656a8bf9b8397de46328b80b21693409'
    else
      onError "unknown AngelScript version (RubySetupSystem doesn't know about: " +
              @Version + ')'
    end

    # sha3
    @DLHashType = 2
    @DownloadURL = "https://boostslair.com/rubysetupsystem/deps/angelscript_#{@Version}.7z"
    @CMakeListFolder = '../sdk/angelscript/projects/cmake/'
    @LocalFileName = "angelscript_#{@Version}.7z"
    @UnZippedName = 'angelscript'
    @LocalPath = File.join(CurrentDir, @LocalFileName)

    # For packaging
    @RepoURL = @DownloadURL
  end

  def DoInstall
    # Copy files to the install target folder
    installer = CustomInstaller.new(@InstallPath,
                                    File.join(@Folder, 'sdk/angelscript/include'))

    # First header files and libs
    installer.addInclude(File.join(@Folder, 'sdk/angelscript/include', 'angelscript.h'))

    # The library
    if OS.linux?

      installer.addLibrary File.join(@Folder, 'build/', 'libangelscript.a')

    elsif OS.windows?
      # TODO: bitness
      installer.addLibrary File.join(@Folder, "build/#{CMakeBuildType}", 'angelscript.lib')
    else
      onError 'Unkown OS'
    end

    installer.run

    # Then the addons
    installer = CustomInstaller.new(@InstallPath,
                                    File.join(@Folder, 'sdk/add_on/'))

    installer.IncludeFolder = 'include/add_on'

    # All the addons from
    # `ls -m | awk 'BEGIN { RS = ","; ORS = ", "}; NF { print "\""$1"\""};'`
    addonnames = Array[
      'autowrapper', 'contextmgr', 'datetime', 'debugger', 'scriptany', 'scriptarray',
      'scriptbuilder', 'scriptdictionary', 'scriptfile', 'scriptgrid', 'scripthandle',
      'scripthelper', 'scriptmath', 'scriptstdstring', 'serializer', 'weakref'
    ]

    addonnames.each do |x|
      installer.addInclude File.join(@Folder, 'sdk/add_on/', x)
    end

    installer.run

    true
  end

  def getInstalledFiles
    if OS.windows?
      [
        'lib/angelscript.lib',
        'include/angelscript.h',
        'include/add_on'
      ]
    elsif OS.linux?
      [
        'lib/libangelscript.a',
        'include/angelscript.h',
        'include/add_on'
      ]
    end
  end
end


text:
package cn.com.expense.eps.sys.service.facade;

import java.util.List;

import cn.com.expense.eps.model.EpsPayWay;
import ins.framework.common.Page;
import ins.framework.common.QueryRule;

public interface PayWayService {
	public Page findPayWay(QueryRule queryRule, int pageNo,int pageSize);
	public void addPayWay(EpsPayWay epsPayWay);
	public void deletePayWayByPK(String payWayCode);
	public EpsPayWay findPayWayByPK(String payWayCode);
	public void updatePayWay(EpsPayWay epsPayWay);
	public EpsPayWay getPayWay(QueryRule queryRule);
	public List<EpsPayWay> findPayWayByQuerRule(QueryRule queryRule);
}


text:
from celery import shared_task
from django.conf import settings
from django.core.mail import send_mail

from . import models

@shared_task(name='waldur_mastermind.notifications.send_notification_email')
def send_notification_email(notification_uuid):
    notification = models.Notification.objects.get(uuid=notification_uuid)
    for email in notification.emails:
        send_mail(
            notification.subject,
            notification.body,
            settings.DEFAULT_FROM_EMAIL,
            [email],
            fail_silently=True,
        )


text:
ITEM.name = "Золотой самородок"
ITEM.desc = "Кусок блестящего золота."
ITEM.model = "models/props_tes/items/goldnugget.mdl"
ITEM.Width = 1
ITEM.Height = 1
ITEM.permit = "mat"


text: Requires **Python 3.5.1** and the latest **pygame** to be installed


text:
[repowatcher](http://www.repowatcher.com/)
==========================================

About
--------------------------------------

Simplistic site to improve the way we can organise our saved repositories and keep up-to-date with important changes.
Also consolidates code from various online hosting services for ease of use.


text:
//
//  GJPhotosViewController.m
//  GJAssetsPickerViewController
//
//  Created by ZYVincent on 14-9-8.
//  Copyright (c) 2014年 ZYProSoft. All rights reserved.
//

#import "GJCFPhotosViewController.h"
#import "GJCFAssetsPickerViewController.h"
#import "GJCFAssetsPreviewController.h"
#import "GJCFUitils.h"

@interface GJCFPhotosViewController ()<GJCFAssetsPreviewControllerDelegate>

@property (nonatomic,strong)UIImageView *customBottomToolBar;
@property (nonatomic,strong)UIButton *finishDoneBtn;

@end

@implementation GJCFPhotosViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.colums = 4;//默认行数
        self.mutilSelectLimitCount = 0;//默认不限制选择张数
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.assetsTable = [[UITableView alloc]init];
    self.assetsTable.frame = (CGRect){0,0,self.view.frame.size.width,self.view.frame.size.height};
    [self.view addSubview:self.assetsTable];
    self.assetsTable.delegate = self;
    self.assetsTable.dataSource = self;
    [self.assetsTable setAllowsSelection:NO];
    [self.assetsTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];

    self.assetsArray = [[NSMutableArray alloc]init];

    [self setupStyle];

    [self setupPhotos];

    /* 会有默认选中状态的照片,所以初始完照片数据源就更新一下标题 */
    [self updateFinishDoneBtnTitle];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    /* 主动更新状态 */
    [self.assetsTable reloadData];
}

#pragma mark - 设置外观
// 外观
- (GJCFAssetsPickerStyle *)defaultStyle
{
    GJCFAssetsPickerStyle *defaultStyle = nil;
    if (self.delegate && [self.delegate respondsToSelector:@selector(photoViewControllerShouldUseCustomStyle:)]) {
        defaultStyle = [self.delegate photoViewControllerShouldUseCustomStyle:self];
    }else{
        defaultStyle = [GJCFAssetsPickerStyle defaultStyle];
    }
    return defaultStyle;
}

// 设置外观
- (void)setupStyle{

    GJCFAssetsPickerStyle *defaultStyle = [self defaultStyle];
    self.colums = defaultStyle.numberOfColums;

    //navigationBar 背景
    if (defaultStyle.sysPhotoNavigationBarDes.backgroundColor) {
        UIImage *colorImage = [GJCFAssetsPickerConstans imageForColor:defaultStyle.sysPhotoNavigationBarDes.backgroundColor withSize:CGSizeMake(self.view.frame.size.width,64)];
        [self.navigationController.navigationBar setBackgroundImage:colorImage forBarMetrics:UIBarMetricsDefault];
    }
    if (defaultStyle.sysPhotoNavigationBarDes.backgroundImage) {
        [self.navigationController.navigationBar setBackgroundImage:defaultStyle.sysPhotoNavigationBarDes.backgroundImage forBarMetrics:UIBarMetricsDefault];
    }

    //标题
    UILabel *titleLabel = [[UILabel alloc]init];
    [titleLabel setCommonStyleDescription:defaultStyle.sysPhotoNavigationBarDes];
    if (!self.title) {
        self.title = defaultStyle.sysPhotoNavigationBarDes.title;
    }
    self.navigationItem.titleView = titleLabel;
    self.title = titleLabel.text;
    titleLabel = nil;

    //返回上一级
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setCommonStyleDescription:defaultStyle.sysBackBtnDes];
    NSArray *viewControllers = self.navigationController.viewControllers;
    UIViewController *backToViewController = [viewControllers objectAtIndex:(viewControllers.count-2)];\
    [backBtn setTitle:backToViewController.title forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];

    //设置返回Item
    UIBarButtonItem *backBarItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backBarItem;
    backBarItem = nil;

    //取消返回
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setCommonStyleDescription:defaultStyle.sysCancelBtnDes];
    //响应事件
    [cancelBtn addTarget:self action:@selector(dismissPickerViewController) forControlEvents:UIControlEventTouchUpInside];

    //设置Item
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc]initWithCustomView:cancelBtn];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    rightBarItem = nil;

    //设置底部工具栏的样式
    self.customBottomToolBar = [[UIImageView alloc]init];
    self.customBottomToolBar.userInteractionEnabled = YES;
    if ([self.navigationController.navigationBar backgroundImageForBarMetrics:UIBarMetricsDefault]) {
        self.customBottomToolBar.frame = CGRectOffset(self.view.frame,0,self.view.frame.size.height - defaultStyle.sysPreviewBottomToolBarDes.frameSize.height-64);
        //调整assetsTable的高度适应
        CGFloat delta = [GJCFAssetsPickerConstans isIOS7]? 64:44;
        self.assetsTable.frame = (CGRect){0,0,self.view.frame.size.width,self.view.frame.size.height-defaultStyle.sysPhotoBottomToolBarDes.frameSize.height-delta};
    }else{
        self.customBottomToolBar.frame = CGRectOffset(self.view.frame,0,self.view.frame.size.height - defaultStyle.sysPreviewBottomToolBarDes.frameSize.height);
    }
    self.customBottomToolBar.backgroundColor = defaultStyle.sysPhotoBottomToolBarDes.backgroundColor;
    self.customBottomToolBar.image = defaultStyle.sysPhotoBottomToolBarDes.backgroundImage;
    [self.view addSubview:self.customBottomToolBar];

    //设置预览按钮
    UIButton *previewBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [previewBtn setCommonStyleDescription:defaultStyle.sysPreviewBtnDes];
    [self.customBottomToolBar addSubview:previewBtn];
    [previewBtn addTarget:self action:@selector(previewSelectedPhotos) forControlEvents:UIControlEventTouchUpInside];

    //设置完成按钮
    self.finishDoneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.finishDoneBtn setCommonStyleDescription:defaultStyle.sysFinishDoneBtDes];
    [self.customBottomToolBar addSubview:self.finishDoneBtn];
    [self.finishDoneBtn addTarget:self action:@selector(finishSelectImage) forControlEvents:UIControlEventTouchUpInside];
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dismissPickerViewController
{
    [GJCFAssetsPickerConstans postNoti:kGJAssetsPickerNeedCancelNoti];
}

- (void)previewSelectedPhotos
{
    if ([self totalSelectedAssets].count <= 0) {
        [GJCFAssetsPickerConstans postNoti:kGJAssetsPickerRequirePreviewButNoSelectPhotoTipNoti];
        return;
    }

    GJCFAssetsPreviewController *previewController = [[GJCFAssetsPreviewController alloc]initWithAssets:[self totalSelectedAssets]];
    previewController.previewDelegate = self;
    previewController.pageIndex = 0;
    previewController.mutilSelectLimitCount = self.mutilSelectLimitCount;
    [self.navigationController pushViewController:previewController animated:YES];
}

- (void)finishSelectImage
{
    [GJCFAssetsPickerConstans postNoti:kGJAssetsPickerDidFinishChooseMediaNoti withObject:[self totalSelectedAssets]];
}

#pragma mark - 帮助图片分组方法

- (void)seprateAssetsGroup:(NSMutableArray *)aGroupArray withStartIndex:(NSInteger)sIndex withLength:(NSInteger)length
{
    //非法参数
    if (length == 0 || sIndex < 0 || !aGroupArray || aGroupArray.count == 0) {
        return;
    }

    //如果一开始就取不到足够数量的照片
    if (aGroupArray.count-1 < sIndex+length) {

        length = aGroupArray.count-sIndex > length? length:aGroupArray.count-sIndex;

        NSArray * subArray = [aGroupArray subarrayWithRange:NSMakeRange(sIndex,length)];

        [self.assetsArray addObject:[NSMutableArray arrayWithArray:subArray]];

        return;
    }

    NSArray *subArray = [aGroupArray subarrayWithRange:NSMakeRange(sIndex, length)];

    [self.assetsArray addObject:[NSMutableArray arrayWithArray:subArray]];

    //重新设置游标位置
    sIndex = sIndex+length;

    //如果还有足够可以取成length数量的照片
    if (aGroupArray.count-1>= sIndex+length) {

        [self seprateAssetsGroup:aGroupArray withStartIndex:sIndex withLength:length];

    }else{

        NSArray *subArray = [aGroupArray subarrayWithRange:NSMakeRange(sIndex, aGroupArray.count-sIndex)];

        [self.assetsArray addObject:[NSMutableArray arrayWithArray:subArray]];
    }
}

- (void)setupPhotos
{
    /* 判断传过来的相册对象有没有已经枚举好的照片 */
    if (self.albums.assetsArray && self.albums.assetsArray.count > 0) {

        [self.assetsArray addObjectsFromArray:self.albums.assetsArray];

        [self.assetsTable reloadData];

        return;
    }

    if (self.albums.assetsGroup && self.assetsTable) {

        NSMutableArray *tempAssetsArray = [NSMutableArray array];
        [self.albums.assetsGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {

            /* 枚举的时候发现多了一个,这个是系统方法出现的问题,所以我们先判断这个result有没有 */
            if (result) {

                GJCFAsset *asset = [[GJCFAsset alloc]initWithAsset:result];
                asset.selected = NO;

                [tempAssetsArray addObject:asset];

            }

        }];

        [self seprateAssetsGroup:tempAssetsArray withStartIndex:0 withLength:self.colums];

        /* 枚举完了的时候,可以调用代理来更新对应相册的数据 */
        if (self.delegate && [self.delegate respondsToSelector:@selector(photoViewController:didFinishEnumrateAssets:forAlbums:)]) {
            [self.delegate photoViewController:self didFinishEnumrateAssets:self.assetsArray forAlbums:self.albums];
        }

        [self.assetsTable reloadData];
        /* 相册默认滚动到底部 */
        CGFloat bottomStartOffsetY = self.assetsTable.contentSize.height - self.assetsTable.frame.size.height;
        [self.assetsTable scrollRectToVisible:CGRectOffset(self.assetsTable.frame, 0, bottomStartOffsetY)  animated:NO];
    }

}

#pragma mark - tableView delegate and dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.assetsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier";
    GJCFAssetsPickerCell *cell = (GJCFAssetsPickerCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
        cell = [[GJCFAssetsPickerCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.delegate = self;

        /* 设定cell需要的风格配置 */
        GJCFAssetsPickerStyle *defaultStyle = [self defaultStyle];
        cell.overlayViewClass = defaultStyle.sysOverlayViewClass;
        cell.columSpace = defaultStyle.columSpace;
        cell.enableBigImageShowAction = defaultStyle.enableBigImageShowAction;
        cell.colums = self.colums;
    }

    [cell setAssets:[self.assetsArray objectAtIndex:indexPath.row]];

    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.assetsTable.frame.size.width/self.colums;
}

#pragma mark - 计算已经选中的图片数量
- (NSArray *)totalSelectedAssets
{
    NSMutableArray *selectedArray = [NSMutableArray array];
    [self.assetsArray enumerateObjectsUsingBlock:^(NSArray *subArray, NSUInteger idx, BOOL *stop) {

        [subArray enumerateObjectsUsingBlock:^(GJCFAsset *asset, NSUInteger idx, BOOL *stop) {

            if (asset.selected) {
                [selectedArray addObject:asset];
            }

        }];

    }];

    return selectedArray;
}

- (void)updateFinishDoneBtnTitle
{
    GJCFAssetsPickerStyle *defaultStyle = [self defaultStyle];
    NSString *newTitle = [NSString stringWithFormat:@"%@(%lu)",defaultStyle.sysFinishDoneBtDes.normalStateTitle,(unsigned long)[self totalSelectedAssets].count];

    [self.finishDoneBtn setTitle:newTitle forState:UIControlStateNormal];
}

#pragma mark - GJAssetsPickerCell delegate
- (void)assetsPickerCell:(GJCFAssetsPickerCell *)assetsPickerCell didChangeStateAtIndex:(NSInteger)index withState:(BOOL)isSelected
{
    //更新数据源的状态
    NSIndexPath *indexPath = [self.assetsTable indexPathForCell:assetsPickerCell];
    NSMutableArray *subArray = [self.assetsArray objectAtIndex:indexPath.row];
    GJCFAsset *asset = [subArray objectAtIndex:index];
    asset.selected = isSelected;

    [subArray replaceObjectAtIndex:index withObject:asset];
    [self.assetsArray replaceObjectAtIndex:indexPath.row withObject:subArray];

    //更新完成操作按钮标题
    [self updateFinishDoneBtnTitle];
}

- (BOOL)assetsPickerCell:(GJCFAssetsPickerCell *)assetsPickerCell shouldChangeToSelectedStateAtIndex:(NSInteger)index
{
    //默认没有限制
    if (self.mutilSelectLimitCount==0) {
        return YES;
    }

    NSInteger totalSelectCount = [self totalSelectedAssets].count;

    if (totalSelectCount>=self.mutilSelectLimitCount) {

        dispatch_async(dispatch_get_main_queue(), ^{

            [GJCFAssetsPickerConstans postNoti:kGJAssetsPickerPhotoControllerDidReachLimitCountNoti withObject:[NSNumber numberWithInteger:self.mutilSelectLimitCount]];

        });

        return NO;

    }else{
        return YES;
    }
}

/* 进入大图查看模式 */
- (void)assetsPickerCell:(GJCFAssetsPickerCell *)assetsPickerCell shouldBeginBigImageShowAtIndex:(NSInteger)index
{
    /* 将所有的照片组成新的组传递 */
    NSMutableArray *allAssets = [NSMutableArray array];
    [self.assetsArray enumerateObjectsUsingBlock:^(NSArray *subArray, NSUInteger idx, BOOL *stop) {

        [subArray enumerateObjectsUsingBlock:^(GJCFAsset *asset, NSUInteger idx, BOOL *stop) {

            [allAssets addObject:asset];
        }];
    }];

    /* 转化成实际的索引 */
    NSIndexPath *indexPath = [self.assetsTable indexPathForCell:assetsPickerCell];
    NSInteger totalIndex = indexPath.row * self.colums + index;

    GJCFAssetsPreviewController *previewController = [[GJCFAssetsPreviewController alloc]initWithAssets:allAssets];
    previewController.previewDelegate = self;
    previewController.pageIndex = totalIndex;
    previewController.mutilSelectLimitCount = self.mutilSelectLimitCount;
    [self.navigationController pushViewController:previewController animated:YES];
}

#pragma mark - GJAssetsPickerPreviewControllerDelegate
- (GJCFAssetsPickerStyle *)previewControllerShouldCustomStyle:(GJCFAssetsPreviewController *)previewController
{
    return [self defaultStyle];
}

- (void)previewController:(GJCFAssetsPreviewController *)previewController didUpdateAssetSelectedState:(GJCFAsset *)asset
{
    __block NSUInteger indexPath = 0;
    __block NSUInteger subIndex = 0;

    [self.assetsArray enumerateObjectsUsingBlock:^(NSArray *subArray, NSUInteger rowIndex, BOOL *rowStop) {

        [subArray enumerateObjectsUsingBlock:^(GJCFAsset *sAsset, NSUInteger idx, BOOL *stop) {

            if ([sAsset isEqual:asset]) {

                indexPath = rowIndex;
                subIndex = idx;

                *rowStop = YES;
                *stop = YES;
            }
        }];

    }];

    //更新数据源的状态
    NSMutableArray *subArray = [self.assetsArray objectAtIndex:indexPath];
    GJCFAsset *theAsset = [subArray objectAtIndex:subIndex];
    theAsset.selected = asset.selected;

    [subArray replaceObjectAtIndex:subIndex withObject:theAsset];
    [self.assetsArray replaceObjectAtIndex:indexPath withObject:subArray];

    //更新完成操作按钮标题
    [self updateFinishDoneBtnTitle];

}

@end


text:
Imports System
Imports System.Reflection

Namespace ROSObjects.IP

    <RObj(BaseCommand:="/ip address")>
    Public Class Address

        <RObj(ROSName:="ip")>
        Public Property Address As _IPAddress

    End Class

End Namespace


text:
<?php

namespace Lechimp\Dicto\Variables;

class Methods extends Entities
{
    /**
     * @inheritdoc
     */
    public function id()
    {
        return Variable::METHOD_TYPE;
    }

    /**
     * @inheritdoc
     */
    public function meaning()
    {
        return "methods";
    }
}


text:
<?php
namespace Expresso\MailBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class FolderController extends Controller
{
    public function ListFoldersAction($folder = 'INBOX')
    {

        $imap = $this->get('ExpressoImap');
        $imap->openMailbox($folder);
        $folders =  $imap->getMailBoxes();

        $return = array();
        foreach($folders as $i => $folder)
        {
            $iFolder = array();
            $iFolder['id'] = mb_convert_encoding( str_replace( $folder->delimiter , '.', substr($folder->name,(strpos($folder->name , '}') + 1))) , 'UTF-8' , 'UTF7-IMAP' ) ;
            $explodeName = explode( '.' , $iFolder['id']);
            $iFolder['cn'] = array_pop($explodeName);
            $iFolder['parentFolder'] = implode('.' , $explodeName) == 'INBOX' ? '' : implode('.' , $explodeName);

            $status = $imap->status(substr($folder->name,(strpos($folder->name , '}') + 1)));
            $iFolder['status']['Messages'] = $status->messages;
            $iFolder['status']['Recent'] = $status->recent;
            $iFolder['status']['Unseen'] = $status->unseen;
            $iFolder['status']['UIDnext'] = $status->uidnext;
            $iFolder['status']['UIDvalidity'] = $status->uidvalidity;

            $return[] = $iFolder;
        }

        $newReturn = array();

        foreach ($imap->getDefaultFolders() as $i => $v)
        {
            foreach ($return as $ii => $vv)
            {
                if($vv['cn'] == $v)
                {
                   $vv['cn'] = $this->get('translator')->trans($vv['cn']);
                   unset($return[$ii]);
                   $newReturn[] = $vv;
                }
            }
        }

        $response = new Response( json_encode( array_merge ($newReturn , $return) ) );
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function createFolderAction(){
        $request = Request::createFromGlobals();
        $imap = $this->get('ExpressoImap');
        $imap->openMailbox();
        $response = new Response();
        if($imap->createFolder($request->request->get('folder'))){
            $response->headers->set('Content-Location', '/rest/Mail/Folder/'.$request->request->get('folder'));
            $response->setStatusCode(201);
        }else{
            $response->setContent($this->get('translator')->trans(imap_last_error()));
            $response->setStatusCode(400);
        }
        return $response;
    }

    public function editFolderAction($folder){
        $imap = $this->get('ExpressoImap');
        $imap->openMailbox();

        $put_str = $this->getRequest()->getContent();
        parse_str($put_str, $_PUT);

        $response = new Response();
        if($imap->editFolder($folder,$_PUT['folder'])){
            $response->setStatusCode(204);
            $response->headers->set('Content-Location', '/rest/Mail/Folder/'.$_PUT['folder']);
        }else{
            $response->setContent($this->get('translator')->trans(imap_last_error()));
            $response->setStatusCode(500);
        }
        return $response;
    }

    public function deleteFolderAction($folder){
        $imap = $this->get('ExpressoImap');
        $imap->openMailbox();
        $response = new Response();
        if($imap->deleteFolder($folder)){
            $response->setStatusCode(204);
        }else{
            $response->setContent($this->get('translator')->trans(imap_last_error()));
            $response->setStatusCode(500);
        }
        return $response;
    }

    public function getFolderAction($folder){
        $request = Request::createFromGlobals();
        $imap = $this->get('ExpressoImap');
        $imap->openMailbox();
        $response = new Response();
        if($imap->deleteFolder($folder)){
            $response->setStatusCode(204);
        }else{
            $response->setContent($this->get('translator')->trans(imap_last_error()));
            $response->setStatusCode(500);
        }
        return $response;
    }
}


text:
\hypertarget{dir_4a3e42a91b72a329d42e3402f9afd72e}{\section{Highway.\-Data.\-Entity\-Framework.\-Structure\-Map.\-Example/ Directory Reference}
\label{dir_4a3e42a91b72a329d42e3402f9afd72e}\index{Highway.\-Data.\-Entity\-Framework.\-Structure\-Map.\-Example/ Directory Reference@{Highway.\-Data.\-Entity\-Framework.\-Structure\-Map.\-Example/ Directory Reference}}
}
\subsection*{Directories}
\begin{DoxyCompactItemize}
\item
directory \hyperlink{dir_48524cafc800cde92660323dbe8903af}{Domain}
\item
directory \hyperlink{dir_7b068e9e7e7547c83c5691a3047e61f8}{obj}
\item
directory \hyperlink{dir_647110b45170f9e38a929e668710ea98}{Properties}
\item
directory \hyperlink{dir_2c025376426c377c51b24290992cdc84}{Queries}
\end{DoxyCompactItemize}
\subsection*{Files}
\begin{DoxyCompactItemize}
\item
file {\bfseries Demo\-Application.\-cs}
\item
file {\bfseries Highway\-Data\-Mappings.\-cs}
\item
file {\bfseries Program.\-cs}
\end{DoxyCompactItemize}


text:
namespace WebAssembly.Instructions;

/// <summary>
/// Signed less than.
/// </summary>
public class Int32LessThanSigned : ValueTwoToOneInstruction
{
    /// <summary>
    /// Always <see cref="OpCode.Int32LessThanSigned"/>.
    /// </summary>
    public sealed override OpCode OpCode => OpCode.Int32LessThanSigned;

    private protected sealed override WebAssemblyValueType ValueType => WebAssemblyValueType.Int32;

    private protected sealed override System.Reflection.Emit.OpCode EmittedOpCode =>
        System.Reflection.Emit.OpCodes.Clt;

    /// <summary>
    /// Creates a new  <see cref="Int32LessThanSigned"/> instance.
    /// </summary>
    public Int32LessThanSigned()
    {
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layout>
    <data>
        <variable
            name="configuration"
            type="cz.zcu.fav.remotestimulatorcontrol.model.configuration.AConfiguration" />
    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorERP"
        android:elevation="16dp">

        <TextView
            android:id="@+id/text_configuration_type"
            android:layout_width="96dp"
            android:layout_height="96dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="16dp"
            android:background="@{configuration.configurationType}"
            android:gravity="center"
            android:text="@{configuration.configurationType}"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"
            android:transitionName="transition_configuration_type"
            app:valid="@{configuration.valid}" />

        <TextView
            android:id="@+id/text_configuration_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:gravity="center_horizontal"
            android:text="@{configuration.name}"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"/>

    </LinearLayout>
</layout>


text:
<?php

declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

class Favorites extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('favorites');
        $table->addColumn('admin_user_id', 'integer')
            ->addColumn('talk_id', 'integer')
            ->addColumn('created', 'datetime')
            ->create();
    }

    /**
     * Migrate Up.
     */
    public function up()
    {
    }

    /**
     * Migrate Down.
     */
    public function down()
    {
    }
}


text:
package org.opensplice.cm.transform.xml;

import java.io.IOException;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.opensplice.cm.Time;
import org.opensplice.cm.qos.DeadlinePolicy;
import org.opensplice.cm.qos.DurabilityKind;
import org.opensplice.cm.qos.DurabilityPolicy;
import org.opensplice.cm.qos.DurabilityServicePolicy;
import org.opensplice.cm.qos.EntityFactoryPolicy;
import org.opensplice.cm.qos.GroupDataPolicy;
import org.opensplice.cm.qos.HistoryPolicy;
import org.opensplice.cm.qos.HistoryQosKind;
import org.opensplice.cm.qos.InvalidSampleVisibilityKind;
import org.opensplice.cm.qos.LatencyPolicy;
import org.opensplice.cm.qos.LifespanPolicy;
import org.opensplice.cm.qos.LivelinessKind;
import org.opensplice.cm.qos.LivelinessPolicy;
import org.opensplice.cm.qos.OrderbyKind;
import org.opensplice.cm.qos.OrderbyPolicy;
import org.opensplice.cm.qos.OwnershipKind;
import org.opensplice.cm.qos.OwnershipPolicy;
import org.opensplice.cm.qos.PacingPolicy;
import org.opensplice.cm.qos.ParticipantQoS;
import org.opensplice.cm.qos.PresentationKind;
import org.opensplice.cm.qos.PresentationPolicy;
import org.opensplice.cm.qos.PublisherQoS;
import org.opensplice.cm.qos.QoS;
import org.opensplice.cm.qos.ReaderLifecyclePolicy;
import org.opensplice.cm.qos.ReaderLifespanPolicy;
import org.opensplice.cm.qos.ReaderQoS;
import org.opensplice.cm.qos.ReliabilityKind;
import org.opensplice.cm.qos.ReliabilityPolicy;
import org.opensplice.cm.qos.ResourcePolicy;
import org.opensplice.cm.qos.ScheduleKind;
import org.opensplice.cm.qos.SchedulePolicy;
import org.opensplice.cm.qos.SchedulePriorityKind;
import org.opensplice.cm.qos.SharePolicy;
import org.opensplice.cm.qos.StrengthPolicy;
import org.opensplice.cm.qos.SubscriberQoS;
import org.opensplice.cm.qos.TopicDataPolicy;
import org.opensplice.cm.qos.TopicQoS;
import org.opensplice.cm.qos.TransportPolicy;
import org.opensplice.cm.qos.UserDataPolicy;
import org.opensplice.cm.qos.UserKeyPolicy;
import org.opensplice.cm.qos.WriterLifecyclePolicy;
import org.opensplice.cm.qos.WriterQoS;
import org.opensplice.cm.transform.QoSDeserializer;
import org.opensplice.cm.transform.TransformationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * The XML implementation of an QoSDeserializer. It is capable of
 * transforming a serialized XML representation to an QoS object.
 *
 * @date Jan 10, 2005
 */
public class QoSDeserializerXML implements QoSDeserializer {
    private DocumentBuilder builder = null;
    private Logger logger = null;

    /**
     * Creates a new QoSDeserializerXML object which is a concrete descendant
     * of the QoSDeserializer interface.
     *
     * @throws ParserConfigurationException Thrown when no DOM parser is
     *                                      available in the standard Java API.
     */
    public QoSDeserializerXML() throws ParserConfigurationException{
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(false);
        builder = factory.newDocumentBuilder();
        logger = Logger.getLogger("com.thales.splice.api.cm.transform.xml");
    }

    @Override
    public QoS deserializeQoS(Object qos) throws TransformationException{
        QoS result = null;
        Document document = null;

        if(qos == null){
            throw new TransformationException("Supplied QoS is not valid.");
        }

        if(qos instanceof String){
            try {
                synchronized(builder){
                    document = builder.parse(new InputSource(new StringReader((String)qos)));
                }
            }
            catch (SAXException se) {
                logger.logp(Level.SEVERE,  "QoSDeserializerXML",
                                           "deserializeQoS",
                                           "SAXException occurred, QoS could not be deserialized");
                throw new TransformationException(se.getMessage());
            }
            catch (IOException ie) {
                logger.logp(Level.SEVERE,  "QoSDeserializerXML",
                                           "deserializeQoS",
                                           "IOException occurred, QoS could not be deserialized");
                throw new TransformationException(ie.getMessage());
            }

            if(document == null){
                logger.logp(Level.SEVERE,  "QoSDeserializerXML",
                        "deserializeQoS",
                        "Received NULL document");
                throw new TransformationException("Supplied QoS is not valid.");
            }
            Element rootElement = document.getDocumentElement();
            result = this.buildQoS(rootElement);
        } else if(qos instanceof Element){
            result = this.buildQoS((Element)qos);
        } else {
            throw new TransformationException("Supplied object type not supported. (" + qos.getClass().getName() + ")");
        }
        return result;
    }

    private QoS buildQoS(Element e){
        String kind = null;
        QoS result = null;

        if(e == null){
            return null;
        }
        Node kindNode = this.getChildNode(e, "kind");

        if(kindNode != null){
            Element elmt = (Element)(kindNode);
            Node n = elmt.getFirstChild();

            if(n != null){
                kind = n.getNodeValue();
            }
        }

        if("V_PARTICIPANT_QOS".equals(kind)){
            result = this.parseParticipantQoS(e);
        } else if("V_TOPIC_QOS".equals(kind)){
            result = this.parseTopicQoS(e);
        } else if("V_WRITER_QOS".equals(kind)){
            result = this.parseWriterQoS(e);
        } else if("V_READER_QOS".equals(kind)){
            result = this.parseReaderQoS(e);
        } else if("V_PUBLISHER_QOS".equals(kind)){
            result = this.parsePublisherQos(e);
        } else if("V_SUBSCRIBER_QOS".equals(kind)){
            result = this.parseSubscriberQoS(e);
        } else{
            logger.logp(Level.SEVERE,  "QoSDeserializerXML",
                   "buildQoS",
                   "Unknown QoS kind found: " + kind);
            assert false: "Deserialize QoS XML: received unknown QoS: " + kind;
        }
        return result;
    }

    private Element getDataChild(Element e){
        NodeList list = e.getChildNodes();
        if (list.getLength() != 1) {
            /* presumably old format */
            return e;
        }
        Node n = list.item(0);

        if (n instanceof Element) {
            Element c = (Element) n;
            String name = c.getNodeName();
            if ("v".equals(name)) {
                return c;
            }
        }
        return e;
    }

    private ParticipantQoS parseParticipantQoS(Element e){
        NodeList list = e.getChildNodes();
        String name;
        Element child;
        EntityFactoryPolicy efp = null;
        UserDataPolicy udp = null;
        SchedulePolicy scp = null;

        for(int i=0; i<list.getLength(); i++){
            child = (Element)list.item(i);
            name = child.getNodeName();

            if("entityFactory".equals(name)){
                efp = this.parseEntityFactory(this.getDataChild(child));
            } else if("userData".equals(name)){
                udp = this.parseUserData(this.getDataChild(child));
            } else if("watchdogScheduling".equals(name)){
                scp = this.parseSchedule(this.getDataChild(child));
            }
        }
        return new ParticipantQoS(efp, udp, scp);
    }

    private TopicQoS parseTopicQoS(Element e){
        NodeList list = e.getChildNodes();
        String name;
        Element child;
        TopicQoS qos = null;
        TopicDataPolicy tdp = null;
        DurabilityPolicy drp = null;
        DurabilityServicePolicy dsp = null;
        DeadlinePolicy dlp = null;
        LatencyPolicy lcp = null;
        LivelinessPolicy llp = null;
        ReliabilityPolicy rbp = null;
        OrderbyPolicy obp = null;
        HistoryPolicy hsp = null;
        ResourcePolicy rsp = null;
        TransportPolicy trp = null;
        LifespanPolicy lsp = null;
        OwnershipPolicy osp = null;

        for(int i=0; i<list.getLength(); i++){
            if(list.item(i) instanceof Element){
                child = (Element)list.item(i);
                name = child.getNodeName();

                if("topicData".equals(name)){
                    tdp = this.parseTopicData(this.getDataChild(child));
                } else if("durability".equals(name)){
                    drp = this.parseDurability(this.getDataChild(child));
                } else if("durabilityService".equals(name)){
                    dsp = this.parseDurabilityService(this.getDataChild(child));
                } else if("deadline".equals(name)){
                    dlp = this.parseDeadline(this.getDataChild(child));
                } else if("latency".equals(name)){
                    lcp = this.parseLatency(this.getDataChild(child));
                } else if("liveliness".equals(name)){
                    llp = this.parseLiveliness(this.getDataChild(child));
                } else if("reliability".equals(name)){
                    rbp = this.parseReliability(this.getDataChild(child));
                } else if("orderby".equals(name)){
                    obp = this.parseOrderby(this.getDataChild(child));
                } else if("history".equals(name)){
                    hsp = this.parseHistory(this.getDataChild(child));
                } else if("resource".equals(name)){
                    rsp = this.parseResource(this.getDataChild(child));
                } else if("transport".equals(name)){
                    trp = this.parseTransport(this.getDataChild(child));
                } else if("lifespan".equals(name)){
                    lsp = this.parseLifespan(this.getDataChild(child));
                } else if("ownership".equals(name)){
                    osp = this.parseOwnership(this.getDataChild(child));
                }
            }
        }
        qos = new TopicQoS(tdp, drp, dsp, dlp, lcp, llp, rbp, obp, hsp, rsp, trp, lsp, osp);
        return qos;
    }

    private WriterQoS parseWriterQoS(Element e){
        NodeList list = e.getChildNodes();
        String name;
        Element child;
        WriterQoS qos = null;
        DurabilityPolicy drp = null;
        DeadlinePolicy dlp = null;
        LatencyPolicy lcp = null;
        LivelinessPolicy llp = null;
        ReliabilityPolicy rbp = null;
        OrderbyPolicy obp = null;
        HistoryPolicy hsp = null;
        ResourcePolicy rsp = null;
        TransportPolicy trp = null;
        LifespanPolicy lsp = null;
        UserDataPolicy udp = null;
        OwnershipPolicy osp = null;
        StrengthPolicy stp = null;
        WriterLifecyclePolicy wlp = null;

        for(int i=0; i<list.getLength(); i++){
            if(list.item(i) instanceof Element){
                child = (Element)list.item(i);
                name = child.getNodeName();

                if("durability".equals(name)){
                    drp = this.parseDurability(this.getDataChild(child));
                } else if("deadline".equals(name)){
                    dlp = this.parseDeadline(this.getDataChild(child));
                } else if("latency".equals(name)){
                    lcp = this.parseLatency(this.getDataChild(child));
                } else if("liveliness".equals(name)){
                    llp = this.parseLiveliness(this.getDataChild(child));
                } else if("reliability".equals(name)){
                    rbp = this.parseReliability(this.getDataChild(child));
                } else if("orderby".equals(name)){
                    obp = this.parseOrderby(this.getDataChild(child));
                } else if("history".equals(name)){
                    hsp = this.parseHistory(this.getDataChild(child));
                } else if("resource".equals(name)){
                    rsp = this.parseResource(this.getDataChild(child));
                } else if("transport".equals(name)){
                    trp = this.parseTransport(this.getDataChild(child));
                } else if("lifespan".equals(name)){
                    lsp = this.parseLifespan(this.getDataChild(child));
                } else if("userData".equals(name)){
                    udp = this.parseUserData(this.getDataChild(child));
                } else if("ownership".equals(name)){
                    osp = this.parseOwnership(this.getDataChild(child));
                } else if("strength".equals(name)){
                    stp = this.parseStrenght(this.getDataChild(child));
                } else if("lifecycle".equals(name)){
                    wlp = this.parseWriterLifecycle(this.getDataChild(child));
                }
            }
        }
        qos = new WriterQoS(drp, dlp, lcp, llp, rbp, obp, hsp, rsp, trp, lsp, udp, osp, stp, wlp);
        return qos;
    }

    private ReaderQoS parseReaderQoS(Element e){
        NodeList list = e.getChildNodes();
        String name;
        Element child;
        ReaderQoS qos = null;
        DurabilityPolicy drp = null;
        DeadlinePolicy dlp = null;
        LatencyPolicy lcp = null;
        LivelinessPolicy llp = null;
        ReliabilityPolicy rbp = null;
        OrderbyPolicy obp = null;
        HistoryPolicy hsp = null;
        ResourcePolicy rsp = null;
        UserDataPolicy udp = null;
        PacingPolicy pcp = null;
        OwnershipPolicy osp = null;
        ReaderLifecyclePolicy rlp = null;
        ReaderLifespanPolicy rlsp = null;
        SharePolicy sp = null;
        UserKeyPolicy uk = null;

        for(int i=0; i<list.getLength(); i++){
            if(list.item(i) instanceof Element){
                child = (Element)list.item(i);
                name = child.getNodeName();

                if("durability".equals(name)){
                    drp = this.parseDurability(this.getDataChild(child));
                } else if("deadline".equals(name)){
                    dlp = this.parseDeadline(this.getDataChild(child));
                } else if("latency".equals(name)){
                    lcp = this.parseLatency(this.getDataChild(child));
                } else if("liveliness".equals(name)){
                    llp = this.parseLiveliness(this.getDataChild(child));
                } else if("reliability".equals(name)){
                    rbp = this.parseReliability(this.getDataChild(child));
                } else if("orderby".equals(name)){
                    obp = this.parseOrderby(this.getDataChild(child));
                } else if("history".equals(name)){
                    hsp = this.parseHistory(this.getDataChild(child));
                } else if("resource".equals(name)){
                    rsp = this.parseResource(this.getDataChild(child));
                } else if("userData".equals(name)){
                    udp = this.parseUserData(this.getDataChild(child));
                } else if("ownership".equals(name)){
                    osp = this.parseOwnership(this.getDataChild(child));
                } else if("pacing".equals(name)){
                    pcp = this.parsePacing(this.getDataChild(child));
                } else if("lifecycle".equals(name)){
                    rlp = this.parseReaderLifecycle(this.getDataChild(child));
                } else if("lifespan".equals(name)){
                    rlsp = this.parseReaderLifespan(this.getDataChild(child));
                } else if("share".equals(name)){
                    sp = this.parseShare(this.getDataChild(child));
                } else if("userKey".equals(name)){
                    uk = this.parseUserKey(this.getDataChild(child));
                }
            }
        }
        qos = new ReaderQoS(drp, dlp, lcp, llp, rbp, obp, hsp, rsp, udp, osp, pcp, rlp, rlsp, sp, uk);
        return qos;
    }

    private PublisherQoS parsePublisherQos(Element e){
        NodeList list = e.getChildNodes();
        String name;
        Element child;
        PresentationPolicy prp = null;
        String partition = null;
        GroupDataPolicy gdp = null;
        EntityFactoryPolicy efp = null;

        for(int i=0; i<list.getLength(); i++){
            if(list.item(i) instanceof Element){
                child = (Element)list.item(i);
                name = child.getNodeName();

                if("presentation".equals(name)){
                    prp = this.parsePresentation(this.getDataChild(child));
                } else if("partition".equals(name)){
                    partition = this.parsePartition(this.getDataChild(child));
                } else if("groupData".equals(name)){
                    gdp = this.parseGroupData(this.getDataChild(child));
                } else if("entityFactory".equals(name)){
                    efp = this.parseEntityFactory(this.getDataChild(child));
                }
            }
        }
        return new PublisherQoS(prp, partition, gdp, efp);
    }

    private SubscriberQoS parseSubscriberQoS(Element e){
        NodeList list = e.getChildNodes();
        String name;
        Element child;
        PresentationPolicy prp = null;
        String partition = null;
        GroupDataPolicy gdp = null;
        EntityFactoryPolicy efp = null;
        SharePolicy sp = null;

        for(int i=0; i<list.getLength(); i++){
            if(list.item(i) instanceof Element){
                child = (Element)list.item(i);
                name = child.getNodeName();

                if("presentation".equals(name)){
                    prp = this.parsePresentation(this.getDataChild(child));
                } else if("partition".equals(name)){
                    partition = this.parsePartition(this.getDataChild(child));
                } else if("groupData".equals(name)){
                    gdp = this.parseGroupData(this.getDataChild(child));
                } else if("entityFactory".equals(name)){
                    efp = this.parseEntityFactory(this.getDataChild(child));
                } else if("share".equals(name)){
                    sp = this.parseShare(this.getDataChild(child));
                }
            }
        }
        return new SubscriberQoS(prp, partition, gdp, efp, sp);
    }
    /*
    private ViewQoS parseViewQoS(Element e){
        String name;
        Element child;
        String keyPolicy = null;
        NodeList list = e.getChildNodes();

        for(int i=0; i<list.getLength(); i++){
            if(list.item(i) instanceof Element){
                child = (Element)list.item(i);
                name = child.getNodeName();

                if("keyList".equals(name)){
                    keyPolicy = this.parseKeyPolicy(this.getDataChild(child));
                }
            }
        }
        return new ViewQoS(keyPolicy);
    }
    */
    private EntityFactoryPolicy parseEntityFactory(Element e){
        Node child = this.getChildNode(e, "autoenable_created_entities");
        EntityFactoryPolicy result = null;

        if(child != null){
            Element el = (Element)child;
            String value = el.getFirstChild().getNodeValue();
            boolean b = false;

            if("TRUE".equals(value)){
               b = true;
            }
            result = new EntityFactoryPolicy(b);
        }
        return result;
    }

    private UserDataPolicy parseUserData(Element e){
        NodeList list;
        UserDataPolicy result;
        int size = -1;
        byte[] value;

        Node child = this.getChildNode(e, "size");

        if(child != null){
            Element el = (Element)child;
            size = Integer.parseInt(el.getFirstChild().getNodeValue());
        }

        if(size == -1){
            result = null;
        } else if(size > 0){
            value = new byte[size];
            list = e.getElementsByTagName("value");

            if(list.getLength() > 0){
                list = ((Element)list.item(0)).getElementsByTagName("element");

                for(int i=0; i<value.length; i++){
                    value[i] = Byte.parseByte(
                                list.item(i).getFirstChild().getNodeValue());
                }
            }
            result = new UserDataPolicy(value);
        } else {
            result = new UserDataPolicy(null);
        }
        return result;
    }

    private TopicDataPolicy parseTopicData(Element e){
        NodeList list;
        TopicDataPolicy result;
        int size = -1;
        byte[] value;
        Node child = this.getChildNode(e, "size");

        if(child != null){
            Element el = (Element)child;
            size = Integer.parseInt(el.getFirstChild().getNodeValue());
        }

        if(size == -1){
            result = null;
        } else if(size > 0){
            value = new byte[size];
            list = e.getElementsByTagName("value");

            if(list.getLength() > 0){
                list = ((Element)list.item(0)).getElementsByTagName("element");

                for(int i=0; i<value.length; i++){
                    value[i] = Byte.parseByte(
                                list.item(i).getFirstChild().getNodeValue());
                }
            }
            result = new TopicDataPolicy(value);
        } else {
            result = new TopicDataPolicy(null);
        }
        return result;
    }

    private DurabilityPolicy parseDurability(Element e){
        DurabilityPolicy result = null;
        DurabilityKind kind = null;
        Node child = this.getChildNode(e, "kind");

        if(child != null){
            Element el = (Element)child;
            String value = el.getFirstChild().getNodeValue();
            kind = DurabilityKind.from_string(value);

            if(kind != null){
                result = new DurabilityPolicy(kind);
            }
        }
        return result;
    }

    private DurabilityServicePolicy parseDurabilityService(Element e){
        DurabilityServicePolicy result = null;
        NodeList list = e.getChildNodes();
        Node n;
        int max_samples = -1;
        int max_instances = -1;
        int max_samples_per_instance = -1;
        int history_depth = 1;
        HistoryQosKind kind = null;
        Time service_cleanup_delay = null;

        for(int i=0; i< list.getLength(); i++){
            n = list.item(i);

            if("max_samples".equals(n.getNodeName())){
                max_samples = Integer.parseInt(n.getFirstChild().getNodeValue());
            } else if("max_instances".equals(n.getNodeName())){
                max_instances = Integer.parseInt(n.getFirstChild().getNodeValue());
            } else if("max_samples_per_instance".equals(n.getNodeName())){
                max_samples_per_instance =
                            Integer.parseInt(n.getFirstChild().getNodeValue());
            } else if("history_depth".equals(n.getNodeName())){
                history_depth = Integer.parseInt(n.getFirstChild().getNodeValue());
            } else if("history_kind".equals(n.getNodeName())){
                kind = HistoryQosKind.from_string(n.getFirstChild().getNodeValue());
            }
        }
        service_cleanup_delay = this.parseDuration("service_cleanup_delay", e);

        result = new DurabilityServicePolicy(service_cleanup_delay, kind,
                history_depth, max_samples, max_instances, max_samples_per_instance);

        return result;
    }

    private DeadlinePolicy parseDeadline(Element e){
        return new DeadlinePolicy(this.parseDuration("period", e));
    }

    private LatencyPolicy parseLatency(Element e){
        return new LatencyPolicy(this.parseDuration("duration", e));
    }

    private LivelinessPolicy parseLiveliness(Element e){
        LivelinessPolicy result = null;
        LivelinessKind kind = null;
        Time t = null;

        Node child = this.getChildNode(e, "kind");

        if(child != null){
            Element el = (Element)child;
            kind = LivelinessKind.from_string(el.getFirstChild().getNodeValue());
            t = this.parseDuration("lease_duration", e);

            result = new LivelinessPolicy(kind, t);
        }

        return result;
    }

    private ReliabilityPolicy parseReliability(Element e){
        ReliabilityPolicy result = null;
        ReliabilityKind kind = null;
        Time t = null;
        Boolean synchronous = false;
        Node child = this.getChildNode(e, "kind");

        if(child != null){
            Element el = (Element)child;
            kind = ReliabilityKind.from_string(el.getFirstChild().getNodeValue());
            t = this.parseDuration("max_blocking_time", e);
            child = this.getChildNode(e, "synchronous");
            if (child != null) {
                synchronous = new Boolean(child.getFirstChild().getNodeValue());
            }
            result = new ReliabilityPolicy(kind, t, synchronous);
        }
        return result;
    }

    private OrderbyPolicy parseOrderby(Element e){
        OrderbyPolicy result = null;
        OrderbyKind kind = null;
        Node child = this.getChildNode(e, "kind");

        if(child != null){
            Element el = (Element)child;
            kind = OrderbyKind.from_string(el.getFirstChild().getNodeValue());

            result = new OrderbyPolicy(kind);
        }
        return result;
    }

    private HistoryPolicy parseHistory(Element e){
        HistoryPolicy result = null;
        HistoryQosKind kind = null;
        NodeList list = e.getChildNodes();
        Node n;
        int depth = 0;

        for(int i=0; i< list.getLength(); i++){
            n = list.item(i);

            if("kind".equals(n.getNodeName())){
                kind = HistoryQosKind.from_string(n.getFirstChild().getNodeValue());
            } else if("depth".equals(n.getNodeName())){
                depth = Integer.parseInt(n.getFirstChild().getNodeValue());
            }
        }
        result = new HistoryPolicy(kind, depth);

        return result;
    }

    private ResourcePolicy parseResource(Element e){
        ResourcePolicy result = null;
        NodeList list = e.getChildNodes();
        Node n;
        int max_samples = -1;
        int max_instances = -1;
        int max_samples_per_instance = -1;

        for(int i=0; i< list.getLength(); i++){
            n = list.item(i);

            if("max_samples".equals(n.getNodeName())){
                max_samples = Integer.parseInt(n.getFirstChild().getNodeValue());
            } else if("max_instances".equals(n.getNodeName())){
                max_instances = Integer.parseInt(n.getFirstChild().getNodeValue());
            } else if("max_samples_per_instance".equals(n.getNodeName())){
                max_samples_per_instance =
                            Integer.parseInt(n.getFirstChild().getNodeValue());
            }
        }
        result = new ResourcePolicy(max_samples, max_instances, max_samples_per_instance);

        return result;
    }

    private TransportPolicy parseTransport(Element e){
        TransportPolicy result = null;
        int value;
        Node n = this.getChildNode(e, "value");

        if(n != null){
            value = Integer.parseInt(n.getFirstChild().getNodeValue());
            result = new TransportPolicy(value);
        }
        return result;
    }

    private LifespanPolicy parseLifespan(Element e){
        return new LifespanPolicy(this.parseDuration("duration", e));
    }

    private StrengthPolicy parseStrenght(Element e){
        StrengthPolicy result = null;
        int value;
        Node n = this.getFirstChildElement(e);

        if(n != null){
            value = Integer.parseInt(n.getFirstChild().getNodeValue());
            result = new StrengthPolicy(value);
        }
        return result;
    }

    private WriterLifecyclePolicy parseWriterLifecycle(Element e){
        WriterLifecyclePolicy result = null;
        Node n = this.getFirstChildElement(e);

        if(n != null){
            String value = n.getFirstChild().getNodeValue();
            boolean b = false;

            if("TRUE".equals(value)){
               b = true;
            }
            result = new WriterLifecyclePolicy(b, this.parseDuration("autopurge_suspended_samples_delay", e), this.parseDuration("autounregister_instance_delay", e));
        }
        return result;
    }

    private OwnershipPolicy parseOwnership(Element e){
        OwnershipPolicy result = null;
        OwnershipKind kind = null;
        Node child = this.getChildNode(e, "kind");

        if(child != null){
            Element el = (Element)child;
            kind = OwnershipKind.from_string(el.getFirstChild().getNodeValue());

            result = new OwnershipPolicy(kind);
        }
        return result;
    }

    private PacingPolicy parsePacing(Element e){
        return new PacingPolicy(this.parseDuration("minSeperation", e));
    }

    private ReaderLifecyclePolicy parseReaderLifecycle(Element e){
        boolean autopurge_dispose_all;
        boolean enable_invalid_samples;
        InvalidSampleVisibilityKind invalid_sample_visibility;
        Node node = this.getChildNode(e, "autopurge_dispose_all");

        if(node != null){
            String value = node.getFirstChild().getNodeValue();

            if("TRUE".equals(value)){
                autopurge_dispose_all = true;
            } else {
                autopurge_dispose_all = false;
            }
        } else {
            autopurge_dispose_all = false;
        }

        node = this.getChildNode(e, "enable_invalid_samples");
        if(node != null){
            String value = node.getFirstChild().getNodeValue();

            if("TRUE".equals(value)){
                enable_invalid_samples = true;
            } else {
                enable_invalid_samples = false;
            }
        } else {
            enable_invalid_samples = false;
        }
        node = this.getChildNode(e, "invalid_sample_visibility");

        if(node != null){
            invalid_sample_visibility = InvalidSampleVisibilityKind.from_string(node.getFirstChild().getNodeValue());
        } else {
            invalid_sample_visibility = InvalidSampleVisibilityKind.MINIMUM_INVALID_SAMPLES;
        }
        return new ReaderLifecyclePolicy(
                this.parseDuration("autopurge_nowriter_samples_delay", e),
                this.parseDuration("autopurge_disposed_samples_delay", e),
                autopurge_dispose_all,
                enable_invalid_samples,
                invalid_sample_visibility);
    }

    private ReaderLifespanPolicy parseReaderLifespan(Element e){
        ReaderLifespanPolicy result = null;
        Node n = this.getFirstChildElement(e);

        if(n != null){
            String value = n.getFirstChild().getNodeValue();
            boolean b = false;

            if("TRUE".equals(value)){
               b = true;
            }
            result = new ReaderLifespanPolicy(b, this.parseDuration("duration", e));
        }
        return result;
    }

    private SharePolicy parseShare(Element e){
        SharePolicy result = null;
        Node n;
        String name = null;
        boolean enable = false;

        NodeList list = e.getChildNodes();

        for(int i=0; i< list.getLength(); i++){
            n = list.item(i);

            if("name".equals(n.getNodeName())){
                Node child = n.getFirstChild();

                if(child == null){
                    name = "";
                } else {
                    name = child.getNodeValue();

                    if("<NULL>".equals(name) || "<NULL>".equals(name)){
                        name = null;
                    }
                }
            } else if("enable".equals(n.getNodeName())){
                enable = new Boolean(n.getFirstChild().getNodeValue()).booleanValue();
            }
        }
        result = new SharePolicy(name, enable);

        return result;
    }

    private UserKeyPolicy parseUserKey(Element e){
        UserKeyPolicy result = null;
        Node n, expressionNode;
        String expression = null;
        boolean enable = false;

        NodeList list = e.getChildNodes();

        for(int i=0; i< list.getLength(); i++){
            n = list.item(i);

            if("expression".equals(n.getNodeName())){
                expressionNode = n.getFirstChild();

                if(expressionNode != null) {
                    expression = expressionNode.getNodeValue();

                    if("<NULL>".equals(expression) || "<NULL>".equals(expression)){
                        expression = null;
                    }
                } else {
                    expression = "";
                }
            } else if("enable".equals(n.getNodeName())){
                enable = new Boolean(n.getFirstChild().getNodeValue()).booleanValue();
            }
        }
        result = new UserKeyPolicy(enable, expression);

        return result;
    }

    private PresentationPolicy parsePresentation(Element e){
        PresentationPolicy result = null;
        NodeList list = e.getChildNodes();
        Node n;
        PresentationKind access_scope = null;
        boolean coherent_access = false;
        boolean ordered_access = false;

        for(int i=0; i< list.getLength(); i++){
            n = list.item(i);

            if("access_scope".equals(n.getNodeName())){
                access_scope = PresentationKind.from_string(
                                        n.getFirstChild().getNodeValue());
            } else if("coherent_access".equals(n.getNodeName())){
                 coherent_access = new Boolean(
                             n.getFirstChild().getNodeValue()).booleanValue();
            } else if("ordered_access".equals(n.getNodeName())){
                ordered_access = new Boolean(
                            n.getFirstChild().getNodeValue()).booleanValue();
            }
        }
        result = new PresentationPolicy(access_scope, coherent_access, ordered_access);

        return result;
    }

    private SchedulePolicy parseSchedule(Element e){
        SchedulePolicy result = null;
        Node n;
        ScheduleKind kind = ScheduleKind.DEFAULT;
        SchedulePriorityKind priorityKind = SchedulePriorityKind.RELATIVE;
        int priority = -1;

        NodeList list = e.getChildNodes();

        for(int i=0; i< list.getLength(); i++){
            n = list.item(i);

            if("kind".equals(n.getNodeName())){
                kind = ScheduleKind.from_string(n.getFirstChild().getNodeValue());
            } else if("priorityKind".equals(n.getNodeName())){
                priorityKind = SchedulePriorityKind.from_string(n.getFirstChild().getNodeValue());
            } else if("priority".equals(n.getNodeName())){
                priority = Integer.parseInt(n.getFirstChild().getNodeValue());
            }
        }
        result = new SchedulePolicy(kind, priorityKind, priority);

        return result;
    }

    private String parsePartition(Element e){
        String result;
        Node child = e.getFirstChild();

        if(child == null){
            result = null;
        } else if (child.getNodeValue().equals("<NULL>")) {
            result = null;
        } else {
            result = child.getNodeValue();
        }
        return result;
    }

    private GroupDataPolicy parseGroupData(Element e){
        NodeList list;
        GroupDataPolicy result;
        int size = -2;
        byte[] value;
        Node child = this.getChildNode(e, "size");

        if(child != null){
            Element el = (Element)child;
            size = Integer.parseInt(el.getFirstChild().getNodeValue());
        }

        if(size == -2){
            result = null;
        } else if(size > 0){
            value = new byte[size];
            list = e.getElementsByTagName("value");

            if(list.getLength() > 0){
                list = ((Element)list.item(0)).getElementsByTagName("element");

                for(int i=0; i<value.length; i++){
                    value[i] = Byte.parseByte(
                                list.item(i).getFirstChild().getNodeValue());
                }
            }
            result = new GroupDataPolicy(value);
        } else {
            result = new GroupDataPolicy(null);
        }
        return result;
    }
    /*
    private String parseKeyPolicy(Element e){
        Node n = this.getChildNode(e, "expression");
        String result = null;

        if(n != null){
            result = n.getFirstChild().getNodeValue();
        }
        return result;
    }
    */
    protected Time parseTime(String name, Element e){
        NodeList list = e.getElementsByTagName(name);
        Node n;
        int sec = 0, nsec = 0;
        Time result = null;

        Node node = this.getChildNode(e, name);

        if(node != null){
            Element child = (Element)node;
            list = child.getChildNodes();

            for(int i=0; i<list.getLength(); i++){
               n = list.item(i);

               if("seconds".equals(n.getNodeName())){
                   sec = Integer.parseInt(n.getFirstChild().getNodeValue());
               } else if("nanoseconds".equals(n.getNodeName())){
                   nsec = Integer.parseInt(n.getFirstChild().getNodeValue());
               }
            }
            result = new Time(sec, nsec);
        }
        return result;
    }

    protected Time parseDuration(String name, Element e){
        NodeList list = e.getElementsByTagName(name);
        Node n;
        int sec = 0, nsec = 0;
        Time result = null;

        Node node = this.getChildNode(e, name);

        if(node != null){
            Element child = (Element)node;
            list = child.getChildNodes();

            for(int i=0; i<list.getLength(); i++){
               n = list.item(i);

               if("seconds".equals(n.getNodeName())){
                   sec = Integer.parseInt(n.getFirstChild().getNodeValue());
               } else if("nanoseconds".equals(n.getNodeName())){
                   nsec = Integer.parseInt(n.getFirstChild().getNodeValue());
               }
            }
            result = new Time(sec, nsec);
        }
        return result;
    }

    protected Node getChildNode(Node node, String child){
        NodeList members = node.getChildNodes();
        Node childNode = null;

        if(child != null){
            for(int i=0; (i<members.getLength()) && (childNode == null); i++){
                if(child.equals(members.item(i).getNodeName())){
                    childNode = members.item(i);
                }
            }
        }
        return childNode;
    }

    private Element getFirstChildElement(Node parent){
        NodeList members = parent.getChildNodes();
        Element childNode = null;

        for(int i=0; (i<members.getLength()) && (childNode == null); i++){
            if(members.item(i) instanceof Element){
                childNode = (Element)members.item(i);
            }
        }
        return childNode;
    }
    /*
    private Element getLastChildElement(Node parent){
        NodeList members = parent.getChildNodes();
        Element childNode = null;

        for(int i=0; i<members.getLength(); i++){
            if(members.item(i) instanceof Element){
                childNode = (Element)members.item(i);
            }
        }
        return childNode;
    }
    */
}