text:
<!DOCTYPE html>

  <meta charset="utf-8"/>
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=yes" />
  <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">

  <%
    var citations = _.map(doc.get('citations').nodes, function(citationId) {
      return doc.get(citationId);
    });
  %>

  <% if (options.include_toc) { %>

  <% } %>

  <link href="style.css" rel="stylesheet" />
  <% if (options.enable_bookmarks) { %>

  <% } %>

  <title><%= doc.title %></title>

<body class="<%= options.enable_section_numbering ? "section-numbering" : "" %><%= options.include_toc ? " include-toc" : "" %>">

<% if (options.include_toc) { %>

 <%= doc.title %>

Table of Contents

  <%
    var sections = [];

    var nodes = doc.get('content').nodes;
    var currentSection;
    _.each(nodes, function(nodeId) {
      var node = doc.get(nodeId);

      if (node.type === "heading") {
        currentSection = {
          "heading": node,
          figures: []
        };
        sections.push(currentSection);
      } else if (currentSection) {

        // Add teaser to section if it does not yet exist
        if (node.type === "text" && !currentSection.teaser) {
          currentSection.teaser = node;
        }

        // Collect figures per section
        if (node.type === "figure") {
          currentSection.figures.push(node);
        }
      }
    });
  %>

      <% _.each(sections, function(section) { %>

        <div id="toc_<%= section.heading.id %>" class="toc-entry level-<%= section.heading.level %>">

              <a href="#<%= section.heading.id %>" class="jumpto-node" data-id="<%= section.heading.id %>">

<%= section.heading.content %>

                  <% if (section.teaser) { %>
                    <%= section.teaser.content %>
                  <% } %>

              <% _.each(section.figures, function(figure) { %>
                <a class="figure jumpto-node" data-id="<%= figure.id %>" href="#<%= figure.id %>">
                  <img src="<%= figure.image %>">

              <% }); %>

      <% }); %>

      <% if (options.include_references && citations.length > 0) { %>

                  References

      <% } %>

<% } %>

<%= render(doc) %>

<% if (options.include_references && citations.length > 0) { %>

      #

References

          <% citations.forEach(function(citation) { %>
            <div class="citation" id="<%= citation.id %>">

<a href="<%= citation.url %>"><%= citation.title %>

<%= citation.description %>

          <% }); %>

<% } %>

        "<%= doc.title %>" was published on <%= new Date(doc.published_on).toDateString() %>. It has been modified on <%= new Date(doc.updated_at).toDateString() %>.

      <% var authors = []; %>
      <%
        doc.getAuthors().forEach(function(a) {
          if (a.description) authors.push(a);
        });
      %>
      <% if (authors.length > 0) { %>

          <% authors.forEach(function(a) { %>
            <div class="author" id="<%= a.id %>">
              <img class="author-image" src="<%= a.image %>"/>

<%= a.name %>

<%= a.description %>

          <% }); %>

      <% } %>

      <% if (options.include_source_file) { %>

Supplements

<a href="<%= filename %>"><%= filename %>

              Download this article to read offline, add personal notes and even edit.
Just make sure to install the Substance Composer on your desktop.

      <% } %>

        <% var license = doc.get('license'); %>

        <% if (authors.length > 0) { %>

          Copyright © <%= new Date(doc.published_on).getFullYear() %>
          <%= authors.map(function(a) { return a.name; }).join(', ') %>

        <% } %>

          <%= license.description %>
          <% if (license.url) { %>
          See <a href="<%= license.url %>"><%= license.name %>.
          <% } %>

          This article was created with Substance, an open self-publishing system.


text:
@interface TestCommonClass : NSObject

@end

redpajama_set_name: RedPajamaGithub


text:
(function() {
    'use strict';

    function TvSimilar(TvSimilarService) {
        return {
            restrict: 'EA',
            replace: true,
            templateUrl : './src/app/components/tvSimilar/template.html',
            scope: {
                filter: "@"
            },
            controllerAs: 'vm',
            bindToController: true,
            controller: function($log, TvSimilarService, $stateParams) {
                var vm = this;
                var filter = vm.filter;
                TvSimilarService.getOneMovie($stateParams.id).then(function(data){
                    vm.similartvs = filter > 0 ? _.slice(data.data.results, 0, filter) : data.data.results;
                });
            },
            link: function(scope, elm, attrs) {

            }
        };
    }

    angular.module('tvSimilarDirective', ['service.similartv']).directive('tvSimilar', TvSimilar);
})();


text:
package com.jeecms.common.upload;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Tom
 */
public class FileUpload {
	/**
	* 模拟form表单的形式 ,上传文件 以输出流的形式把文件写入到url中,然后用输入流来获取url的响应
	*
	* @param url 请求地址 form表单url地址
	* @param filePath 文件在服务器保存路径
	* @return String 正确上传返回media_id
	* @throws IOException
	*/

	/** 微信上传文件接口  */
	public  String uploadFile(String url,String filePath,String type) throws Exception {
		 File file = new File(filePath);
		 String result = null;
	        if (!file.exists() || !file.isFile()) {
	            return "文件路径错误";
	        }
	        /**
	         * 第一部分
	         */
	        url = url+"&type="+type;
	        URL urlObj = new URL(url);
	        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

	        /**
	         * 设置关键值
	         */
	        con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
	        con.setDoInput(true);
	        con.setDoOutput(true);
	        con.setUseCaches(false); // post方式不能使用缓存
	        // 设置请求头信息
	        con.setRequestProperty("Connection", "Keep-Alive");
	        con.setRequestProperty("Charset", "UTF-8");

	        // 设置边界
	        String BOUNDARY = "----------" + System.currentTimeMillis();
	        con.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY);
	        //con.setRequestProperty("Content-Type", "multipart/mixed; boundary=" + BOUNDARY);
	        //con.setRequestProperty("content-type", "text/html");
	        // 请求正文信息

	        // 第一部分:
	        StringBuilder sb = new StringBuilder();
	        sb.append("--"); // ////////必须多两道线
	        sb.append(BOUNDARY);
	        sb.append("\r\n");
	        sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
	                + file.getName() + "\"\r\n");
	        sb.append("Content-Type:application/octet-stream\r\n\r\n");
	        byte[] head = sb.toString().getBytes("utf-8");
	        // 获得输出流
	        OutputStream out = new DataOutputStream(con.getOutputStream());
	        out.write(head);

	        // 文件正文部分
	        DataInputStream in = new DataInputStream(new FileInputStream(file));
	        int bytes = 0;
	        byte[] bufferOut = new byte[1024];
	        while ((bytes = in.read(bufferOut)) != -1) {
	            out.write(bufferOut, 0, bytes);
	        }
	        in.close();
	        // 结尾部分
	        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
	        out.write(foot);
	        out.flush();
	        out.close();
	        /**
	         * 读取服务器响应,必须读取,否则提交不成功
	         */
	       // con.getResponseCode();

	        /**
	         * 下面的方式读取也是可以的
	         */

	         try {

	         // 定义BufferedReader输入流来读取URL的响应
	        	 StringBuffer buffer = new StringBuffer();
		         BufferedReader reader = new BufferedReader(new InputStreamReader(
		         con.getInputStream(),"UTF-8"));
		         String line = null;
		         while ((line = reader.readLine()) != null) {
		            //System.out.println(line);
		            buffer.append(line);
		         }
		         if(result==null){
					result = buffer.toString();
				}
		         System.out.println(buffer.toString());
		         return buffer.toString();
	         } catch (Exception e) {
	        	 System.out.println("发送POST请求出现异常!" + e);
	        	 e.printStackTrace();
	         }
	         return result;
	}

	public static void main(String[] args) throws Exception {
		String filePath = "d:/mv1.jpg";
		String token="Jdr_B5dQzbWlmmTAlMxbpOZiUfe100laWKeNjRgqfYAJ2GkgCdbQCQO4gAA6e0qd7uYM8fhhzx9ehQBCHlQvKQ";
		String result = null;
		FileUpload fileUpload = new FileUpload();
		result = fileUpload.uploadFile(token, filePath, "image");
		System.out.println(result);
	}
}


text:
namespace EncompassRest.Settings.Personas
{
    /// <summary>
    /// DisclosureTrackingRights
    /// </summary>
    public sealed class DisclosureTrackingRights : PersonaAccessRights
    {
    }
}


text:
using System;
using System.Text;

public class Substring
{
    public static void Main()
    {
        string text = Console.ReadLine();
        int count = int.Parse(Console.ReadLine());

        const char Search = 'p';

        bool hasMatch = false;

        for (int i = 0; i < text.Length; i++)
        {
            if (text[i].ToString().CompareTo(Search.ToString()) == 0)
            {
                hasMatch = true;

                int endIndex = count + 1;

                if (i + endIndex > text.Length)
                {
                    endIndex = text.Length - i;
                }

                string matchedString = text.Substring(i, endIndex);
                Console.WriteLine(matchedString);
                i += count;
            }
        }

        if (!hasMatch)
        {
            Console.WriteLine("no");
        }
    }
}


text:
<?php
namespace Rikby\GitExt\Git;

use Rikby\GitExt\Exception as RootException;

/**
 * Class Exception
 *
 * @package Rikby\GitExt\Git
 */
class Exception extends RootException
{
}


text:
<?php

/* SfBlogBlogBundle::layout.html.twig */
class __TwigTemplate_2a37692d3f2623a69460cd0cf48fa21aa351fce3312ef4de31790890afa46a4c extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        $this->parent = $this->loadTemplate("::base.html.twig", "SfBlogBlogBundle::layout.html.twig", 1);
        $this->blocks = array(
            'stylesheets' => array($this, 'block_stylesheets'),
            'sidebar' => array($this, 'block_sidebar'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_stylesheets($context, array $blocks = array())
    {
        // line 4
        echo "    ";
        $this->displayParentBlock("stylesheets", $context, $blocks);
        echo "
    <link href=\"";
        // line 5
        echo twig_escape_filter($this->env, $this->env->getExtension('asset')->getAssetUrl("css/blog.css"), "html", null, true);
        echo "\" type=\"text/css\" rel=\"stylesheet\" />
    <link href=\"";
        // line 6
        echo twig_escape_filter($this->env, $this->env->getExtension('asset')->getAssetUrl("css/sidebar.css"), "html", null, true);
        echo "\" type=\"text/css\" rel=\"stylesheet\" />
";
    }

    // line 10
    public function block_sidebar($context, array $blocks = array())
    {
        // line 11
        echo "    ";
        echo $this->env->getExtension('http_kernel')->renderFragment($this->env->getExtension('http_kernel')->controller("SfBlogBlogBundle:Page:sidebar"));
        echo "
";
    }

    public function getTemplateName()
    {
        return "SfBlogBlogBundle::layout.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  50 => 11,  47 => 10,  41 => 6,  37 => 5,  32 => 4,  29 => 3,  11 => 1,);
    }
}


text:
var git = require("../");
var Diff = git.Diff;
var ConvenientHunk = require("./convenient_hunk");

function ConvenientPatch(delta, patch) {
  this.delta = delta;
  this.patch = patch;
}

/**
 * Old name of the file
 * @return {String}
 */
ConvenientPatch.prototype.oldFile = function() {
  return this.delta.oldFile();
};

/**
 * New name of the file
 * @return {String}
 */
ConvenientPatch.prototype.newFile = function() {
  return this.delta.newFile();
};

/**
 * The number of hunks in this patch
 * @return {Number}
 */
ConvenientPatch.prototype.size = function() {
  return this.patch.numHunks();
};

/**
 * The hunks in this patch
 * @return {[ConvenientHunk]} an array of ConvenientHunks
 */
ConvenientPatch.prototype.hunks = function() {
  var result = [];

  for (var i = 0; i < this.size(); i++) {
    result.push(new ConvenientHunk(this.patch, i));
  }

  return result;
};

/**
 * The status of this patch (unmodified, added, deleted)
 * @return {Number}
 */
ConvenientPatch.prototype.status = function() {
  return this.delta.status();
};

/**
 * Is this an unmodified patch?
 * @return {Boolean}
 */
ConvenientPatch.prototype.isUnmodified = function() {
  return this.status() == Diff.DELTA.UNMODIFIED;
};

/**
 * Is this an added patch?
 * @return {Boolean}
 */
ConvenientPatch.prototype.isAdded = function() {
  return this.status() == Diff.DELTA.ADDED;
};

/**
 * Is this a deleted patch?
 * @return {Boolean}
 */
ConvenientPatch.prototype.isDeleted = function() {
  return this.status() == Diff.DELTA.DELETED;
};

/**
 * Is this an modified patch?
 * @return {Boolean}
 */
ConvenientPatch.prototype.isModified = function() {
  return this.status() == Diff.DELTA.MODIFIED;
};

/**
 * Is this a renamed patch?
 * @return {Boolean}
 */
ConvenientPatch.prototype.isRenamed = function() {
  return this.status() == Diff.DELTA.RENAMED;
};

/**
 * Is this a copied patch?
 * @return {Boolean}
 */
ConvenientPatch.prototype.isCopied = function() {
  return this.status() == Diff.DELTA.COPIED;
};

/**
 * Is this an ignored patch?
 * @return {Boolean}
 */
ConvenientPatch.prototype.isIgnored = function() {
  return this.status() == Diff.DELTA.IGNORED;
};

/**
 * Is this an untracked patch?
 * @return {Boolean}
 */
ConvenientPatch.prototype.isUntracked = function() {
  return this.status() == Diff.DELTA.UNTRACKED;
};

/**
 * Is this a type change?
 * @return {Boolean}
 */
ConvenientPatch.prototype.isTypeChange = function() {
  return this.status() == Diff.DELTA.TYPECHANGE;
};

module.exports = ConvenientPatch;


text:
title: Adding a Database
pageTitle: 'Creating a Prisma Database Service Tutorial'
description: 'Learn how to add a database to your GraphQL server. The database is powered by Prisma.'
question: What is the role of Prisma Client in the GraphQL API?
answers:
  ['It receives and processes GraphQL queries', 'It connects your GraphQL server to the database', 'It lets you cache your data', 'It lets you design your GraphQL schema']
correctAnswer: 1
---

In this section, you're going to set up a new [SQLite](https://www.sqlite.org/index.html) to persist the data of incoming GraphQL mutations. Instead of writing SQL directly, you will
use [Prisma](https://www.prisma.io/) to access your database.

## So, what is Prisma?

Prisma is an [open source](https://github.com/prisma/prisma) database toolkit and ORM that makes it easy for developers to reason about their data and how they access it, by providing a
clean and type-safe API for submitting database queries.

You will be using these tools from the Prisma ecosystem:

- **Prisma Client**: An auto-generated and type-safe query builder for Node.js & TypeScript.
- **Prisma CLI**: A command line tool to interact with your Prisma project.
- **Prisma Migrate**: A declarative data modeling & migration system.
- **Prisma Studio**: A GUI to view and edit data in your database.

In this tutorial, you will be setting everything up from scratch and taking full advantage of these tools. We want to get you building stuff right away, so explanations of
Prisma concepts will be kept light but you can refer to the [Prisma docs](https://www.prisma.io/docs/) in case you want to dive deeper on any particular concept.

### Why Prisma?

You've now understood the basic mechanics of how GraphQL servers work under the hood and the beauty of GraphQL itself – it actually only follows a few very simple rules. The
statically typed schema and the GraphQL engine that resolves the queries inside the server take away major pain points commonly dealt with in API development.

Well, in real-world applications you're likely to encounter many scenarios where implementing the resolvers can become extremely complex. Especially because GraphQL queries can be
nested multiple levels deep, the implementation often becomes tricky and can easily lead to performance problems.

Most of the time, you also need to take care of many additional workflows such as authentication, authorization (permissions), pagination, filtering, realtime, integrating with
3rd-party services or legacy systems, and so on.

Prisma is focused on addressing that issue and [making developers more productive](https://www.prisma.io/docs/understand-prisma/why-prisma#prisma-makes-developers-productive) when
working with databases.

Speaking of being productive and building awesome stuff, let's jump back in and continue with our HackerNews Clone! 🏎💨

### Setting up our project with Prisma and SQLite

<Instruction>

First, let's install the Prisma CLI and Prisma Client by running the following command in your terminal:

```bash(path=".../hackernews-typescript/")
npm install prisma@^3.5.0 --save-dev
npm install @prisma/client@^3.5.0
```

</Instruction>

Next, use the Prisma CLI to initialize Prisma in the project.

<Instruction>

From your project root, run the following commands in your terminal:

```bash(path=".../hackernews-typescript/")
npx prisma init
```

</Instruction>

Remember the GraphQL schema that you've been working with until now? Well, Prisma has a schema, too! Inside the `prisma` directory that was created in the last step, you'll see a
file called `schema.prisma`. You can think of the `schema.prisma` file as a _database schema_. It has three components:

- **Data source**: Specifies your database connection.
- **Generator**: Indicates that you want to generate Prisma Client.
- **Data model**: Defines your application _models_. Each model will be mapped to a table in the underlying database.

Prisma's unique data model bridges the gap to help you reason about your data in a way that maps very well to the underlying database, while still providing an abstraction that
allows you to be productive with type safety and auto-completion.

Let's see it in action with your project!

<Instruction>

Open `schema.prisma` and add the following code:

```graphql(path=".../hackernews-typescript/prisma/schema.prisma")
// 1
datasource db {
  provider = "sqlite"
  url      = "file:./dev.db"
}

// 2
generator client {
  provider = "prisma-client-js"
}

// 3
model Link {
  id          Int      @id @default(autoincrement())   // 4
  createdAt   DateTime @default(now())  // 5
  description String
  url         String
}
```

</Instruction>

Let's dig deeper into this:

- `// 1`: **Data source**: Tells Prisma you'll be using SQLite for your database connection, along with the path to the SQLite file.
- `// 2`: **Generator**: Indicates that you want to generate Prisma Client.
- `// 3`: **Data model**: The `Link` model defines the structure of the `Link` database table that Prisma is going to create for you in a bit. Each field in the model consists of a field name, field type and additional attributes (`@id`, `@default`, etc) that define various behavior.
- `// 4`: The `@id` attribute signifies that the `id` field is the _primary-key_ for the `Link` database table. The `@default` attribute signifies how the field is to be generated if an explicit value is not specified when creating a `link` record.
- `// 5`: The `@default` attribute for `createdAt` also specifies the default value in case the `createdAt` field is not manually specified. The `DateTime` type follows a standard ISO 8601-formatted string (eg: `2021-11-16T21:48:39.798Z`).

> **Note:**  If you are using VS Code, you should install the [Prisma vscode extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) to make it easier to work with the `schema.prisma` file. Prisma also has integrations for other IDEs as well, which you can check out [here](https://www.prisma.io/docs/guides/development-environment/editor-setup).

## Getting started with SQLite

It's finally time to actually create our [SQLite](https://www.sqlite.org/index.html) database. In case you aren't familiar with SQLite, it is an in-process library that implements
a self-contained, serverless, zero-configuration, transactional SQL database engine.

The great thing is that, unlike most other SQL databases, SQLite does not have a separate server process. SQLite reads and writes directly to ordinary disk files. A complete SQL
database with multiple tables, indices, triggers, and views is contained in a single disk file. This makes it a perfect choice for projects like this.

So how about the setup? Well, the great news is that Prisma can do that for us right out of the box with a simple command!

<Instruction>

From the root directory of your project, create your first _migration_ by running the following command in your terminal:

```bash(path=".../hackernews-typescript/")
npx prisma migrate dev --name "init"
```

</Instruction>

Take a look at the `prisma` directory in your project's file system. You'll see that there is now a `/migrations` directory that Prisma Migrate created for you when running the
above command.

For now, the important thing to understand is that we have told Prisma with our data model, "I want to create a `Link` table to store data about _links_, and here's what that data will look like".

Prisma then generates the necessary migration and packages it into a dedicated directory with its own `.sql` file containing detailed information about the specific migration. This is then put inside that `prisma/migrations` directory, which becomes a historical reference of how your database evolves over time with each individual
migration you make!

Boom! 💥 You now have a database with a `Link` table! 🎉

Check out the [Prisma Migrate docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-migrate) for a deeper dive on this.

After running the migration, you should see a message similar to this:

```shell(nocopy)
Your database is now in sync with your schema.

✔ Generated Prisma Client (3.5.0) to ./node_modules/@prisma/client in 302ms
```

This means that Prisma has automatically generated _Prisma Client_ based on your data model. Prisma Client contains everything you need to run queries against your database. Just like Nexus it is designed to be completely type-safe. By default, Prisma Client is generated in `/node_modules/@prisma/client`, which can be imported and used in your code.

> *Note:* If for whatever reason you would like to regenerate Prisma Client, you can always do so independent of a migration using the `npx prisma generate` command.

Let's write your first query with Prisma Client and break everything down. You'll do that in a separate file to not mess with your current GraphQL server implementation.

<Instruction>

Create a new file in the `src/` directory called `script.ts`:

```bash(path=".../hackernews-typescript/")
touch src/script.ts
```

</Instruction>

The script file will contain the code for your first Prisma query.

<Instruction>

In `src/script.ts` write up the following code:

```typescript(path=".../hackernews-typescript/src/script.ts")
// 1
import { PrismaClient } from "@prisma/client";

// 2
const prisma = new PrismaClient();

// 3
async function main() {
    const allLinks = await prisma.link.findMany();
    console.log(allLinks);
}

// 4
main()
    .catch((e) => {
        throw e;
    })
    // 5
    .finally(async () => {
        await prisma.$disconnect();
    });
```

</Instruction>

Let's break down what's going on here with the numbered comments:

- `// 1`: Import the `PrismaClient` constructor from the `@prisma/client` node module.
- `// 2`: Instantiate `PrismaClient`.
- `// 3`: Define an `async` function called `main` to send queries to the database. You will write all your queries inside this function. You are calling the `findMany()` query, which will return all the `link` records that exist in the database.
- `// 4`: Call the `main` function.
- `// 5`: Close the database connections when the script terminates.

Take a moment to re-type the query line and notice the helpful autocompletion you get after typing `prisma.` and `prisma.link.`. The autocompletion lets us see all of the possible models we can
access and operations we can use to query that data:

![typing prisma. and prisma.link.](https://i.imgur.com/G52euHi.gif)

So now let's see things in action.

<Instruction>

Run your new code with the following command:

```bash(path=".../hackernews-typescript/")
npx ts-node src/script.ts
```

</Instruction>

You successfully queried the database with Prisma Client! Of course, you got an empty array back since the database is empty, so now let's quickly create a new link in the same
script.

<Instruction>

Type out the following lines of code inside of the `main` function right above the `allLinks` query and pay close attention to the incredibly helpful autocompletion:

```typescript(path=".../hackernews-typescript/src/script.ts")
const newLink = await prisma.link.create({
    data: {
      description: 'Fullstack tutorial for GraphQL',
      url: 'www.howtographql.com',
    },
  })
```

</Instruction>

Notice how the autocompletion suggestion helps us understand that `.create()` is the operation we need (just scroll through the options) and then it actually shows us exactly how to construct the mutation!

![You successfully queried the database with Prisma Client](https://i.imgur.com/d8r8WRp.gif)

Great! Re-run the previous command (`npx ts-node src/script.ts`) and this time you should now see your newly created link print in the terminal output.

```shell(nocopy)
[
  {
    id: 1,
    createdAt: 2021-11-16T21:48:39.798Z,
    description: 'Fullstack tutorial for GraphQL',
    url: 'www.howtographql.com'
  }
]
```

Much more satisfying ✨

### Summary of your workflow

To recap, this is the typical workflow you will follow when updating your data:

- Manually adjust your Prisma data model.
- Migrate your database using the `prisma migrate` CLI commands we covered.
- (Re-)generate Prisma Client.
- Use Prisma Client in your application code to access your database.

In the next chapters, you will evolve the API of your GraphQL server and use Prisma Client to access the database from inside your resolver functions.


text:
/// <reference path="_references.ts" />
module.exports = Curtain1;
/*jshint -W104 */ // Bitwise
const definesCurtain: IDefineExport = require("./defines");

/*
 * This is a class for controlling Harrison curtain controllers..
 */
function Curtain1(rfxcom: IRfxCom) {
    var self: ICurtain1 = this;
    self.rfxcom = rfxcom;
}

/*
 * Splits the device id x/y and returns the components, the deviceId will be
 * returned as the component bytes, ready for sending.
 *
 * Throws an Error if the format is invalid.
 */
Curtain1.prototype._splitDeviceId = function(deviceId : string) {
  var parts = deviceId.split("/");
  if (parts.length !== 2) {
      throw new Error("Invalid deviceId format.");
  }
  return {
      houseCode: parseInt(parts[0], 16),
      unitCode: parseInt(parts[1], 16)
  };
};

(<ICurtain1>Curtain1.prototype)._sendCommand = function(deviceId, command, callback) {
    var self: ICurtain1 = this;
    var device = self._splitDeviceId(deviceId);
    var cmdId = self.rfxcom.getCmdNumber();
    var buffer : number[] = [0x07, defines.CURTAIN1, 0x00, cmdId, device.houseCode, device.unitCode, command, 0];

  if (self.rfxcom.options.debug) {
      console.log("Sending %j", self.rfxcom.dumpHex(buffer));
  }
  self.rfxcom.serialport.write(buffer, function(err, response) {
      if (typeof callback === "function") {
          callback(err, response, cmdId);
      }
  });
  return cmdId;
};

/*
 * Open deviceId.
 */
Curtain1.prototype.open = function(deviceId, callback) {
    return (<ICurtain1>this)._sendCommand(deviceId, definesCurtain.CURTAIN_OPEN, callback);
};

/*
 * Close deviceId.
 */
Curtain1.prototype.close = function(deviceId, callback) {
    return (<ICurtain1>this)._sendCommand(deviceId, definesCurtain.CURTAIN_CLOSE, callback);
};

/*
 * Stop deviceId.
 */
Curtain1.prototype.stop = function(deviceId, callback) {
    return (<ICurtain1>this)._sendCommand(deviceId, definesCurtain.CURTAIN_STOP, callback);
};

/*
 * Open deviceId.
 */
Curtain1.prototype.program = function(deviceId, callback) {
    return (<ICurtain1>this)._sendCommand(deviceId, definesCurtain.CURTAIN_PROGRAM, callback);
};


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';

import { SharedModule } from '../shared/shared.module';
import {
  CanActivateAuthenticatedUserGuard,
  CanActivateUnauthenticatedUserGuard
} from '../shared/guards';
import { SensorListComponent } from './components';
import { SensorService } from './services';

import { SensorsRoutingModule } from './sensors-routing.module';
import { Last10DateKeysPipe } from '../shared/pipes';

@NgModule({
  imports: [
    CommonModule,
    ReactiveFormsModule,
    SharedModule,
   SensorsRoutingModule
  ],
  declarations: [
    SensorListComponent,
    Last10DateKeysPipe
  ],
  providers: [
    SensorService,
    CanActivateAuthenticatedUserGuard,
    CanActivateUnauthenticatedUserGuard
  ],
})
export class SensorsModule { }


text:
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using EPiServer;
using EPiServer.Core;
using EPiServer.Framework.DataAnnotations;
using EPiServer.Web.Mvc;
using EPiServer_angular.Models.Pages;

namespace EPiServer_angular.Controllers
{
    public class InsightsPageController : PageController<InsightsPage>
    {
        public ActionResult Index(InsightsPage currentPage)
        {
            /* Implementation of action. You can create your own view model class that you pass to the view or
             * you can pass the page type for simpler templates */

            return View(currentPage);
        }
    }
}


text:
package org.camunda.bpm.cockpit.plugin.acm;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

import org.camunda.bpm.engine.impl.cmmn.entity.runtime.CaseExecutionEntity;
import org.camunda.bpm.engine.runtime.CaseExecution;
import org.camunda.bpm.model.cmmn.impl.instance.CaseImpl;
import org.camunda.bpm.model.cmmn.impl.instance.CaseTaskImpl;
import org.camunda.bpm.model.cmmn.impl.instance.EventListenerImpl;
import org.camunda.bpm.model.cmmn.impl.instance.HumanTaskImpl;
import org.camunda.bpm.model.cmmn.impl.instance.MilestoneImpl;
import org.camunda.bpm.model.cmmn.impl.instance.PlanItemDefinitionImpl;
import org.camunda.bpm.model.cmmn.impl.instance.ProcessTaskImpl;
import org.camunda.bpm.model.cmmn.impl.instance.StageImpl;
import org.camunda.bpm.model.xml.instance.ModelElementInstance;

@XmlRootElement
public class DetailedCaseExecution implements Serializable {

  public static enum Type {
    HUMANTASK, CASETASK, PROCESSTASK, STAGE, CASE, MILESTONE, EVENTLISTENER;
  }

  /**
   * Factory method creating a detailed execution from case execution and case
   * execution entity.
   *
   * @param executionEntity
   *          case execution entity.
   * @param execution
   *          case execution.
   * @return
   */
  public static DetailedCaseExecution fromExecutionEntity(final CaseExecutionEntity executionEntity, final CaseExecution execution) {
    return new DetailedCaseExecution(executionEntity.getId(), executionEntity.getActivityId(), executionEntity.getCaseDefinitionId(),
        executionEntity.getCaseInstanceId(), execution.isEnabled(), execution.isActive(), execution.isDisabled());
  }

  /**
   * Factory method constructing a list of detailed case executions from list of
   * case executions.
   *
   * @param executions
   *          list of executions.
   * @return list of detailed executions.
   */
  public static List<DetailedCaseExecution> fromExecutions(final List<CaseExecution> executions) {
    final List<DetailedCaseExecution> tasks = new ArrayList<DetailedCaseExecution>();
    for (final CaseExecution ce : executions) {
      if (ce instanceof CaseExecutionEntity) {
        final CaseExecutionEntity cee = (CaseExecutionEntity) ce;
        if (cee.isCaseInstanceExecution()) {
          // skip the case model itself
          continue;
        }
        tasks.add(fromExecutionEntity(cee, ce));
      }
    }
    return tasks;
  }

  private static final long serialVersionUID = 1L;

  private String id;
  private String activityId;
  private String caseDefinitionId;
  private String caseInstanceId;
  private boolean enabled;
  private boolean disabled;
  private boolean active;

  private Type type;
  private String name;
  private String description;

  public DetailedCaseExecution(final String id, final String activity, final String caseDefinitionId, final String caseInstanceId, final boolean enabled,
      final boolean active, final boolean disabled) {
    this.id = id;
    this.activityId = activity;
    this.caseDefinitionId = caseDefinitionId;
    this.caseInstanceId = caseInstanceId;
    this.enabled = enabled;
    this.active = active;
    this.disabled = disabled;
  }

  public DetailedCaseExecution() {
  }

  public void enrichType(final ModelElementInstance element) {
    if (element instanceof HumanTaskImpl) {
      setType(DetailedCaseExecution.Type.HUMANTASK);
    } else if (element instanceof CaseTaskImpl) {
      setType(DetailedCaseExecution.Type.CASETASK);
    } else if (element instanceof CaseImpl) {
      setType(DetailedCaseExecution.Type.CASE);
    } else if (element instanceof StageImpl) {
      setType(DetailedCaseExecution.Type.STAGE);
    } else if (element instanceof ProcessTaskImpl) {
      setType(DetailedCaseExecution.Type.PROCESSTASK);
    } else if (element instanceof MilestoneImpl) {
      setType(DetailedCaseExecution.Type.MILESTONE);
    } else if (element instanceof EventListenerImpl) {
      setType(DetailedCaseExecution.Type.EVENTLISTENER);
    } else {
      // unknown type
      throw new IllegalStateException("Unknown model element of type " + element.getClass().getName() + " detected.");
    }
  }

  public void enrichLabels(final ModelElementInstance element) {
    if (element instanceof PlanItemDefinitionImpl) {
      final PlanItemDefinitionImpl pid = (PlanItemDefinitionImpl) element;
      setName(pid.getName());
      setDescription(pid.getDescription());
    }
  }

  public String getId() {
    return id;
  }

  public void setId(final String id) {
    this.id = id;
  }

  public String getActivityId() {
    return activityId;
  }

  public void setActivityId(final String activityId) {
    this.activityId = activityId;
  }

  public String getCaseDefinitionId() {
    return caseDefinitionId;
  }

  public void setCaseDefinitionId(final String caseDefinitionId) {
    this.caseDefinitionId = caseDefinitionId;
  }

  public String getCaseInstanceId() {
    return caseInstanceId;
  }

  public void setCaseInstanceId(final String caseInstanceId) {
    this.caseInstanceId = caseInstanceId;
  }

  public boolean isEnabled() {
    return enabled;
  }

  public void setEnabled(final boolean enabled) {
    this.enabled = enabled;
  }

  public boolean isActive() {
    return active;
  }

  public void setActive(final boolean active) {
    this.active = active;
  }

  public void setType(final Type type) {
    this.type = type;
  }

  public Type getType() {
    return type;
  }

  public String getName() {
    return name;
  }

  public void setName(final String name) {
    this.name = name;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(final String description) {
    this.description = description;
  }

  public boolean isDisabled() {
    return disabled;
  }

  public void setDisabled(final boolean disabled) {
    this.disabled = disabled;
  }

}


text:
//
//  UIImage+Rotate.m
//  图片选择器
//
//  Created by Lone on 16/7/6.
//  Copyright © 2016年 Mac. All rights reserved.
//

#import "UIImage+Rotate.h"

@implementation UIImage (Rotate)

/*
 * @brief rotate image 90 with CounterClockWise
 */
- (UIImage *)rotate90CounterClockwise
{
    UIImage *image = nil;
    switch (self.imageOrientation) {
        case UIImageOrientationUp:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationLeft];
            break;
        }
        case UIImageOrientationDown:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationRight];
            break;
        }
        case UIImageOrientationLeft:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationDown];
            break;
        }
        case UIImageOrientationRight:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationUp];
            break;
        }
        case UIImageOrientationUpMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationRightMirrored];
            break;
        }
        case UIImageOrientationDownMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationLeftMirrored];
            break;
        }
        case UIImageOrientationLeftMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationUpMirrored];
            break;
        }
        case UIImageOrientationRightMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationDownMirrored];
            break;
        }
        default:
            break;
    }

    return image;
}

/*
 * @brief rotate image 90 with Clockwise
 */
- (UIImage *)rotate90Clockwise
{
    UIImage *image = nil;
    switch (self.imageOrientation) {
        case UIImageOrientationUp:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationRight];
            break;
        }
        case UIImageOrientationDown:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationLeft];
            break;
        }
        case UIImageOrientationLeft:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationUp];
            break;
        }
        case UIImageOrientationRight:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationDown];
            break;
        }
        case UIImageOrientationUpMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationLeftMirrored];
            break;
        }
        case UIImageOrientationDownMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationRightMirrored];
            break;
        }
        case UIImageOrientationLeftMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationDownMirrored];
            break;
        }
        case UIImageOrientationRightMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationUpMirrored];
            break;
        }
        default:
            break;
    }

    return image;
}

/*
 * @brief rotate image 180 degree
 */
- (UIImage *)rotate180
{
    UIImage *image = nil;
    switch (self.imageOrientation) {
        case UIImageOrientationUp:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationDown];
            break;
        }
        case UIImageOrientationDown:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationUp];
            break;
        }
        case UIImageOrientationLeft:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationRight];
            break;
        }
        case UIImageOrientationRight:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationLeft];
            break;
        }
        case UIImageOrientationUpMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationDownMirrored];
            break;
        }
        case UIImageOrientationDownMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationUpMirrored];
            break;
        }
        case UIImageOrientationLeftMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationRightMirrored];
            break;
        }
        case UIImageOrientationRightMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationLeftMirrored];
            break;
        }
        default:
            break;
    }

    return image;
}

/*
 * @brief rotate image to default orientation
 */
- (UIImage *)rotateImageToOrientationUp
{
    CGSize size = CGSizeMake(self.size.width * self.scale, self.size.height * self.scale);
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, CGRectMake(0, 0, size.width, size.height));

    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

/*
 * @brief flip horizontal
 */
- (UIImage *)flipHorizontal
{
    UIImage *image = nil;
    switch (self.imageOrientation) {
        case UIImageOrientationUp:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationUpMirrored];
            break;
        }
        case UIImageOrientationDown:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationDownMirrored];
            break;
        }
        case UIImageOrientationLeft:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationRightMirrored];
            break;
        }
        case UIImageOrientationRight:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationLeftMirrored];
            break;
        }
        case UIImageOrientationUpMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationUp];
            break;
        }
        case UIImageOrientationDownMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationDown];
            break;
        }
        case UIImageOrientationLeftMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationRight];
            break;
        }
        case UIImageOrientationRightMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationLeft];
            break;
        }
        default:
            break;
    }

    return image;
}

/*
 * @brief flip vertical
 */
- (UIImage *)flipVertical
{
    UIImage *image = nil;
    switch (self.imageOrientation) {
        case UIImageOrientationUp:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationDownMirrored];
            break;
        }
        case UIImageOrientationDown:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationUpMirrored];
            break;
        }
        case UIImageOrientationLeft:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationLeftMirrored];
            break;
        }
        case UIImageOrientationRight:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationRightMirrored];
            break;
        }
        case UIImageOrientationUpMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationDown];
            break;
        }
        case UIImageOrientationDownMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationUp];
            break;
        }
        case UIImageOrientationLeftMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationLeft];
            break;
        }
        case UIImageOrientationRightMirrored:
        {
            image = [UIImage imageWithCGImage:self.CGImage scale:1 orientation:UIImageOrientationRight];
            break;
        }
        default:
            break;
    }

    return image;
}

/*
 * @brief flip horizontal and vertical
 */
- (UIImage *)flipAll
{
    return [self rotate180];
}

@end


text:
<?php

namespace Noherczeg\RestExt\Services;

interface AuthorizationService {

    /**
     * Checks if the authenticated User has any of the given Roles (names) specified in the parameter array
     *
     * @param array $roles  Array of strings
     * @return boolean
     */
    public function hasRoles(array $roles);

    /**
     * Checks if the authenticated User has the given Role or not
     *
     * @param string $role
     * @return boolean
     */
    public function hasRole($role);

}


text:
class Activity < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
  validates :title, :happened_at, :project, :user, presence: true
  validates :summary, length: { maximum: 140 }, allow_nil: true
end


text:
dojo.provide("util.docscripts.tests.doctests");

dojo.require("util.docscripts.tests.basic");


text:
A Dockerfile describing an container capable of executing s source files.

# Build

```sh
git clone https://github.com/docker-exec/coffee.git
docker build -t dexec/lang-coffee .
```

# Usage

In a directory containing a script e.g. foo.coffee, run:

```sh
docker run -t --rm \
    -v $(pwd -P)/foo.coffee:/tmp/dexec/build/foo.coffee \
    dexec/lang-coffee foo.coffee
```

## Passing arguments to the script

Arguments can be passed to the script using any of the following forms:

```
-a argument
--arg argument
--arg=argument
```

Each argument passed must be prefixed in this way, e.g.

```sh
docker run -t --rm \
    -v $(pwd -P)/foo.coffee:/tmp/dexec/build/foo.coffee \
    dexec/lang-coffee foo.coffee \
    --arg='hello world' \
    --arg=foo \
    --arg=bar
```


text:
Spinkit.Xaml
============

A port of a collection of styles for the Windows 8 Progress Ring control, inspired by the CSS [SpinKit][sk] by [Tobias Ahlin][ta]. Demo video available on [Youtube: Spinkit Xaml demo][yt].

Usage
-----

Install the nuget package:

```PowerShell
Install-Package Spinkit.Xaml
```

Which will import the **Spinkit.Styles.xaml** resource dictionary into your projects. You can then import this dictionary in your *App.xaml*.

```Xml
<Application.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="Spinkit.Styles.xaml" />
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Application.Resources>
```

You can then mark up your Progress Ring controls with the new styles.

```Xml
<ProgressRing IsActive="True" Style="{StaticResource RotatingPlaneProgressRingStyle}" />
```

Check out the sample app in this repository to browse all the available styles.

[sk]: http://tobiasahlin.com/spinkit/
[ta]: https://twitter.com/tobiasahlin
[yt]: http://www.youtube.com/watch?v=Lr5EulwTYz0


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

package com.google.collide.client.code;

import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.communication.FrontendApi;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.communication.MessageFilter;
import com.google.collide.client.communication.MessageFilter.MessageRecipient;
import com.google.collide.client.util.QueryCallbacks.SimpleCallback;
import com.google.collide.dto.GetWorkspaceParticipants;
import com.google.collide.dto.GetWorkspaceParticipantsResponse;
import com.google.collide.dto.ParticipantUserDetails;
import com.google.collide.dto.RoutingTypes;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.UserDetails;
import com.google.collide.dto.client.DtoClientImpls.GetWorkspaceParticipantsImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.client.JsoStringSet;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringSet;
import com.google.collide.shared.util.JsonCollections;

/**
 * Model for the participants in the current workspace.
 */
// TODO: Pass the initial list of participants from the workspace bootstrap response
public class ParticipantModel {

  /**
   * Listener for changes in the participant model.
   *
   */
  public interface Listener {
    void participantAdded(Participant participant);

    void participantRemoved(Participant participant);
  }

  private static class ColorGenerator {

    private static final String[] COLORS = new String[] {"#FC9229", // Orange
        "#51D13F", // Green
        "#B744D1", // Purple
        "#3BC9D1", // Cyan
        "#D13B45", // Pinky Red
        "#465FE6", // Blue
        "#F41BDB", // Magenta
        "#B7AC4A", // Mustard
        "#723226" // Brown
    };

    private int previousColorIndex = -1;

    private String nextColor() {
      previousColorIndex = (previousColorIndex + 1) % COLORS.length;
      return COLORS[previousColorIndex];
    }
  }

  public static ParticipantModel create(FrontendApi frontendApi, MessageFilter messageFilter) {
    ParticipantModel model = new ParticipantModel(frontendApi);
    model.registerForInvalidations(messageFilter);
    model.requestAllParticipants();
    return model;
  }

  private final JsoArray<Listener> listeners;

  /**
   * The last callback created when requesting all participants. If this is null, then the last
   * request was for specific participants.
   */
  private SimpleCallback<JsonArray<ParticipantUserDetails>> lastRequestAllCallback;

  /**
   * The set of all active participant ids, including participants who have not been added to the
   * participant list because we don't have user details yet.
   */
  private JsonStringSet presentParticipantsTracker = JsoStringSet.create();

  private final JsoStringMap<Participant> participantsByUserId = JsoStringMap.create();

  private final JsoStringMap<String> clientIdToUserId = JsoStringMap.create();

  /**
   * A map of user ID to the {@link UserDetails} for the participant. We cache participant info in
   * case users connect and disconnect rapidly. We keep the cache here so we can discard it when the
   * user leaves the workspace.
   */
  // TODO: Should we persist user details for the entire session?
  private final JsoStringMap<UserDetails> participantUserDetails = JsoStringMap.create();

  /**
   * Tracks the number of participants (optimization for otherwise having to iterate participants to
   * get its size).
   */
  private int count;
  private final ColorGenerator colorGenerator;
  private Participant self;
  private final FrontendApi frontendApi;

  private ParticipantModel(FrontendApi frontendApi) {
    this.frontendApi = frontendApi;
    colorGenerator = new ColorGenerator();
    listeners = JsoArray.create();
  }

  public void addListener(Listener listener) {
    listeners.add(listener);
  }

  public int getCount() {
    return count;
  }

  public String getUserId(final String clientId) {
    return clientIdToUserId.get(clientId);
  }

  public Participant getParticipantByUserId(final String id) {
    return participantsByUserId.get(id);
  }

  /**
   * Gets the participants keyed by user id. Do not modify the returned map (not enforced for
   * performance reasons).
   */
  public JsoStringMap<Participant> getParticipants() {
    return participantsByUserId;
  }

  public Participant getSelf() {
    return self;
  }

  private void registerForInvalidations(MessageFilter messageFilter) {
    messageFilter.registerMessageRecipient(RoutingTypes.GETWORKSPACEPARTICIPANTSRESPONSE,
        new MessageRecipient<GetWorkspaceParticipantsResponse>() {

            @Override
          public void onMessageReceived(GetWorkspaceParticipantsResponse message) {
            handleParticipantUserDetails(message.getParticipants(), true);
          }
        });
  }

  public void removeListener(Listener listener) {
    listeners.remove(listener);
  }

  private void createAndAddParticipant(
      com.google.collide.dto.Participant participantDto, UserDetails userDetails) {
    boolean isSelf =
        participantDto.getUserId().equals(BootstrapSession.getBootstrapSession().getUserId());
    String color = isSelf ? "black" : colorGenerator.nextColor();
    Participant participant = Participant.create(
        participantDto, userDetails.getDisplayName(), userDetails.getDisplayEmail(), color, isSelf);
    participantsByUserId.put(participantDto.getUserId(), participant);
    count++;

    if (isSelf) {
      self = participant;
    }

    dispatchParticipantAdded(participant);
  }

  private void dispatchParticipantAdded(Participant participant) {
    for (int i = 0, n = listeners.size(); i < n; i++) {
      listeners.get(i).participantAdded(participant);
    }
  }

  private void dispatchParticipantRemoved(Participant participant) {
    for (int i = 0, n = listeners.size(); i < n; i++) {
      listeners.get(i).participantRemoved(participant);
    }
  }

  /**
   * Requests all participants.
   */
  private void requestAllParticipants() {
    lastRequestAllCallback =
      new SimpleCallback<JsonArray<ParticipantUserDetails>>("Failed to retrieve participants") {
      @Override
      public void onQuerySuccess(JsonArray<ParticipantUserDetails> result) {
        /*
         * If there is still an outstanding request for all participants, we should replace all
         * participants with these results. Even if this request isn't the last request for all
         * participants, we should still replace all participants or we might flail in a busy
         * workspace and never update the list.
         *
         * If we've received a tango message containing the updated list of participants,
         * lastRequestAllCallback will be null and we should not replace all participants.
         */
        boolean replaceAll = (lastRequestAllCallback != null);

        /*
         * If this is the last callback, then set lastRequestAllCallback to null so older
         * lastRequestAllCallbacks received out of order do not overwrite the most recent callback.
         */
        if (this == lastRequestAllCallback) {
          lastRequestAllCallback = null;
        }

        handleParticipantUserDetails(result, replaceAll);
      }
    };

    GetWorkspaceParticipants req = GetWorkspaceParticipantsImpl.make();
    frontendApi.GET_WORKSPACE_PARTICIPANTS.send(
        req, new ApiCallback<GetWorkspaceParticipantsResponse>() {

          @Override
          public void onMessageReceived(GetWorkspaceParticipantsResponse message) {
            lastRequestAllCallback.onQuerySuccess(message.getParticipants());
          }

          @Override
          public void onFail(FailureReason reason) {
            // Do nothing.
          }
        });
  }

  /**
   * Updates the model with the participant user details.
   *
   * @param isAllParticipants true if the result contains the complete list of participants
   */
  private void handleParticipantUserDetails(
      JsonArray<ParticipantUserDetails> result, boolean isAllParticipants) {
    // Reset the tracker if the result is all inclusive.
    if (isAllParticipants) {
      presentParticipantsTracker = JsonCollections.createStringSet();
    }

    for (int i = 0; i < result.size(); i++) {
      ParticipantUserDetails item = result.get(i);
      UserDetails userDetails = item.getUserDetails();
      String userId = userDetails.getUserId();

      // Cache the participants' user details.
      participantUserDetails.put(userId, userDetails);
      clientIdToUserId.put(item.getParticipant().getId(), userId);

      if (isAllParticipants) {
        presentParticipantsTracker.add(userId);
        if (!participantsByUserId.containsKey(userId)) {
          createAndAddParticipant(item.getParticipant(), userDetails);
        }
      } else {
        /*
         * Add the participant to the list. If the user is not in presentParticipantsTracker set,
         * then the participant has since disconnected. If the user is in the participants map, then
         * the user was already added to the view.
         */
        if (presentParticipantsTracker.contains(userId)
            && !participantsByUserId.containsKey(userId)) {
          createAndAddParticipant(item.getParticipant(), userDetails);
        }
      }
    }

    // Sweep through participants to find removed participants.
    removeOldParticipants();
  }

  /**
   * Removes users who have left the workspace from the participant list.
   */
  private void removeOldParticipants() {
    // NOTE: Iterating collection that is not affected by removing.
    for (String userId : participantsByUserId.getKeys().asIterable()) {
      if (!presentParticipantsTracker.contains(userId)) {
        Participant participant = participantsByUserId.remove(userId);
        if (participant != null) {
          count--;
          dispatchParticipantRemoved(participant);
        }

        for (String clientId : clientIdToUserId.getKeys().asIterable()) {
          if (clientIdToUserId.get(clientId).equals(userId)) {
            clientIdToUserId.remove(clientId);
          }
        }
      }
    }
  }
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'pry'
require 'hystrix'

RSpec.configure do |config|
  config.mock_with :rspec
end


text:
<!DOCTYPE html>

<title>Faq</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="" />

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

<link href="css/style.css" rel='stylesheet' type='text/css' />

<link href='http://fonts.useso.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

<link rel="stylesheet" href="css/font.css" type="text/css"/>
<link href="css/font-awesome.css" rel="stylesheet">

					Dashboard

					UI Components

					Buttons

					Grids

				Forms

						Inputs

						Form Validation

						Pages

							Image Gallery

							Calendar

							Sign Up Page

							Login Page

						Charts

					Typography

					Tables

					Maps

					Error Page

					Extras

						FAQ

						Blank Page

			Logout

Colored

					<button id="toggle"></button>

				<form action="#" method="post">
					<input type="text" name="Product" value="search" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Search';}" required="">
					<button class="btn btn-default" type="submit"></button>
				</form>

								3

You have 3 new messages

Lorem ipsum dolor amet

1 hour ago

Lorem ipsum dolor amet

1 hour ago

Lorem ipsum dolor amet

1 hour ago

											See all messages

								3

You have 3 new notifications

Lorem ipsum dolor amet

1 hour ago

Lorem ipsum dolor amet

1 hour ago

Lorem ipsum dolor amet

1 hour ago

											See all notifications

								15

You have 8 pending tasks

											Database update40%

											Dashboard done90%

											Mobile App33%

											Issues fixed80%

											See all pending tasks

  Settings

  Profile

  Logout

Frequently Asked Questions

						Home

						Faqs

1.What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

2.What is Lorem Ipsum dummy text ever since the 1500s?

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

3.What is Duis laoreet, erat quis gravida porttitor odio felis ornare dui?

Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam semper elit risus, nec suscipit tellus tincidunt quis. Fusce non auctor enim. Suspendisse sit amet erat mollis, suscipit nisl sed, condimentum turpis. Curabitur faucibus, nisl ut aliquam porta, massa tortor tristique dolor, eget porttitor velit ligula vel eros. Sed egestas aliquet tellus. Nulla ac luctus urna. Pellentesque feugiat eros quis nibh consectetur, eget dapibus magna egestas. Phasellus non efficitur metus.

4.What is Quisque sollicitudin diam vel mauris volutpat viverra Proin ac imperdiet libero?

Proin dignissim mi sit amet tincidunt varius. Quisque molestie fermentum dignissim. Sed in urna eget tortor congue tempus. Vestibulum gravida, erat in eleifend ultricies, felis lorem dictum nulla, ut tincidunt neque libero et nibh. Nullam at eros eu ligula auctor interdum a eget lorem. Praesent molestie eros vitae felis efficitur, at finibus sem molestie. Ut sit amet nisi at nunc pulvinar dapibus. Sed non neque et tortor finibus mattis. Mauris sit amet consectetur eros. Sed et ex posuere, vulputate dolor vel, pulvinar felis.

5.What is Nam semper elit risus, nec suscipit tellus tincidunt quis?

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

6.What is Quisque molestie fermentum dignissim?

Sed eget nunc ex. Donec erat est, dapibus ac massa in, laoreet sagittis eros. Aliquam eget arcu feugiat leo elementum tristique. Praesent facilisis aliquam lorem sed pharetra. Donec scelerisque ipsum vel tincidunt gravida. Aliquam erat volutpat. Etiam mattis rhoncus massa, quis semper purus ornare id. Quisque sit amet mattis ipsum, in porttitor massa. Nullam tincidunt mi vel enim volutpat, a elementum libero imperdiet. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean tincidunt eros eu nisl consequat facilisis. Maecenas ac accumsan elit, sit amet gravida nulla.

7.What is Vestibulum ante ipsum primis in faucibus orci luctus et?

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Copyright © 2016.Company name All rights reserved.网页模板


text:
import re
import os
import datetime
from flask import Flask, abort
import humanfriendly
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Resource, Api, reqparse
from raven.contrib.flask import Sentry
import sqlalchemy

app = Flask(__name__)
sentry = Sentry(app)
application = app  # noqa
app.config['DEBUG'] = os.environ.get('APP_DEBUG', False)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

if 'RDS_HOSTNAME' in os.environ:
    db_creds = {'user': os.environ['RDS_USERNAME'],
                'password': os.environ['RDS_PASSWORD'],
                'host': os.environ['RDS_HOSTNAME'],
                'port': os.environ['RDS_PORT'],
                'database': os.environ['RDS_DB_NAME']}
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'mysql://{user}:{password}@{host}:{port}/{database}'.format(**db_creds)
else:
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
        os.path.expanduser('~/{}.db'.format('slack-locate'))

app.config['SLACK_TOKEN'] = os.environ.get('SLACK_TOKEN', '')
db = SQLAlchemy(app)
api = Api(app)

class MalformedRequest(Exception):
    pass

def parse_date(date):
    date = date.strip().lower()
    # TODO: handle day names (e.g. 'monday', 'tuesday', ...)
    if date == 'today':
        return datetime.date.today()
    elif date == 'tomorrow':
        return datetime.date.today() + datetime.timedelta(days=1)
    else:
        return datetime.date(*humanfriendly.parse_date(date)[:3])

def parse_command(text):
    mode = text.split()[0]
    if mode == 'set':
        text = ' '.join(text.split()[1:])
        time_regexp = '(?P<place>\S+)( (?P<start>\S+)?( (to|until)? (?P<end>\S+)?){0,1}){0,1}'
        details = re.match(time_regexp, text)
        if details:
            details = details.groupdict()
            for moment in ('start', 'end'):
                if details[moment]:
                    details[moment] = parse_date(details[moment])
                details['place'] = details['place'].lower()
            details['action'] = 'set'
            return details
        else:
            raise MalformedRequest(text)
    else:
        username = text.strip().lstrip('@').lower()
        return {'action': 'get', 'name': username}

class Team(db.Model):
    id = db.Column(db.Unicode(64), primary_key=True)
    domain = db.Column(db.Unicode(256))

class User(db.Model):
    id = db.Column(db.Unicode(64), primary_key=True)
    name = db.Column(db.Unicode(256))
    team_id = db.Column(db.Unicode(64), db.ForeignKey('team.id'))
    team = db.relationship('Team', backref=db.backref('users'))

    def __repr__(self):
        return '<User {} "{}">'.format(self.id, self.name)

    def location(self):
        return self.locations[-1].place

class Location(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    start_date = db.Column(db.DateTime)
    end_date = db.Column(db.DateTime)
    place = db.Column(db.Unicode(256))
    user_id = db.Column(db.Unicode(64), db.ForeignKey('user.id'))
    user = db.relationship('User', backref=db.backref('locations'))

    def __repr__(self):
        return '<Location {}@{}>'.format(self.user.name, self.place)

class LocationService(Resource):

    def post(self):
        parser = reqparse.RequestParser(bundle_errors=True)
        parser.add_argument('token', type=str, required=True)
        parser.add_argument('user_id', type=str, required=True)
        parser.add_argument('user_name', type=str, required=True)
        parser.add_argument('team_id', type=str, required=True)
        parser.add_argument('team_domain', type=str, required=True)
        parser.add_argument('text', type=str, required=True)

        args = parser.parse_args()

        if args['token'] != app.config['SLACK_TOKEN']:
            abort(403, 'wrong Slack token')

        s = db.session
        command = parse_command(args['text'])

        if command['action'] == 'set':
            user = User.query.get(args['user_id'])
            if not user:
                team = Team.query.get(args['team_id'])
                if not team:
                    team = Team(id=args['team_id'], domain=args['team_domain'])
                    s.add(team)
                user = User(id=args['user_id'],
                            name=args['user_name'].lower(),
                            team=team)
                s.add(user)
            location = Location(start_date=command['start'],
                                end_date=command['end'],
                                user=user,
                                place=command['place'])
            s.add(location)
            s.commit()
            return {'text': 'Your position is now: {}'.format(location.place)}
        elif command['action'] == 'get':
            try:
                target = User.query.filter_by(name=command['name'],
                                              team_id=args['team_id']).one()
            except sqlalchemy.orm.exc.NoResultFound:
                return {'text': 'Sorry, no known location for {}'.format(command['name'])}
            place = target.location()
            return {'text': "{} is in/at {} today".format(target.name,
                                                          place.title())}
        abort(400)

api.add_resource(LocationService, '/')

if not app.config['TESTING']:
    db.create_all()

if __name__ == '__main__':
    app.run()


text:
4Clojure solutions

## How to run it

Run 'lein test'


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = once;
function once(fn) {
    return function () {
        if (fn === null) return;
        var callFn = fn;
        fn = null;
        callFn.apply(this, arguments);
    };
}
module.exports = exports['default'];


text:
DECLARE
	@LastUpdDt SMALLDATETIME = GETDATE(),
	@LastUpdUs NVARCHAR(50) = N'SV',
	@CouncilId INT = 1;

INSERT INTO [DocumentType]([Name], [CouncilId], [LastUpdDt], [LastUpdUs])
SELECT N'свідоцтво', @CouncilId, @LastUpdDt, @LastUpdUs;

INSERT INTO [DocumentType]([Name], [CouncilId], [LastUpdDt], [LastUpdUs])
SELECT N'посвідчення', @CouncilId, @LastUpdDt, @LastUpdUs;


text:
<?php

// src/AppBundle/Controller/ScheduleController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

use AppBundle\Entity\Exam;
use AppBundle\Entity\GradeExam;

class ScheduleController extends Controller
{

    /**
     * @Route("/teacher/schedule")
     */
    public function display() {

        $em = $this->getDoctrine()->getManager();
        $q = $em->createQuery("select l from AppBundle:Lesson l left join l.classOfStudents cl join cl.year y left join l.period p left join l.teacher t where t.id=:id and y.active=true order by p.ordinal")
        ->setParameter("id", $this->get('security.context')->getToken()->getUser()->getId());

        $lessons = $q->getResult();

        //print_r ($students);

        return $this->render('views/teacher/schedule.html.twig', array(
            "lessons" => $lessons
        ));
    }
}


text:
#pragma once

/**
 * Test STM32F1-specific configuration values for errors at compile-time.
 */

#if ENABLED(SDCARD_EEPROM_EMULATION) && DISABLED(SDSUPPORT)
  #undef SDCARD_EEPROM_EMULATION // Avoid additional error noise
  #if USE_FALLBACK_EEPROM
    #warning "EEPROM type not specified. Fallback is SDCARD_EEPROM_EMULATION."
  #endif
  #error "SDCARD_EEPROM_EMULATION requires SDSUPPORT. Enable SDSUPPORT or choose another EEPROM emulation."
#endif

#if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  #error "SERIAL_STATS_MAX_RX_QUEUED is not supported on the STM32F1 platform."
#elif ENABLED(SERIAL_STATS_DROPPED_RX)
  #error "SERIAL_STATS_DROPPED_RX is not supported on the STM32F1 platform."
#endif

#if ENABLED(NEOPIXEL_LED) && DISABLED(MKS_MINI_12864_V3)
  #error "NEOPIXEL_LED (Adafruit NeoPixel) is not supported for HAL/STM32F1. Comment out this line to proceed at your own risk!"
#endif

// Emergency Parser needs at least one serial with HardwareSerial or USBComposite.
// The USBSerial maple don't allow any hook to implement EMERGENCY_PARSER.
// And copy all USBSerial code to marlin space to support EMERGENCY_PARSER, when we have another options, don't worth it.
#if ENABLED(EMERGENCY_PARSER) && !defined(USE_USB_COMPOSITE) && ((SERIAL_PORT == -1 && !defined(SERIAL_PORT_2)) || (SERIAL_PORT_2 == -1 && !defined(SERIAL_PORT)))
  #error "EMERGENCY_PARSER is only supported by HardwareSerial or USBComposite in HAL/STM32F1."
#endif


text:
require 'net/ssh/transport/session'
require 'net/ssh/connection/session'
require 'net/ssh/test/kex'
require 'net/ssh/test/socket'

module Net
  module SSH
    # This module may be used in unit tests, for when you want to test that your
    # SSH state machines are really doing what you expect they are doing. You will
    # typically include this module in your unit test class, and then build a
    # "story" of expected sends and receives:
    #
    #   require 'minitest/autorun'
    #   require 'net/ssh/test'
    #
    #   class MyTest < Minitest::Test
    #     include Net::SSH::Test
    #
    #     def test_exec_via_channel_works
    #       story do |session|
    #         channel = session.opens_channel
    #         channel.sends_exec "ls"
    #         channel.gets_data "result of ls"
    #         channel.gets_close
    #         channel.sends_close
    #       end
    #
    #       assert_scripted do
    #         result = nil
    #
    #         connection.open_channel do |ch|
    #           ch.exec("ls") do |success|
    #             ch.on_data { |c, data| result = data }
    #             ch.on_close { |c| c.close }
    #           end
    #         end
    #
    #         connection.loop
    #         assert_equal "result of ls", result
    #       end
    #     end
    #   end
    #
    # See Net::SSH::Test::Channel and Net::SSH::Test::Script for more options.
    #
    # Note that the Net::SSH::Test system is rather finicky yet, and can be kind
    # of frustrating to get working. Any suggestions for improvement will be
    # welcome!
    module Test
      # If a block is given, yields the script for the test socket (#socket).
      # Otherwise, simply returns the socket's script. See Net::SSH::Test::Script.
      def story
        Net::SSH::Test::Extensions::IO.with_test_extension { yield socket.script if block_given? }
        return socket.script
      end

      # Returns the test socket instance to use for these tests (see
      # Net::SSH::Test::Socket).
      def socket(options = {})
        @socket ||= Net::SSH::Test::Socket.new
      end

      # Returns the connection session (Net::SSH::Connection::Session) for use
      # in these tests. It is a fully functional SSH session, operating over
      # a mock socket (#socket).
      def connection(options = {})
        @connection ||= Net::SSH::Connection::Session.new(transport(options), options)
      end

      # Returns the transport session (Net::SSH::Transport::Session) for use
      # in these tests. It is a fully functional SSH transport session, operating
      # over a mock socket (#socket).
      def transport(options = {})
        @transport ||= Net::SSH::Transport::Session.new(
          options[:host] || "localhost",
          options.merge(kex: "test", host_key: "ssh-rsa", append_all_supported_algorithms: true, verify_host_key: :never, proxy: socket(options))
        )
      end

      # First asserts that a story has been described (see #story). Then yields,
      # and then asserts that all items described in the script have been
      # processed. Typically, this is called immediately after a story has
      # been built, and the SSH commands being tested are then executed within
      # the block passed to this assertion.
      def assert_scripted
        raise "there is no script to be processed" if socket.script.events.empty?

        Net::SSH::Test::Extensions::IO.with_test_extension { yield }
        assert socket.script.events.empty?, "there should not be any remaining scripted events, but there are still" \
                                            "#{socket.script.events.length} pending"
      end
    end
  end
end


text:
package ch.demo.test;

public @interface IntegrationTest {

}


text:
The parsing of URL parameters is slightly different to usual servers.

For example, let's assume you have a page called `users` which is available by visiting `/users`. The same page and its controller will be called when you request `/users/MyName` or even `/users/MyName/profile`.

In all cases you can access `request.params` inside the `users.js` controller which gives you an array of parameters:

```js
// users
[]

// users/MyName
['MyName']

// users/MyName/profile
['MyName', 'profile']
```

## Query parameters

If you don't like the Aero way of passing parameters to a page you can still use the traditional way and access parameters via `request.query`:

```js
// users?userName=MyName&component=profile
{
	userName: 'MyName',
	component: 'profile'
}
```


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Result | MultiValidator TypeScript PascalSystem</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					MultiValidator TypeScript PascalSystem

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"main"

					Validator

					Result

Class Result

Validator result

Hierarchy

						Result

Index

Constructors

constructor

Properties

errors

Methods

add<wbr>Error

get<wbr>Errors

has<wbr>Error<wbr>Code

is<wbr>Valid

merge<wbr>Errors

Constructors

constructor

new <wbr>Result(): Result

Defined in main.ts:452

Returns Result

Properties

Private errors

errors: ResultItem[]

Defined in main.ts:452

Errors items

Methods

add<wbr>Error

add<wbr>Error(code: string, params: any[]): void

Defined in main.ts:462

Add error code

Parameters

code: string

params: any[]

Returns void

get<wbr>Errors

get<wbr>Errors(): ResultItem[]

Defined in main.ts:484

Get error result items list

Returns ResultItem[]

has<wbr>Error<wbr>Code

has<wbr>Error<wbr>Code(code: string): boolean

Defined in main.ts:496

Has error code

Parameters

code: string

Returns boolean

is<wbr>Valid

is<wbr>Valid(): boolean

Defined in main.ts:490

Get is valid result

Returns boolean

merge<wbr>Errors

merge<wbr>Errors(errors: ResultItem[]): void

Defined in main.ts:473

Merge result items

Parameters

errors: ResultItem[]

Returns void

						Globals

						Result

								constructor

								errors

								add<wbr>Error

								get<wbr>Errors

								has<wbr>Error<wbr>Code

								is<wbr>Valid

								merge<wbr>Errors

						Validator<wbr>Abstract

						Validator<wbr>Clean<wbr>String

						Validator<wbr>Date

						Validator<wbr>Email

						Validator<wbr>Integer

						Validator<wbr>Number

						Validator<wbr>Reg<wbr>Exp

						Validator<wbr>String

						Result<wbr>Item

						Validator<wbr>Clean<wbr>String<wbr>Options

						Validator<wbr>Email<wbr>Options

						Validator<wbr>Number<wbr>Options

						Validator<wbr>Options

						Validator<wbr>Reg<wbr>Exp<wbr>Options

						Validator<wbr>String<wbr>Options

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit0ddd41afaef4ab812948b7c6ebaadbab::getLoader();


text:
import yaql.tests

class TestMath(yaql.tests.TestCase):
    def test_binary_plus_int(self):
        res = self.eval('2 + 3')
        self.assertEqual(5, res)
        self.assertIsInstance(res, int)

    def test_binary_plus_float(self):
        res = self.eval('2 + 3.0')
        self.assertEqual(5, res)
        self.assertIsInstance(res, float)

        res = self.eval('2.3+3.5')
        self.assertEqual(5.8, res)
        self.assertIsInstance(res, float)

    def test_binary_minus_int(self):
        res = self.eval('12 -3')
        self.assertEqual(9, res)
        self.assertIsInstance(res, int)

    def test_binary_minus_float(self):
        res = self.eval('1 - 2.1')
        self.assertEqual(-1.1, res)
        self.assertIsInstance(res, float)

        res = self.eval('123.321- 0.321')
        self.assertEqual(123.0, res)
        self.assertIsInstance(res, float)

    def test_multiplication_int(self):
        res = self.eval('3 * 2')
        self.assertEqual(6, res)
        self.assertIsInstance(res, int)
        self.assertEqual(-6, self.eval('3 * -2'))
        self.assertEqual(6, self.eval('-3 * -2'))

    def test_multiplication_float(self):
        res = self.eval('3.0 * 2.0')
        self.assertEqual(6.0, res)
        self.assertIsInstance(res, float)
        self.assertAlmostEqual(-6.51, self.eval('3.1 * -2.1'))
        self.assertAlmostEqual(6.51, self.eval('-3.1 * -2.1'))

    def test_division(self):
        self.assertEqual(3, self.eval('7 / 2'))
        self.assertEqual(-4, self.eval('7 / -2'))
        self.assertAlmostEqual(2.5, self.eval('5 / 2.0'))
        self.assertAlmostEqual(2.5, self.eval('5.0 / 2'))
        self.assertAlmostEqual(-2.5, self.eval('-5.0 / 2.0'))
        self.assertRaises(ZeroDivisionError, self.eval, '7 / 0')
        self.assertRaises(ZeroDivisionError, self.eval, '7 / -0.0')

    def test_brackets(self):
        self.assertEqual(-4, self.eval('1 - (2) - 3'))
        self.assertEqual(2, self.eval('1 - (2 - 3)'))

    def test_unary_minus(self):
        self.assertEqual(-4, self.eval('-4'))
        self.assertEqual(-12.0, self.eval('-12.0'))
        self.assertEqual(4, self.eval('3--1'))
        self.assertEqual(2, self.eval('3+-1'))
        self.assertAlmostEqual(4.3, self.eval('3.2 - -1.1'))
        self.assertEqual(2, self.eval('-(1-3)'))

    def test_unary_plus(self):
        self.assertEqual(4, self.eval('+4'))
        self.assertEqual(12.0, self.eval('+12.0'))
        self.assertEqual(2, self.eval('3-+1'))
        self.assertEqual(4, self.eval('3++1'))
        self.assertAlmostEqual(2.1, self.eval('3.2 - +1.1'))

    def test_modulo_int(self):
        res = self.eval('9 mod 5')
        self.assertEqual(4, res)
        self.assertIsInstance(res, int)
        self.assertEqual(-1, self.eval('9 mod -5'))

    def test_modulo_float(self):
        res = self.eval('9.0 mod 5')
        self.assertEqual(4.0, res)
        self.assertIsInstance(res, float)

        res = self.eval('9 mod 5.0')
        self.assertEqual(4.0, res)
        self.assertIsInstance(res, float)

        res = self.eval('9.0 mod 5.0')
        self.assertEqual(4.0, res)
        self.assertIsInstance(res, float)

        self.assertAlmostEqual(-1.1, self.eval('9.1 mod -5.1'))

    def test_abs(self):
        self.assertEqual(4, self.eval('abs(-4)'))
        self.assertEqual(4, self.eval('abs(4)'))
        self.assertEqual(4.4, self.eval('abs(-4.4)'))

    def test_gt(self):
        res = self.eval('5 > 3')
        self.assertIsInstance(res, bool)
        self.assertTrue(res)
        self.assertFalse(self.eval('3 > 3'))

    def test_lt(self):
        res = self.eval('3 < 5')
        self.assertIsInstance(res, bool)
        self.assertTrue(res)
        self.assertFalse(self.eval('3 < 3'))
        self.assertTrue(self.eval('2.5 < 3'))

    def test_gte(self):
        res = self.eval('5 >= 3')
        self.assertIsInstance(res, bool)
        self.assertTrue(res)
        self.assertTrue(self.eval('3 >= 3'))
        self.assertTrue(self.eval('3.5 > 3'))
        self.assertFalse(self.eval('2 >= 3'))

    def test_lte(self):
        res = self.eval('3 <= 5')
        self.assertIsInstance(res, bool)
        self.assertTrue(res)
        self.assertTrue(self.eval('3 <= 3'))
        self.assertFalse(self.eval('3 <= 2'))

    def test_eq(self):
        self.assertTrue(self.eval('5 = 5'))
        self.assertTrue(self.eval('1.0 = 1'))
        self.assertFalse(self.eval('5 = 6'))

    def test_neq(self):
        self.assertFalse(self.eval('5 != 5'))
        self.assertFalse(self.eval('0 != 0.0'))
        self.assertTrue(self.eval('5 != 6'))

    def test_zero_division(self):
        self.assertRaises(ZeroDivisionError, self.eval, '0/0')

    def test_random(self):
        self.assertTrue(self.eval('with(random()) -> $ >= 0 and $ < 1'))
        self.assertTrue(self.eval('with(random(2, 5)) -> $ >= 2 and $ <= 5'))

    def test_int(self):
        self.assertEqual(5, self.eval("int('5')"))
        self.assertEqual(5, self.eval('int(5.2)'))
        self.assertEqual(0, self.eval('int(null)'))

    def test_float(self):
        self.assertAlmostEqual(-1.23, self.eval("float('-1.23')"))
        self.assertEqual(0.0, self.eval('float(null)'))

    def test_bitwise_or(self):
        self.assertEqual(3, self.eval('bitwiseOr(1, 3)'))
        self.assertEqual(3, self.eval('bitwiseOr(1, 2)'))

    def test_bitwise_and(self):
        self.assertEqual(1, self.eval('bitwiseAnd(1, 3)'))
        self.assertEqual(0, self.eval('bitwiseAnd(1, 2)'))

    def test_bitwise_xor(self):
        self.assertEqual(2, self.eval('bitwiseXor(1, 3)'))
        self.assertEqual(3, self.eval('bitwiseXor(1, 2)'))

    def test_bitwise_not(self):
        self.assertEqual(-2, self.eval('bitwiseNot(1)'))

    def test_shift_bits_left(self):
        self.assertEqual(32, self.eval('shiftBitsLeft(1, 5)'))

    def test_shift_bits_right(self):
        self.assertEqual(2, self.eval('shiftBitsRight(32, 4)'))
        self.assertEqual(0, self.eval('shiftBitsRight(32, 6)'))

    def test_pow(self):
        self.assertEqual(32, self.eval('pow(2, 5)'))
        self.assertEqual(4, self.eval('pow(2, 5, 7)'))

    def test_sign(self):
        self.assertEqual(1, self.eval('sign(123)'))
        self.assertEqual(-1, self.eval('sign(-123)'))
        self.assertEqual(0, self.eval('sign(0)'))

    def test_round(self):
        self.assertAlmostEqual(2.0, self.eval('round(2.3)'))
        self.assertAlmostEqual(2.3, self.eval('round(2.345, 1)'))

    def test_is_integer(self):
        self.assertTrue(self.eval('isInteger(-2)'))
        self.assertTrue(self.eval('isInteger(2)'))
        self.assertFalse(self.eval('isInteger(2.3)'))
        self.assertFalse(self.eval('isInteger(abc)'))
        self.assertFalse(self.eval('isInteger(true)'))

    def test_is_number(self):
        self.assertTrue(self.eval('isNumber(-2)'))
        self.assertTrue(self.eval('isNumber(2)'))
        self.assertTrue(self.eval('isNumber(2.3)'))
        self.assertFalse(self.eval('isNumber(abc)'))
        self.assertFalse(self.eval('isNumber(true)'))


text:
There are three parts in the documentation below:
* ScharfSandhiTest.py
* ScharfSandhiTest2.py
* comparison to Bucknell Sandhi tables

## ScharfSandhiTest.py
This program permits testing of a batch of known examples.  Several
instances of it are in the shell script testsuite.sh.

The usage is as follows:

```
python ScharfSandhiTest.py <sandhioption> <input> <answer>
where
<sandhioption> is one of the simple sandhi options mentioned above (C, E, etc.)
<input> is a text file of examples, one per line, to which the particular
   sandhi option is to be applied
<answer> is a text file of answers, one per line.  Applying the particular
  sandhi option to a given line from <input> should give the result shown
  on the corresponding line of from <answer>
The two files, <input> and <answer>, must be supplied by the user.
Information regarding sucessful and unsuccessful test results is printed
to stdout.
```

## ScharfSandhiTest2.py
This provides an alternate method for batch testing of the sandhi methods.
The usage is as follows:

```
python ScharfSandhiTest2.py <testfile>
where <testfile> is a file of lines with a test and its result on each line.
The format of a line is that of three colon-delimited fields:
<sandhioption>:<test>:<answer>
where,
<sandhioption> is one of the simple sandhi options (C, E, etc.)
<test> is the example to which the sandhi option is to be applied
<answer> is the desired result of applying the sandhi option to the example.

Results are printed to stdout.

This program was used to compare scharfsandhi to Bucknell's table. For
instance,
$ python ScharfSandhiTest2.py bucknell/vowel_test2.txt > bucknell/log_vowel_tes
t2.txt

The test file, in this case vowel_test2.txt, was constructed by another
program, using Bucknell's tables.

```

## External sandhi comparisons to Bucknell
Aug/Sep, 2015

The `Sanskrit Manual` by Roderick Bucknell succinctly describes external
sandhi rules in a tabular form that facilitates comparison.  Programs were
developed to do this comparison.  With very few exceptions, the analysis
shows that scharfsandhi.py computes results identical to those of Bucknell.
See the [bucknell readme](https://github.com/funderburkjim/ScharfSandhi/tree/master/pythonv4/scharfsandhi_bucknell.md) for a description of the analysis.


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace AFrame.Core.Tests
{
    [TestClass]
    public class PlaybackTests
    {
        [TestMethod]
        public void Can_Add_To_Properties()
        {
            Playback.Properties["Testing"] = "Yay";

            Assert.AreEqual("Yay", Playback.Properties["Testing"]);
        }

        [TestMethod]
        public void DefaultSearchTimeout()
        {
            var expected = TimeSpan.FromSeconds(15);

            Assert.AreEqual(expected.TotalMilliseconds, Playback.SearchTimeout);
        }

        [TestMethod]
        public void AlwaysSearchIsDefaultedToFalse()
        {
            Assert.IsFalse(Playback.AlwaysSearch);
        }
    }
}


text:
#include "stdafx.h"

#include <d3d9.h>
#include <d3dx9.h>

#include "ConstantDescription.h"

using namespace System;

namespace SlimDX
{
namespace Direct3D9
{
	bool ConstantDescription::operator == ( ConstantDescription left, ConstantDescription right )
	{
		return ConstantDescription::Equals( left, right );
	}

	bool ConstantDescription::operator != ( ConstantDescription left, ConstantDescription right )
	{
		return !ConstantDescription::Equals( left, right );
	}

	int ConstantDescription::GetHashCode()
	{
		return Name->GetHashCode() + RegisterSet.GetHashCode() + RegisterIndex.GetHashCode()
			 + RegisterCount.GetHashCode() + Class.GetHashCode() + Type.GetHashCode()
			 + Rows.GetHashCode() + Columns.GetHashCode() + Elements.GetHashCode()
			 + StructMembers.GetHashCode() + Bytes.GetHashCode();
	}

	bool ConstantDescription::Equals( Object^ value )
	{
		if( value == nullptr )
			return false;

		if( value->GetType() != GetType() )
			return false;

		return Equals( safe_cast<ConstantDescription>( value ) );
	}

	bool ConstantDescription::Equals( ConstantDescription value )
	{
		return ( Name == value.Name && RegisterSet == value.RegisterSet && RegisterIndex == value.RegisterIndex
			 && RegisterCount == value.RegisterCount && Class == value.Class && Type == value.Type
			 && Rows == value.Rows && Columns == value.Columns && Elements == value.Elements
			 && StructMembers == value.StructMembers && Bytes == value.Bytes );
	}

	bool ConstantDescription::Equals( ConstantDescription% value1, ConstantDescription% value2 )
	{
		return ( value1.Name == value2.Name && value1.RegisterSet == value2.RegisterSet && value1.RegisterIndex == value2.RegisterIndex
			 && value1.RegisterCount == value2.RegisterCount && value1.Class == value2.Class && value1.Type == value2.Type
			 && value1.Rows == value2.Rows && value1.Columns == value2.Columns && value1.Elements == value2.Elements
			 && value1.StructMembers == value2.StructMembers && value1.Bytes == value2.Bytes );
	}

	void ConstantDescription::Initialize( const D3DXCONSTANT_DESC& description )
	{
		Name = gcnew String( description.Name );
		RegisterSet = static_cast<SlimDX::Direct3D9::RegisterSet>( description.RegisterSet );
		RegisterIndex = description.RegisterIndex;
		RegisterCount = description.RegisterCount;
		Class = static_cast<ParameterClass>( description.Class );
		Type = static_cast<ParameterType>( description.Type );
		Rows = description.Rows;
		Columns = description.Columns;
		Elements = description.Elements;
		StructMembers = description.StructMembers;
		Bytes = description.Bytes;
	}
}
}


text:
module.exports = (function(){
    'use strict';

    var config = require('../config');
    var utils = require('../utils');

    return {
        getAll: function(callback){
            var options = {};
            options.method = 'GET';
            options.uri = config.uri.GET_ALL_CHIP;

            utils.exec(options, callback);
        },
        getTemplates: function(callback){
            var options = {};
            options.method = 'GET';
            options.uri = config.uri.GET_TEMPLATES_CHIP;

            utils.exec(options, callback);
        }
    }
})();