text:
Okay , we will make the application from the server side web service that is of course by using high performance PHP framework Yii 2.0. Yii 2.0 has full support restful which is important thing in making a web service API . Yii teach us about how to make a web service quickly and correctly , everything was magical .

### Create Database Structure
Create database "angular_spa" and create "book" table with following structure.

![](images/dbstructure.png)

or import this sql [angular_spa.sql](../web-service/angular_spa.sql)

Insert some data in this table, You can create other table but this tutorial only will give example book table.

### Config Database Connection
Open [config/db.php](../web-service/config/db.php) in root of Yii application (web service). Modify db configuration and adjust the settings on your server database

```php
return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=angular_spa',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
];
```

### Create Models
Please generate class models from all the tables . You can use tools to menggeneratenya gii or make it manually. I will not explain to you how to make use gii on the assumption that you are already accustomed to using Yii.

This is [models/Book.php](../web-service/models/Book.php)
```php
namespace app\models;
use Yii;

class Book extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'book';
    }

    public function rules()
    {
        return [
            [['title', 'author', 'publisher', 'year'], 'required'],
            [['id', 'year'], 'integer'],
            [['title'], 'string', 'max' => 255],
            [['description'], 'string'],
            [['author','publisher'], 'string', 'max' => 50]
        ];
    }
}
```

### Config Yii as Restful Application
If You very new comer in rest Yii 2, please read from this guide https://github.com/yiisoft/yii2/blob/master/docs/guide/rest-quick-start.md. Its good start, to learn and explore restful in Yii

#### Create Rest Controller
Although not able to use gii to generate CRUD Restful , but Yii has an easy and fun way, here magical.

First, create [BookController.php](../web-service/controllers/BookController.php)  in the folder controllers.

```php
namespace app\controllers;

use yii\rest\ActiveController;

class BookController extends ActiveController
{
    # adjust the models
    public $modelClass = 'app\models\Book';

    public function behaviors()
    {
        return
        \yii\helpers\ArrayHelper::merge(parent::behaviors(), [
            'corsFilter' => [
                'class' => \yii\filters\Cors::className(),
            ],
        ]);
    }
}
```
The controller class extends from yii\rest\ActiveController. By specifying modelClass as app\models\Book, the controller knows what model can be used for fetching and manipulating data.

Add behavior for CORS to grant access to third party code (ajax calls from external domain) to be JSON (optional). read be carefully http://www.yiiframework.com/doc-2.0/yii-filters-cors.html

If You have other model to be made controllersnya restfulnya then you have to create new controllers.

#### Configuring URL Rules
modify the configuration about the urlManager component in your application configuration in [web.php](../web-service/config/web.php) in the config folder.

```php
'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        ['class' => 'yii\rest\UrlRule', 'controller' => 'book'],
    ],
]
```
The above configuration mainly adds a URL rule for the book controller so that the book data can be accessed and manipulated with pretty URLs and meaningful HTTP verbs. If You have more controllers, then You can add as array format
```php

    'rules' => [
        ['class' => 'yii\rest\UrlRule', 'controller' => ['book','user','employee','etc']],
    ],
```
If you are using Apache as a web server , then you need to add a [.htaccess](../web-service/web/.htaccess) file in the folder web-service/web, but if not (nginx) then you do not need to do it.

#### Enabling JSON Input
To let the API accept input data in JSON format, configure the parsers property of the request application component to use the yii\web\JsonParser for JSON input:
```php
'request' => [
    'parsers' => [
        'application/json' => 'yii\web\JsonParser',
    ]
]
```
Info: The above configuration is optional. Without the above configuration, the API would only recognize application/x-www-form-urlencoded and multipart/form-data input formats.

#### Testing in Your Browser Now!
With the above minimal amount of effort, you have already finished your task of creating the RESTful APIs for accessing the book data. The APIs you have created include:

```
GET /books: list all books page by page;
HEAD /books: show the overview information of book listing;
POST /books: create a new book;
GET /books/123: return the details of the book 123;
HEAD /books/123: show the overview information of book 123;
PATCH /books/123 and PUT /books/123: update the book 123;
DELETE /books/123: delete the book 123;
OPTIONS /books: show the supported verbs regarding endpoint /books;
OPTIONS /books/123: show the supported verbs regarding endpoint /books/123.
```

Info: Yii will automatically pluralize controller names for use in endpoints. You can configure this using the yii\rest\UrlRule::$pluralize-property.

Tip: You may also access your APIs via Web browser by entering the URL [http://localhost/web-service/web/books](http://localhost/web-service/web/books). However, you may need some browser plugins to send specific request headers. for example: I use Postman Chrome Extension

![](images/postman.png)

---

> *** Done ***

> [Back To Index](index.md)

> [01. Introduction](01-introduction.md)

> [02. Preparation](02-preparation.md)

> [03. Create Web Service](03-create-web-service.md)

> [04. Create Web Client](04-create-web-client.md)

> [05. Customization](05-customization.md)

> [06. Conclusion](06-conclusion.md)


text:
Find an element in an array where the element peaks.

**In the One-Dimensional version an element is a peak if this element is larger or equal to both the elements on its
sides.**

**In the Two-Dimensional version an element is a peak if this element is larger or equal to all the elements on its
sides (North, south, west and east sides).**

## Install

```
$ npm install --save peak-finding
```

## Usage

```js
var peakFinding = require('peak-finding');

peakFinding([1, 3, 4, 3, 5, 1, 3]);
//=> 4

peakFinding([[23, 20, 19, 10],
			 [14, 10, 12, 11],
			 [15,  9, 11, 21],
			 [16, 11, 10, 17]]);
//=> 23
```

## Time complexity
1D Version: Θ(log2(n)), where *n* is the length of the input list.

2D Version: Θ(n \* log2(m)) or Θ(n \* log2(n)) if n = m,
where *n* is the number of columns and m the number of rows.

## API

### peakFinding(list)

#### list

*Required*
Type: `Array`

## License

MIT © [Vinícius do Carmo](http://vinimdocarmo.js.org)

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

       <interceptors>
              <class>com.github.database.rider.cdi.DBUnitInterceptorImpl</class>
       </interceptors>
</beans>


text: xCodeRemoteConsole


text:
/*
 * Purpose: Code to implement a plugin cache which stores information
 *          about plugins which have already been loaded.
 *
 *          The plugin cache is implemented as a dynamic, global array which
 *          will grow as new plugins are added. The capacity of the cache
 *          never shrinks since plugins stay in memory once loaded.
 *
 *          Note that this functionality has absolutely nothing to do with
 *          the metadata or chunk caches.
 */

/****************/
/* Module Setup */
/****************/

#include "H5PLmodule.h" /* This source code file is part of the H5PL module */

/***********/
/* Headers */
/***********/
#include "H5private.h"   /* Generic Functions            */
#include "H5Eprivate.h"  /* Error handling               */
#include "H5MMprivate.h" /* Memory management            */
#include "H5PLpkg.h"     /* Plugin                       */
#include "H5Zprivate.h"  /* Filter pipeline              */

/****************/
/* Local Macros */
/****************/

/* Initial capacity of the plugin cache */
#define H5PL_INITIAL_CACHE_CAPACITY 16

/* The amount to add to the capacity when the cache is full */
#define H5PL_CACHE_CAPACITY_ADD 16

/******************/
/* Local Typedefs */
/******************/

/* Type for the list of info for opened plugin libraries */
typedef struct H5PL_plugin_t {
    H5PL_type_t type;   /* Plugin type                          */
    H5PL_key_t  key;    /* Unique key to identify the plugin    */
    H5PL_HANDLE handle; /* Plugin handle                        */
} H5PL_plugin_t;

/********************/
/* Local Prototypes */
/********************/

static herr_t H5PL__expand_cache(void);

/*********************/
/* Package Variables */
/*********************/

/*****************************/
/* Library Private Variables */
/*****************************/

/*******************/
/* Local Variables */
/*******************/

/* Cache for storing opened plugin libraries */
static H5PL_plugin_t *H5PL_cache_g = NULL;

/* The number of stored plugins */
static unsigned int H5PL_num_plugins_g = 0;

/* The capacity of the plugin cache */
static unsigned int H5PL_cache_capacity_g = 0;

/*-------------------------------------------------------------------------
 * Function:    H5PL__create_plugin_cache
 *
 * Purpose:     Create the cache that will store plugins that have already
 *              been loaded.
 *
 * Return:      SUCCEED/FAIL
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5PL__create_plugin_cache(void)
{
    herr_t ret_value = SUCCEED;

    FUNC_ENTER_PACKAGE

    /* Allocate memory for the plugin cache */
    H5PL_num_plugins_g = 0;

    H5PL_cache_capacity_g = H5PL_INITIAL_CACHE_CAPACITY;

    if (NULL ==
        (H5PL_cache_g = (H5PL_plugin_t *)H5MM_calloc((size_t)H5PL_cache_capacity_g * sizeof(H5PL_plugin_t))))
        HGOTO_ERROR(H5E_PLUGIN, H5E_CANTALLOC, FAIL, "can't allocate memory for plugin cache")

done:
    /* Try to clean up on errors */
    if (FAIL == ret_value) {
        if (H5PL_cache_g)
            H5PL_cache_g = (H5PL_plugin_t *)H5MM_xfree(H5PL_cache_g);
        H5PL_cache_capacity_g = 0;
    }

    FUNC_LEAVE_NOAPI(ret_value)
} /* end H5PL__create_plugin_cache() */

/*-------------------------------------------------------------------------
 * Function:    H5PL__close_plugin_cache
 *
 * Purpose:     Close the cache of plugins that have already been loaded,
 *              closing all the plugins contained inside.
 *
 * Return:      SUCCEED/FAIL
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5PL__close_plugin_cache(hbool_t *already_closed /*out*/)
{
    unsigned int u; /* iterator */
    herr_t       ret_value = SUCCEED;

    FUNC_ENTER_PACKAGE_NOERR

    /* Close opened dynamic libraries */
    if (H5PL_cache_g) {

        /* Close any cached plugins */
        for (u = 0; u < H5PL_num_plugins_g; u++)
            H5PL__close((H5PL_cache_g[u]).handle);

        /* Free the cache array */
        H5PL_cache_g          = (H5PL_plugin_t *)H5MM_xfree(H5PL_cache_g);
        H5PL_num_plugins_g    = 0;
        H5PL_cache_capacity_g = 0;

        /* Note that actually closed the table (needed by package close call) */
        *already_closed = FALSE;
    }
    else
        *already_closed = TRUE;

    FUNC_LEAVE_NOAPI(ret_value)
} /* end H5PL__close_plugin_cache() */

/*-------------------------------------------------------------------------
 * Function:    H5PL__expand_cache
 *
 * Purpose:     Expand the plugin cache when it's full.
 *
 * Return:      SUCCEED/FAIL
 *
 *-------------------------------------------------------------------------
 */
static herr_t
H5PL__expand_cache(void)
{
    herr_t ret_value = SUCCEED;

    FUNC_ENTER_STATIC

    /* Update the capacity */
    H5PL_cache_capacity_g += H5PL_CACHE_CAPACITY_ADD;

    /* Resize the array */
    if (NULL == (H5PL_cache_g = (H5PL_plugin_t *)H5MM_realloc(H5PL_cache_g, (size_t)H5PL_cache_capacity_g *
                                                                                sizeof(H5PL_plugin_t))))
        HGOTO_ERROR(H5E_PLUGIN, H5E_CANTALLOC, FAIL, "allocating additional memory for plugin cache failed")

    /* Initialize the new memory */
    HDmemset(H5PL_cache_g + H5PL_num_plugins_g, 0, (size_t)H5PL_CACHE_CAPACITY_ADD * sizeof(H5PL_plugin_t));

done:
    /* Set the cache capacity back if there were problems */
    if (FAIL == ret_value)
        H5PL_cache_capacity_g -= H5PL_CACHE_CAPACITY_ADD;

    FUNC_LEAVE_NOAPI(ret_value)
} /* end H5PL__expand_cache() */

/*-------------------------------------------------------------------------
 * Function:    H5PL__add_plugin
 *
 * Purpose:     Add a plugin to the plugin cache.
 *
 * Return:      SUCCEED/FAIL
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5PL__add_plugin(H5PL_type_t type, const H5PL_key_t *key, H5PL_HANDLE handle)
{
    herr_t ret_value = SUCCEED;

    FUNC_ENTER_PACKAGE

    /* Expand the cache if it is too small */
    if (H5PL_num_plugins_g >= H5PL_cache_capacity_g)
        if (H5PL__expand_cache() < 0)
            HGOTO_ERROR(H5E_PLUGIN, H5E_CANTALLOC, FAIL, "can't expand plugin cache")

    /* Store the plugin info and bump the # of plugins */
    H5PL_cache_g[H5PL_num_plugins_g].type   = type;
    H5PL_cache_g[H5PL_num_plugins_g].key    = *key;
    H5PL_cache_g[H5PL_num_plugins_g].handle = handle;

    H5PL_num_plugins_g++;

done:
    FUNC_LEAVE_NOAPI(ret_value)
} /* end H5PL__add_plugin() */

/*-------------------------------------------------------------------------
 * Function:    H5PL__find_plugin_in_cache
 *
 * Purpose:     Attempts to find a matching plugin from the cache.
 *
 *              The 'found' parameter will be set appropriately.
 *
 * Return:      SUCCEED/FAIL
 *
 *-------------------------------------------------------------------------
 */
/* See the other use of H5PL_GET_LIB_FUNC() for an explanation
 * for why we disable -Wpedantic here.
 */
H5_GCC_DIAG_OFF("pedantic")
herr_t
H5PL__find_plugin_in_cache(const H5PL_search_params_t *search_params, hbool_t *found,
                           const void **plugin_info)
{
    unsigned int u; /* iterator */
    herr_t       ret_value = SUCCEED;

    FUNC_ENTER_PACKAGE

    /* Check args - Just assert on package functions */
    HDassert(search_params);
    HDassert(found);
    HDassert(plugin_info);

    /* Initialize output parameters */
    *found       = FALSE;
    *plugin_info = NULL;

    /* Loop over all the plugins, looking for one that matches */
    for (u = 0; u < H5PL_num_plugins_g; u++) {

        /* If the plugin type (filter, VOL connector, etc.) and ID match, query the plugin for its info */
        if ((search_params->type == (H5PL_cache_g[u]).type) &&
            (search_params->key->id == (H5PL_cache_g[u]).key.id)) {

            H5PL_get_plugin_info_t get_plugin_info_function;
            const void *           info;

            /* Get the "get plugin info" function from the plugin. */
            if (NULL == (get_plugin_info_function = (H5PL_get_plugin_info_t)H5PL_GET_LIB_FUNC(
                             (H5PL_cache_g[u]).handle, "H5PLget_plugin_info")))
                HGOTO_ERROR(H5E_PLUGIN, H5E_CANTGET, FAIL, "can't get function for H5PLget_plugin_info")

            /* Call the "get plugin info" function */
            if (NULL == (info = (*get_plugin_info_function)()))
                HGOTO_ERROR(H5E_PLUGIN, H5E_CANTGET, FAIL, "can't get plugin info")

            /* Set output parameters */
            *found       = TRUE;
            *plugin_info = info;

            /* No need to continue processing */
            break;

        } /* end if */

    } /* end for */

done:
    FUNC_LEAVE_NOAPI(ret_value)
} /* end H5PL__find_plugin_in_cache() */
H5_GCC_DIAG_ON("pedantic")


text:
require "uri"
require "chef/resource/file"
require "chef/provider/remote_file"
require "chef/mixin/securable"
require "chef/mixin/uris"

class Chef
  class Resource
    class RemoteFile < Chef::Resource::File
      include Chef::Mixin::Securable

      description "Use the remote_file resource to transfer a file from a remote location"\
                  " using file specificity. This resource is similar to the file resource."

      def initialize(name, run_context = nil)
        super
        @source = []
      end

      # source can take any of the following as arguments
      # - A single string argument
      # - Multiple string arguments
      # - An array or strings
      # - A delayed evaluator that evaluates to a string
      #   or array of strings
      # All strings must be parsable as URIs.
      # source returns an array of strings.
      def source(*args)
        arg = parse_source_args(args)
        ret = set_or_return(:source,
                            arg,
                            { callbacks: {
                                validate_source: method(:validate_source),
                              } })
        if ret.is_a? String
          Array(ret)
        else
          ret
        end
      end

      def parse_source_args(args)
        if args.empty?
          nil
        elsif args[0].is_a?(Chef::DelayedEvaluator) && args.count == 1
          args[0]
        elsif args.any? { |a| a.is_a?(Chef::DelayedEvaluator) } && args.count > 1
          raise Exceptions::InvalidRemoteFileURI, "Only 1 source argument allowed when using a lazy evaluator"
        else
          Array(args).flatten
        end
      end

      property :checksum, String

      # Disable or enable ETag and Last Modified conditional GET. Equivalent to
      #   use_etag(true_or_false)
      #   use_last_modified(true_or_false)
      def use_conditional_get(true_or_false)
        use_etag(true_or_false)
        use_last_modified(true_or_false)
      end

      property :use_etag, [ TrueClass, FalseClass ], default: true

      alias :use_etags :use_etag

      property :use_last_modified, [ TrueClass, FalseClass ], default: true

      property :ftp_active_mode, [ TrueClass, FalseClass ], default: false

      property :headers, Hash, default: lazy { Hash.new }

      property :show_progress, [ TrueClass, FalseClass ], default: false

      property :remote_user, String

      property :remote_domain, String

      property :remote_password, String, sensitive: true

      property :authentication, equal_to: [:remote, :local], default: :remote

      def after_created
        validate_identity_platform(remote_user, remote_password, remote_domain)
        identity = qualify_user(remote_user, remote_password, remote_domain)
        remote_domain(identity[:domain])
        remote_user(identity[:user])
      end

      def validate_identity_platform(specified_user, password = nil, specified_domain = nil)
        if node[:platform_family] == "windows"
          if specified_user && password.nil?
            raise ArgumentError, "A value for `remote_password` must be specified when a value for `user` is specified on the Windows platform"
          end
        end
      end

      def qualify_user(specified_user, password = nil, specified_domain = nil)
        domain = specified_domain
        user = specified_user

        if specified_user.nil? && ! specified_domain.nil?
          raise ArgumentError, "The domain `#{specified_domain}` was specified, but no user name was given"
        end

        # if domain is provided in both username and domain
        if specified_user && ((specified_user.include? '\\') || (specified_user.include? "@")) && specified_domain
          raise ArgumentError, "The domain is provided twice. Username: `#{specified_user}`, Domain: `#{specified_domain}`. Please specify domain only once."
        end

        if ! specified_user.nil? && specified_domain.nil?
          # Splitting username of format: Domain\Username
          domain_and_user = user.split('\\')

          if domain_and_user.length == 2
            domain = domain_and_user[0]
            user = domain_and_user[1]
          elsif domain_and_user.length == 1
            # Splitting username of format: Username@Domain
            domain_and_user = user.split("@")
            if domain_and_user.length == 2
              domain = domain_and_user[1]
              user = domain_and_user[0]
            elsif domain_and_user.length != 1
              raise ArgumentError, "The specified user name `#{user}` is not a syntactically valid user name"
            end
          end
        end

        if ( password || domain ) && user.nil?
          raise ArgumentError, "A value for `password` or `domain` was specified without specification of a value for `user`"
        end

        { domain: domain, user: user }
      end

      private

      include Chef::Mixin::Uris

      def validate_source(source)
        source = Array(source).flatten
        raise ArgumentError, "#{resource_name} has an empty source" if source.empty?
        source.each do |src|
          unless absolute_uri?(src)
            raise Exceptions::InvalidRemoteFileURI,
              "#{src.inspect} is not a valid `source` parameter for #{resource_name}. `source` must be an absolute URI or an array of URIs."
          end
        end
        true
      end

      def absolute_uri?(source)
        Chef::Provider::RemoteFile::Fetcher.network_share?(source) || (source.kind_of?(String) && as_uri(source).absolute?)
      rescue URI::InvalidURIError
        false
      end

    end
  end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="generator" content="Source Themes Academic 4.6.1">

  <meta name="author" content="Cheng-Jun Wang">

  <meta name="description" content="I am inspired to use markdown to make HTML5 slides, However the specification is too hard. Actually, I don’t know how to make it less ugly, especilly for the first page of the slides.
By chance, I find Torres’s slides (Click here), it is made through R using the slidify package. Of course, you also need to write R markdown using Rstudio and Knitr.
Install slidify package in Rstudio install_github('slidify', 'ramnathv') install_github('slidifyLibraries', 'ramnathv')  {:lang=«ruby»}">

  <link rel="alternate" hreflang="en-us" href="https://chengjunwang.com/post/en/2013-08-18-using-slidify-to-publish-html5-presentations/">

  <meta name="theme-color" content="#2962ff">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css" integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha256-+N4/V/SbAFiW1MPBCXnfnP9QSN3+Keu+NlB+0ev/YKQ=" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">

          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/styles/github.min.css" crossorigin="anonymous" title="hl-light">
          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/styles/dracula.min.css" crossorigin="anonymous" title="hl-dark" disabled>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.css" integrity="sha256-SHMGCYmST46SoyGgo4YR/9AlK1vf3ff84Aq9yK4hdqM=" crossorigin="anonymous">

  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,700%7CRoboto:400,400italic,700%7CRoboto+Mono&display=swap">

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

  <link rel="manifest" href="/index.webmanifest">
  <link rel="icon" type="image/png" href="/img/icon-32.png">
  <link rel="apple-touch-icon" type="image/png" href="/img/icon-192.png">

  <link rel="canonical" href="https://chengjunwang.com/post/en/2013-08-18-using-slidify-to-publish-html5-presentations/">

  <meta property="twitter:card" content="summary_large_image">

  <meta property="twitter:site" content="@ChengJunWang">
  <meta property="twitter:creator" content="@ChengJunWang">

  <meta property="og:site_name" content="Cheng-Jun Wang">
  <meta property="og:url" content="https://chengjunwang.com/post/en/2013-08-18-using-slidify-to-publish-html5-presentations/">
  <meta property="og:title" content="Using slidify to publish HTML5 presentations | Cheng-Jun Wang">
  <meta property="og:description" content="I am inspired to use markdown to make HTML5 slides, However the specification is too hard. Actually, I don’t know how to make it less ugly, especilly for the first page of the slides.
By chance, I find Torres’s slides (Click here), it is made through R using the slidify package. Of course, you also need to write R markdown using Rstudio and Knitr.
Install slidify package in Rstudio install_github('slidify', 'ramnathv') install_github('slidifyLibraries', 'ramnathv')  {:lang=«ruby»}"><meta property="og:image" content="https://chengjunwang.com/img/headers/deer.webp">
  <meta property="twitter:image" content="https://chengjunwang.com/img/headers/deer.webp"><meta property="og:locale" content="en-us">

  <title>Using slidify to publish HTML5 presentations | Cheng-Jun Wang</title>

Search

        <input name="q" id="search-query" placeholder="Search..." autocapitalize="off"
        autocomplete="off" autocorrect="off" spellcheck="false" type="search">

      Cheng-Jun Wang

    <button type="button" class="navbar-toggler" data-toggle="collapse"
            data-target="#navbar-content" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Home

          Publications

          Teaching

          News

          Projects

          CV

          Contact

Using slidify to publish HTML5 presentations

    Jan 1, 0001

    4 min read

I am inspired to use markdown to make HTML5 slides, However the specification is too hard. Actually, I don’t know how to make it less ugly, especilly for the first page of the slides.

By chance, I find Torres’s slides (Click here), it is made through R using the slidify package. Of course, you also need to write R markdown using Rstudio and Knitr.

Install slidify package in Rstudio

install_github('slidify', 'ramnathv')
install_github('slidifyLibraries', 'ramnathv')

{:lang=«ruby»}

However, to install R packages host on Github is very painful. I failed in installing the slidifyLibrairies package.

Following thie post installing-slidify-on-a-windows-machine. Althought I have tried R CMD INSTALL, but failed. I don’t know why :<, however, I use the alternative method to install R packages on local computers.

First, download slidifyLibraries from github to your local directory, e.g., «D:/github/«.

Second, extract it and rename it as «slidifyLibraries».

Third, build it with this R script:

build("D:/github/slidifyLibraries/", binary=FALSE)

{:lang=«ruby»}

Fourth, install the tar.gz file following this R script:

install.packages("D:/github/slidifyLibraries_0.1.tar.gz", repos = NULL, type = "source")

{:lang=«ruby»}

Using slidify to write R markdown

initialize a presentation following this introduction about slidify.

library(slidify)
author('mydeck')

{:lang=«ruby»}

Write markdown files

<iframe width="420"
height="315" src="//www.youtube.com/embed/I95GOmLc7TA"
frameborder="0" allowfullscreen></iframe>

{:lang=«ruby»}

Check my first slidify HTML5 slides here: chengjun.github.io/slides/computational-communication.html

Click here to see it.

The markdown file is given below (I choose «standalone» as the mode):

---
title       : The Way to Computational Communication
subtitle    :
author      : Cheng-Jun Wang
job         : Web Mining Web, City University of Hong Kong
framework   : io2012        # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js  # {highlight.js, prettify, highlight}
hitheme     : tomorrow      #
widgets     : []            # {mathjax, quiz, bootstrap}
mode        : standalone # {standalone, draft, selfcontained}
---

## Three metaphors of theory
>Immanuel Kant: All our knowledge begins with the senses, proceeds then to the understanding, and ends with reason. There is nothing higher than reason.

![](http://farm8.staticflickr.com/7379/9532736494_99b95287a2_z.jpg)

--- .class #id

## Sandglass of generalization

![](http://farm8.staticflickr.com/7366/9529954881_53a00fe15b_z.jpg)

---
## Five levels of Research

![](http://farm3.staticflickr.com/2819/9529954801_e6d59c8eba_z.jpg)

---
## Computational Thinking

![](http://farm4.staticflickr.com/3669/9529954763_06a6c95970_z.jpg)

---
## The Way to Computational Communication

![](http://farm6.staticflickr.com/5540/9529954731_4cbf032b06_z.jpg)

---

## Network Science

![](http://farm8.staticflickr.com/7353/9529954585_94686e3aa4_z.jpg)

--- .class1 #id1 bg:yellow

## What should we do?

- Network science
- Statistical linguistics
- Human dynamics
- Big data& digital traces
- Digital media
- Data journalism
- Computational advertising

![](http://gifs.gifbin.com/1236681924_snail_transformers.gif)

---

## Thank you for your attention!

## wangchj04@gmail.com

![](http://farm3.staticflickr.com/2840/9508319890_2cbaa2c4d4_n.jpg)

{:lang=«ruby»}

How to host your slidify HTML5 presentations on github

I failed in publish it directly to github following the the way introduced by slidify website. I am not sure why it does not work. However, I figured out my solutions.

You can still do it very easily. But, first, you should know the structure of github repository. Assume you have a github repo named «slidify». We can work at different branches: «master» or «gh-pages». You can generate your gh-pages branch following the figure on the right. gh-pages is a very special branch of github repository. The branch of gh-pages are acturally a website host by Github.The files in slidify/test/index.html on the branch of gh-pages could be displayed by your default github website. e.g., chengjun.github.io/slidify/test. So the first move is to make a gh-pages, and upload your slidify stuff to this branch.

You can generate new sub-branch too. e.g., slidify/computational-communication. See two examples:

http://chengjun.github.io/slides/slidify/

If your markdown file is ‘selfcontained’{:lang=«ruby»} , it will not turn to https://code.google.com/p/slidifylibraries/ for the font and theme information (but it still needs to refer to the other websites where your insert your pictures into your slides). So theoretically, self-contained file is a little little little bit faster than ‘standalone’{:lang=«ruby»} files. However, you can almost not detect it if the internet access is good. Check this standalone HTML in the following link and compare it with the two selfcontained ones on the above:

[](http://chengjun.github.io/slides/)

In you sub-directory, you have to have everything the selfcontained html needs, it is not clever enough to scan the upper-directory. Anyway, enjoy your HTML5 slides host on github!

Afterwords

I have also tried to use pandoc and reveal.js to make slides.

Using reveal.js, I have reproduced the slides of computational communication on slid.es.

However, using pandoc and markdown, it seems to be quite limited to set the slides, here is the result:chengjun.github.io/slides/reveal.js/cc

The method is briefly introduced here: [](chengjun.github.io/slides/reveal.js/pandoc-revealjs-slides)

Cheng-Jun Wang

Associate Professor

Cheng-Jun Wang is currently an associate  professor in the School of Journalism and Communication, Nanjing University.

    All rights © reserved 2021 ·

    Powered by the
    Academic theme for
    Hugo.

Cite

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

           Copy

           Download


text:
package net.geforcemods.securitycraft.blocks.reinforced;

import net.geforcemods.securitycraft.api.OwnableBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;

public class ReinforcedCobwebBlock extends BaseReinforcedBlock {
	public ReinforcedCobwebBlock(Properties properties, Block vB) {
		super(properties, vB);
	}

	@Override
	public VoxelShape getCollisionShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) {
		return Shapes.empty();
	}

	@Override
	public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) {
		if (entity instanceof Player player) {
			if (level.getBlockEntity(pos) instanceof OwnableBlockEntity be) {
				if (be.getOwner().isOwner(player))
					return;
			}
		}

		entity.makeStuckInBlock(state, new Vec3(0.25D, 0.05D, 0.25D));
	}
}


text:
local GRU = {}

--[[
Creates one timestep of one GRU
Paper reference: http://arxiv.org/pdf/1412.3555v1.pdf
]]--
function GRU.gru(num_inputs, num_actions, num_hidden_layer_neurons, num_hidden_layers, num_outputs, dropout)

  -- there are n+1 inputs (hiddens on each layer and x)
  local inputs = {}
  table.insert(inputs, nn.Identity()()) -- x
  for L = 1,num_hidden_layers do
    table.insert(inputs, nn.Identity()()) -- prev_h[L]
  end

  function new_input_sum(insize, xv, hv)
    local i2h = nn.Linear(insize, num_hidden_layer_neurons)(xv)
    local h2h = nn.Linear(num_hidden_layer_neurons, num_hidden_layer_neurons)(hv)
    return nn.CAddTable()({i2h, h2h})
  end

  local x, input_size_L
  local outputs = {}
  for L = 1,num_hidden_layers do

    local prev_h = inputs[L+1]
    if L == 1 then
       -- convert class lable and action to 1-of-k representations
      local p = nn.Parallel(3, 2)
      p:add(OneHot(num_inputs))
      p:add(OneHot(num_actions))
      x = p(inputs[1])
      input_size_L = num_inputs + num_actions
    else
      x = outputs[L-1]
      if dropout > 0 then x = nn.Dropout(dropout)(x) end -- apply dropout, if any
      input_size_L = num_hidden_layer_neurons
    end

    -- GRU tick
    -- forward the update and reset gates
    local update_gate = nn.Sigmoid()(new_input_sum(input_size_L, x, prev_h))
    local reset_gate = nn.Sigmoid()(new_input_sum(input_size_L, x, prev_h))
    -- compute candidate hidden state
    local gated_hidden = nn.CMulTable()({reset_gate, prev_h})
    local p2 = nn.Linear(num_hidden_layer_neurons, num_hidden_layer_neurons)(gated_hidden)
    local p1 = nn.Linear(input_size_L, num_hidden_layer_neurons)(x)
    local hidden_candidate = nn.Tanh()(nn.CAddTable()({p1,p2}))
    -- compute new interpolated hidden state, based on the update gate
    local zh = nn.CMulTable()({update_gate, hidden_candidate})
    local zhm1 = nn.CMulTable()({nn.AddConstant(1,false)(nn.MulConstant(-1,false)(update_gate)), prev_h})
    local next_h = nn.CAddTable()({zh, zhm1})

    table.insert(outputs, next_h)
  end

    -- add softmax output layer (decoder)
  local top_h = outputs[#outputs]
  if dropout > 0 then top_h = nn.Dropout(dropout)(top_h) end
  local proj = nn.Linear(num_hidden_layer_neurons, num_outputs)(top_h)
  local logsoft = nn.LogSoftMax()(proj)
  table.insert(outputs, logsoft)

  return nn.gModule(inputs, outputs)
end

return GRU


text:
package org.familysearch.api.client.gens;

import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import org.familysearch.api.client.FamilySearchCollectionState;
import org.familysearch.api.client.FamilySearchReferenceEnvironment;
import org.gedcomx.Gedcomx;
import org.gedcomx.conclusion.Person;
import org.gedcomx.records.Collection;
import org.gedcomx.rs.client.PersonState;
import org.gedcomx.rs.client.StateTransitionOption;
import org.gedcomx.source.SourceDescription;

import javax.ws.rs.core.MultivaluedMap;
import java.net.URI;

public class GenealogiesTreeState extends FamilySearchCollectionState {

  public GenealogiesTreeState() {
    super();
  }

  public GenealogiesTreeState(FamilySearchReferenceEnvironment env) {
    super(env);
  }

  public GenealogiesTreeState(URI uri) {
    super(uri);
  }

  public GenealogiesTreeState(ClientRequest request, ClientResponse client, String accessToken, GenealogiesStateFactory stateFactory) {
    super(request, client, accessToken, stateFactory);
  }

  @Override
  protected GenealogiesTreeState clone(ClientRequest request, ClientResponse response) {
    return new GenealogiesTreeState(request, response, this.accessToken, (GenealogiesStateFactory) this.stateFactory);
  }

  @Override
  public GenealogiesTreeState ifSuccessful() {
    return (GenealogiesTreeState) super.ifSuccessful();
  }

  @Override
  public GenealogiesTreeState head(StateTransitionOption... options) {
    return (GenealogiesTreeState) super.head(options);
  }

  @Override
  public GenealogiesTreeState get(StateTransitionOption... options) {
    return (GenealogiesTreeState) super.get(options);
  }

  @Override
  public GenealogiesTreeState delete(StateTransitionOption... options) {
    return (GenealogiesTreeState) super.delete(options);
  }

  @Override
  public GenealogiesTreeState put(Gedcomx e, StateTransitionOption... options) {
    return (GenealogiesTreeState) super.put(e, options);
  }

  @Override
  public GenealogiesTreeState post(Gedcomx entity, StateTransitionOption... options) {
    return (GenealogiesTreeState) super.post(entity, options);
  }

  @Override
  public GenealogiesTreeState authenticateViaOAuth2Password(String username, String password, String clientId) {
    return (GenealogiesTreeState) super.authenticateViaOAuth2Password(username, password, clientId);
  }

  @Override
  public GenealogiesTreeState authenticateViaOAuth2Password(String username, String password, String clientId, String clientSecret) {
    return (GenealogiesTreeState) super.authenticateViaOAuth2Password(username, password, clientId, clientSecret);
  }

  @Override
  public GenealogiesTreeState authenticateViaOAuth2AuthCode(String authCode, String redirect, String clientId, String clientSecret) {
    return (GenealogiesTreeState) super.authenticateViaOAuth2AuthCode(authCode, redirect, clientId, clientSecret);
  }

  @Override
  public GenealogiesTreeState authenticateViaOAuth2AuthCode(String authCode, String redirect, String clientId) {
    return (GenealogiesTreeState) super.authenticateViaOAuth2AuthCode(authCode, redirect, clientId);
  }

  @Override
  public GenealogiesTreeState authenticateViaOAuth2ClientCredentials(String clientId, String clientSecret) {
    return (GenealogiesTreeState) super.authenticateViaOAuth2ClientCredentials(clientId, clientSecret);
  }

  @Override
  public GenealogiesTreeState authenticateViaOAuth2(MultivaluedMap<String, String> formData, StateTransitionOption... options) {
    return (GenealogiesTreeState) super.authenticateViaOAuth2(formData, options);
  }

  @Override
  public FamilySearchCollectionState addCollection(Collection collection, StateTransitionOption... options) {
    throw new UnsupportedOperationException("Can't add a collection to a tree");
  }

  @Override
  public FamilySearchCollectionState addCollection(Collection collection, SourceDescription sourceDescription, StateTransitionOption... options) {
    throw new UnsupportedOperationException("Can't add a collection to a tree");
  }

  @Override
  public GenealogiesPersonState addPerson(Person person, StateTransitionOption... options) {
    Gedcomx entity = new Gedcomx();
    entity.addPerson(person);
    return addPerson(entity, options);
  }

  @Override
  public GenealogiesPersonState addPerson(Gedcomx gx, StateTransitionOption... options) {
    return (GenealogiesPersonState) super.addPerson(gx, options);
  }

  @Override
  public GenealogiesPersonState readPerson(Person person, StateTransitionOption... options) {
    return (GenealogiesPersonState) super.readPerson(person, options);
  }

}


text:
package hello;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.FastThreadLocal;

public class HelloServerHandler extends SimpleChannelInboundHandler<Object> {

	private static final FastThreadLocal<DateFormat> FORMAT = new FastThreadLocal<DateFormat>() {
		@Override
		protected DateFormat initialValue() {
			return new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
		}
	};

	private static final ObjectMapper newMapper() {
		ObjectMapper m = new ObjectMapper();
		m.registerModule(new AfterburnerModule());
		return m;
	}

	private static final Message newMsg() {
		return new Message("Hello, World!");
	}

	private static final int jsonLen() {
		try {
			return newMapper().writeValueAsBytes(newMsg()).length;
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
	}

	private static final byte[] STATIC_PLAINTEXT = "Hello, World!".getBytes(CharsetUtil.UTF_8);
	private static final int STATIC_PLAINTEXT_LEN = STATIC_PLAINTEXT.length;
	private static final ByteBuf PLAINTEXT_CONTENT_BUFFER = Unpooled.unreleasableBuffer(Unpooled.directBuffer().writeBytes(STATIC_PLAINTEXT));
	private static final CharSequence PLAINTEXT_CLHEADER_VALUE = HttpHeaders.newEntity(String.valueOf(STATIC_PLAINTEXT_LEN));
	private static final CharSequence JSON_CLHEADER_VALUE = HttpHeaders.newEntity(String.valueOf(jsonLen()));

	private static final CharSequence TYPE_PLAIN = HttpHeaders.newEntity("text/plain; charset=UTF-8");
	private static final CharSequence TYPE_JSON = HttpHeaders.newEntity("application/json; charset=UTF-8");
	private static final CharSequence SERVER_NAME = HttpHeaders.newEntity("Netty");
	private static final CharSequence CONTENT_TYPE_ENTITY = HttpHeaders.newEntity(HttpHeaders.Names.CONTENT_TYPE);
	private static final CharSequence DATE_ENTITY = HttpHeaders.newEntity(HttpHeaders.Names.DATE);
	private static final CharSequence CONTENT_LENGTH_ENTITY = HttpHeaders.newEntity(HttpHeaders.Names.CONTENT_LENGTH);
	private static final CharSequence SERVER_ENTITY = HttpHeaders.newEntity(HttpHeaders.Names.SERVER);
	private static final ObjectMapper MAPPER = newMapper();

	private volatile CharSequence date = HttpHeaders.newEntity(FORMAT.get().format(new Date()));

	HelloServerHandler(ScheduledExecutorService service) {
		service.scheduleWithFixedDelay(new Runnable() {
			private final DateFormat format = FORMAT.get();

			@Override
			public void run() {
				date = HttpHeaders.newEntity(format.format(new Date()));
			}
		}, 1000, 1000, TimeUnit.MILLISECONDS);

	}

	@Override
	public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg instanceof HttpRequest) {
			HttpRequest request = (HttpRequest) msg;
			String uri = request.getUri();
			switch (uri) {
			case "/plaintext":
				writeResponse(ctx, request, PLAINTEXT_CONTENT_BUFFER.duplicate(), TYPE_PLAIN, PLAINTEXT_CLHEADER_VALUE);
				return;
			case "/json":
				byte[] json = MAPPER.writeValueAsBytes(newMsg());
				writeResponse(ctx, request, Unpooled.wrappedBuffer(json), TYPE_JSON, JSON_CLHEADER_VALUE);
				return;
			}
			FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, Unpooled.EMPTY_BUFFER, false);
			ctx.write(response).addListener(ChannelFutureListener.CLOSE);
		}
	}

	private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf, CharSequence contentType, CharSequence contentLength) {
		// Decide whether to close the connection or not.
		boolean keepAlive = HttpHeaders.isKeepAlive(request);
		// Build the response object.
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf, false);
		HttpHeaders headers = response.headers();
		headers.set(CONTENT_TYPE_ENTITY, contentType);
		headers.set(SERVER_ENTITY, SERVER_NAME);
		headers.set(DATE_ENTITY, date);
		headers.set(CONTENT_LENGTH_ENTITY, contentLength);

		// Close the non-keep-alive connection after the write operation is done.
		if (!keepAlive) {
			ctx.write(response).addListener(ChannelFutureListener.CLOSE);
		} else {
			ctx.write(response, ctx.voidPromise());
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}
}


text:
import codecs
import concurrent.futures
import glob
import os

from django.core.management.base import BaseCommand, CommandError
from django.core.management.utils import find_command, popen_wrapper

def has_bom(fn):
    with open(fn, 'rb') as f:
        sample = f.read(4)
    return sample.startswith((codecs.BOM_UTF8, codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE))

def is_writable(path):
    # Known side effect: updating file access/modified time to current time if
    # it is writable.
    try:
        with open(path, 'a'):
            os.utime(path, None)
    except (IOError, OSError):
        return False
    return True

class Command(BaseCommand):
    help = 'Compiles .po files to .mo files for use with builtin gettext support.'

    requires_system_checks = False

    program = 'msgfmt'
    program_options = ['--check-format']

    def add_arguments(self, parser):
        parser.add_argument(
            '--locale', '-l', action='append', default=[],
            help='Locale(s) to process (e.g. de_AT). Default is to process all. '
                 'Can be used multiple times.',
        )
        parser.add_argument(
            '--exclude', '-x', action='append', default=[],
            help='Locales to exclude. Default is none. Can be used multiple times.',
        )
        parser.add_argument(
            '--use-fuzzy', '-f', dest='fuzzy', action='store_true',
            help='Use fuzzy translations.',
        )

    def handle(self, **options):
        locale = options['locale']
        exclude = options['exclude']
        self.verbosity = options['verbosity']
        if options['fuzzy']:
            self.program_options = self.program_options + ['-f']

        if find_command(self.program) is None:
            raise CommandError("Can't find %s. Make sure you have GNU gettext "
                               "tools 0.15 or newer installed." % self.program)

        basedirs = [os.path.join('conf', 'locale'), 'locale']
        if os.environ.get('DJANGO_SETTINGS_MODULE'):
            from django.conf import settings
            basedirs.extend(settings.LOCALE_PATHS)

        # Walk entire tree, looking for locale directories
        for dirpath, dirnames, filenames in os.walk('.', topdown=True):
            for dirname in dirnames:
                if dirname == 'locale':
                    basedirs.append(os.path.join(dirpath, dirname))

        # Gather existing directories.
        basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs)))

        if not basedirs:
            raise CommandError("This script should be run from the Django Git "
                               "checkout or your project or app tree, or with "
                               "the settings module specified.")

        # Build locale list
        all_locales = []
        for basedir in basedirs:
            locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % basedir))
            all_locales.extend(map(os.path.basename, locale_dirs))

        # Account for excluded locales
        locales = locale or all_locales
        locales = set(locales).difference(exclude)

        self.has_errors = False
        for basedir in basedirs:
            if locales:
                dirs = [os.path.join(basedir, l, 'LC_MESSAGES') for l in locales]
            else:
                dirs = [basedir]
            locations = []
            for ldir in dirs:
                for dirpath, dirnames, filenames in os.walk(ldir):
                    locations.extend((dirpath, f) for f in filenames if f.endswith('.po'))
            if locations:
                self.compile_messages(locations)

        if self.has_errors:
            raise CommandError('compilemessages generated one or more errors.')

    def compile_messages(self, locations):
        """
        Locations is a list of tuples: [(directory, file), ...]
        """
        with concurrent.futures.ThreadPoolExecutor() as executor:
            futures = []
            for i, (dirpath, f) in enumerate(locations):
                if self.verbosity > 0:
                    self.stdout.write('processing file %s in %s\n' % (f, dirpath))
                po_path = os.path.join(dirpath, f)
                if has_bom(po_path):
                    self.stderr.write(
                        'The %s file has a BOM (Byte Order Mark). Django only '
                        'supports .po files encoded in UTF-8 and without any BOM.' % po_path
                    )
                    self.has_errors = True
                    continue
                base_path = os.path.splitext(po_path)[0]

                # Check writability on first location
                if i == 0 and not is_writable(base_path + '.mo'):
                    self.stderr.write(
                        'The po files under %s are in a seemingly not writable location. '
                        'mo files will not be updated/created.' % dirpath
                    )
                    self.has_errors = True
                    return

                args = [self.program] + self.program_options + [
                    '-o', base_path + '.mo', base_path + '.po'
                ]
                futures.append(executor.submit(popen_wrapper, args))

            for future in concurrent.futures.as_completed(futures):
                output, errors, status = future.result()
                if status:
                    if self.verbosity > 0:
                        if errors:
                            self.stderr.write("Execution of %s failed: %s" % (self.program, errors))
                        else:
                            self.stderr.write("Execution of %s failed" % self.program)
                    self.has_errors = True


text:
{% extends "layout.html" %}

{% block page_title %}
Tel input
{% endblock %}

{% block content %}

{{ macro.breadcrumb() }}

Tel input

What is it?

A simple telephone input.

screenshot

Accessibility success criteria

The text input test cases cover basic form interaction criteria.

It must be possible to identify the field type using a screen reader

It must be possible to enter a telephone number, or select a previously entered telephone number, using the keyboard

Test Cases

01 - telephone input

{% endblock %}


text:
if ((window.unsafeWindow == null ? window : unsafeWindow).MathJax == null) {
  //
  //  Replace the images with MathJax scripts of type math/tex
  //
  var images = document.getElementsByTagName('img'), count = 0;
  for (var i = images.length - 1; i >= 0; i--) {
    var img = images[i];
    if (img.className === "tex") {
      var script = document.createElement("script"); script.type = "math/tex";
      if (window.opera) {script.innerHTML = img.alt} else {script.text = img.alt}
      img.parentNode.replaceChild(script,img); count++;
    }
  }
  if (count) {
    //
    //  Load MathJax and have it process the page
    //
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML-full";
    document.getElementsByTagName("head")[0].appendChild(script);
  }
}


text:
require "helper"

require "gapic/grpc/service_stub"

require "google/cloud/billing/budgets/v1beta1/budget_service"

class ::Google::Cloud::Billing::Budgets::V1beta1::BudgetService::ClientPathsTest < Minitest::Test
  def test_billing_account_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Cloud::Billing::Budgets::V1beta1::BudgetService::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.billing_account_path billing_account: "value0"
      assert_equal "billingAccounts/value0", path
    end
  end

  def test_budget_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Cloud::Billing::Budgets::V1beta1::BudgetService::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.budget_path billing_account: "value0", budget: "value1"
      assert_equal "billingAccounts/value0/budgets/value1", path
    end
  end
end


text:
namespace jingle_xmpp {
class XmppTaskParentInterface;
}  // namespace jingle_xmpp

namespace notifier {

struct ServerInformation;

// Handles all of the aspects of a single login attempt.  By
// containing this within one class, when another login attempt is
// made, this class can be destroyed to immediately stop the previous
// login attempt.
class SingleLoginAttempt : public XmppConnection::Delegate {
 public:
  // At most one delegate method will be called, depending on the
  // result of the login attempt.  After the delegate method is
  // called, this class won't do anything anymore until it is
  // destroyed, at which point it will disconnect if necessary.
  class Delegate {
   public:
    // Called when the login attempt is successful.
    virtual void OnConnect(
        base::WeakPtr<jingle_xmpp::XmppTaskParentInterface> base_task) = 0;

    // Called when the server responds with a redirect.  A new login
    // attempt should be made to the given redirect server.
    virtual void OnRedirect(const ServerInformation& redirect_server) = 0;

    // Called when a server rejects the client's login credentials.  A
    // new login attempt should be made once the client provides new
    // credentials.
    virtual void OnCredentialsRejected() = 0;

    // Called when no server could be logged into for reasons other
    // than redirection or rejected credentials.  A new login attempt
    // may be created, but it should be done with exponential backoff.
    virtual void OnSettingsExhausted() = 0;

   protected:
    virtual ~Delegate();
  };

  // Does not take ownership of |delegate|, which must not be NULL.
  SingleLoginAttempt(const LoginSettings& login_settings, Delegate* delegate);

  ~SingleLoginAttempt() override;

  // XmppConnection::Delegate implementation.
  void OnConnect(base::WeakPtr<jingle_xmpp::XmppTaskParentInterface> parent) override;
  void OnError(jingle_xmpp::XmppEngine::Error error,
               int error_subcode,
               const jingle_xmpp::XmlElement* stream_error) override;

 private:
  void TryConnect(const ConnectionSettings& new_settings);

  const LoginSettings login_settings_;
  Delegate* const delegate_;
  const ConnectionSettingsList settings_list_;
  ConnectionSettingsList::const_iterator current_settings_;
  std::unique_ptr<XmppConnection> xmpp_connection_;

  DISALLOW_COPY_AND_ASSIGN(SingleLoginAttempt);
};

}  // namespace notifier

#endif  // JINGLE_NOTIFIER_COMMUNICATOR_SINGLE_LOGIN_ATTEMPT_H_


text:
# JavaScript Style Guide [![Build Status](https://travis-ci.org/romamatusevich/JavaScript-Style-Guide.svg?branch=master)](https://travis-ci.org/romamatusevich/JavaScript-Style-Guide)

## Table of Contents
1. [Whitespaces](#whitespaces)
1. [Line Length](#line-length)
1. [Variables](#variables)
1. [Properties](#properties)
1. [Type Conversion](#type-conversion)
1. [Naming](#naming)
1. [Semicolons](#semicolons)
1. [Blocks](#blocks)
1. [Equality](#equality)
1. [Quotes](#quotes)
1. [Comments](#comments)
1. [Function Constructor](#function-constructor)
1. [Strict Mode](#strict-mode)
1. [Linters Config](#linters-config)
1. [Great Style Guides](#great-style-guides)
1. [Compatibility Tables](#compatibility-tables)
1. [License](#license)

## Whitespaces
- Use 4 spaces for indents. Usage of tabs for indents should be avoided.

```javascript

    // good

    var config = {
        path: '/users',
        debug: true
    };

    function fact() {
        var i = 0;
    }

    if (true) {
        var inc = 2;
        var i;

        for (i = 0; i < inc; i++) {
            // statements
        }
    }

```

```javascript

    // bad

    var config = {
      path: '/users',
        debug: true
    };

    function fact() {
            var i = 0;
    }

    if (true) {
        var inc = 2;
          var i;

            for (i = 0; i < inc; i++) {
            // statements
        }
    }

```

- Wrap operators (assignment, comparison, bitwise, logical, string, special) with single spaces.

```javascript

    // good

    var i = 1 + 2;

    1 !== 0;

    1 & 0;

    1 || 0;

    'Hello, ' + 'world!';

    true ? 1 : 0;

```

```javascript

    // bad

    var i =  1 + 2;

    1  !==0;

    1 &  0;

    1 ||     0;

    'Hello, '+'world!';

    true ? 1 :0;

```

- Use single space after functions, loops, operators keywords and after parentheses.

```javascript

    // good

    var fn = function () {
        // statements
    };

    function fact() {
        // statements
    }

    if (1 === 0) {
        // statements
    }

    while (1 === 0) {
        // statements
    }

    for (var i = 0; i < 3; i++) {
        // statements
    }
```

```javascript

    // bad

    var fn = function(){
        // statements
    };

    function fact(){
        // statements
    }

    if(1 === 0){
        // statements
    }

    while(1===0){
        // statements
    }

    for (var i = 0; i < 3; i++){
        // statements
    }
```

- Use single space before parameters and arguments except first.

```javascript

    // good

    function fact(i, j, k) {
        // statements
    }

    fact(1, 2, 3);
```

```javascript

    // bad

    function fact(i,j,k) {
        // statements
    }

    fact(1,2,3);
```

## Line Length
- Limit line length to 80 characters.

## Variables
- Declare one variable per `var` statement. Declaration variables without `var` should be prohibited.

```javascript

    // good

    var keys = ['vehicle', 'model', 'year'];
    var obj = {};
    var i;
```

```javascript

    // bad

    var keys = ['vehicle', 'model', 'year'],
        obj = {},
        i;
```

- Declare variables at the top of the scope.

```javascript

    // good

    function fact() {
        var flag = true;
        var keys = ['vehicle', 'model', 'year'];

        if (flag) {
            // statements
        }
    }
```

```javascript

    // bad

    function fact() {
        if (flag) {
            // statements
        }

        var flag = true;
        var keys = ['vehicle', 'model', 'year'];
    }
```

## Properties
- Use the dot notation for accessing properties.

```javascript

    // good

    var obj = {
        i: 1,
        j: 2
    };

    obj.i; // 1
    obj.j; // 2
```

```javascript

    // bad

    var obj = {
        i: 1,
        j: 2
    };

    obj['i']; // 1
    obj['j']; // 2
```

- Use the bracket notation for accessing variable properties.

```javascript

    // good

    var obj = {
        i: 1,
        j: 2
    };
    var prop = 'i';

    obj[prop]; // 1
```

```javascript

    // bad

    var obj = {
        i: 1,
        j: 2
    };
    var prop = 'i';

    obj.prop;
```

## Type Conversion
- To strings: use String() instead of addition operator (+)

```javascript

    // good

    var i = 10;

    var iStr = String(i); // '10'
```

```javascript

    // bad

    var i = 10;

    var iStr = '' + i; // '10'
```

- To numbers: use Number() instead of unary plus operator (+)

```javascript

    // good

    var i = '10';

    var iNumber = Number(i); // 10
```

```javascript

    // bad

    var i = '10';

    var iNumber = +i; // 10
```

- To booleans: use Boolean() instead of double logical not operator

```javascript

    // good

    var i = '10';

    var iBoolean = Boolean(i); // true
```

```javascript

    // bad

    var i = '10';

    var iBoolean = !!i; // true
```

## Naming
- Use camel case with lowercase first letter for variables, properties, arguments and parameters.

```javascript

    // good

    var isEmptyItem = true;

    var carObj = {
        hasFogLights: false
    };

    function fact(stepVal, incVal) {
        // statements
    }
```

```javascript

    // bad

    var Isemptyitem = true;

    var carobj = {
        hasFogLights: false
    };

    function fact(stepval, incval) {
        // statements
    }
```

- Use all uppercase letters for constants.

```javascript

    // good

    var PI = 3.14;
    var E = 2.71;
```

```javascript

    // bad

    var pi = 3.14;
    var e = 2.71;
```

- Use `me` as reference to `this`.

```javascript

    // good

    function rt() {
        var me = this;

        return function () {
            return me;
        };
    }
```

```javascript

    // bad

    function rt() {
        var that = this;

        return function () {
            return me;
        };
    }
```

## Semicolons
- Use semicolons.

```javascript

    // good

    var car = function () {
        // statements
    };

    var flag = false;

    car();
```

```javascript

    // bad

    var car = function () {
        // statements
    }

    var flag = false

    car()
```

## Blocks
- Use multi-line blocks.

```javascript

    // good

    if (1 === 0) {
        // statements
    }

    while (11 < 10) {
        y++;
    }
```

```javascript

    // bad

    if (1 === 0) // statements

    while (11 < 10) y++;
```

- Opening braces `{` should be on the same line as statements.

```javascript

    // good

    if (1 === 0) {
        // statements
    }

    function fact() {
        // statements
    }
```

```javascript

    // bad

    if (1 === 0)
    {
        // statements
    }

    function fact()
    {
        // statements
    }
```

- Closing braces `}` should be on a new line and be indented as statements.

```javascript

    // good

    function fact() {
        var i;

        if (1 === 0) {
            // statement

            for (i = 0; i < 3; i++) {
                // statements
            }
        }
    }
```

```javascript

    // bad

    function fact() {
    var i;

    if (1 === 0) {
        // statement

        for (i = 0; i < 3; i++) {
            // statements
        }
    }}
```

## Equality
- Use strict equality operators `===`, `!==`. Usage of equality operators `==`, `!=` should be avoided.

```javascript

    // good

    11 === 11; // true
    11 === '11'; // false
    true === true; // true
    1 === true; // false
```

```javascript

    // bad

    11 == 11; // true
    11 == '11'; // true
    true == true; // true
    1 == true; // true
```

## Quotes
- Use one type of quotes over a project: `'` or `"`. Single quotes best option.

```javascript

    // good

    var filmTitle = 'Star Wars';
```

```javascript

    // bad

    var filmTitle = "Star Wars";
```

## Comments
- Use `//` for single-line comments.

```javascript

    // good

    // Title of the film
    var title = 'Star Wars';
```

```javascript

    // bad

    /* Title of the film */
    var title = 'Star Wars';
```

- Use `/** ... */` for multi-line comments.

```javascript

    // good

    /**
     * Return film title
     * @param {Number} id - id of the film
     * @return {String} - title of the film
     */
    function getTitle(id) {
        // statements

        return filmsData[id];
    }
```

```javascript

    // bad

    // Return film title
    // @param {Number} id - id of the film
    // @return {String} - title of the film
    function getTitle(id) {
        // statements

        return filmsData[id];
    }
```

- Use `// TODO:` for tasks and solutions in your code.

```javascript

    // good

    function Car(make) {
        // TODO: pass year to constructor instead of hard coding
        var year = 2015;
    }
```

```javascript

    // bad

    function Car(make) {
        // to do: pass year to constructor instead of hard coding
        var year = 2015;
    }
```

## Function Constructor
- Function constructor names should be capitalized.

```javascript

    // good

    function Car() {
        // statements
    }

    var c = new Car();
```

```javascript

    // bad

    function car() {
        // statements
    }

    var c = new car();
```

- Prototype methods can return `this` in case chaining implementation.

```javascript

    function Car() {
        // statements
    }

    Car.prototype.setYear = function (year) {
        this.year = year;
        return this;
    };

    Car.prototype.showYear = function () {
        // log year
        return this;
    };

    var c = new Car();

    c.setYear(2010).showYear();
```

## Strict Mode
- Use strict mode which provide better error checking for code.

```javascript

    'use strict';
```

## Linters Config
[ESLint config](linters/.eslintrc.json)

## Great Style Guides
* [Airbnb](https://github.com/airbnb/javascript)
* [Airbnb ES5-only](https://github.com/airbnb/javascript/tree/master/es5)
* [idiomatic.js](https://github.com/rwaldron/idiomatic.js)
* [Google](https://google.github.io/styleguide/javascriptguide.xml)
* [jQuery](http://contribute.jquery.org/style-guide/js/)
* [Douglas Crockford](http://javascript.crockford.com/code.html)
* [Felix Node.js](http://nodeguide.com/style.html)

## Compatibility Tables
* [ECMAScript 5](http://kangax.github.io/compat-table/es5/)
* [ECMAScript 2015 (ES6)](http://kangax.github.io/compat-table/es6/)
* [ECMAScript 2016 (ES7)](http://kangax.github.io/compat-table/es7/)

## License

The MIT License (MIT)

Copyright (c) 2014-2017 Roman Matusevich

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


text:
package com.alaraph.sudoku

object SudokuApp {

  def main(args: Array[String]): Unit = {
    val board = readBoard(args)
    if (board != Vector.empty)
      solve(board)
    else
      instructions
  }

  private def readBoard(args: Array[String]): Vector[Vector[Char]] = {
    args.headOption match {
      case Some(str) =>
        val opt = str.takeWhile(_ != '=')
        val arg = str.substring(str.indexOf('=')+1)
        val actions = Map("-s" -> fromString _,
          "-f" -> fromFile _,
          "-c" -> fromConsole _) withDefaultValue ((_: String) => (Vector.empty))
        actions(opt)(arg)

      case None =>
        Vector.empty
    }
  }

  private def fromString(s: String) = {
    lazy val board = (for {
      (size, alpha) <- Sudoku.alphabet
      ncells = size*size
      filteredInput = s.filter(c => (alpha + '-').contains(c))
      if filteredInput.size == ncells
    } yield (size, filteredInput)).toSeq

    board.headOption match {
      case Some((size, input)) =>
        input.grouped(size).map(x => x.toVector).toVector
      case None =>
        val msg = for ((s, a) <- Sudoku.alphabet)
          yield "(*) %d symbols taken from %s".format(s * s, a.toSeq.sorted.mkString("(", ",", ")"))
        println(msg.mkString("\n"))
        Vector.empty
    }
  }

  private def fromFile(filename: String) = {
    /* This statement is taken from:
     * http://alvinalexander.com/scala/scala-how-open-read-files-scala-examples
     */
    import scala.io.Source
    val fileContents = Source.fromFile(filename).getLines.mkString
    fromString(fileContents)
  }

  private def fromConsole(size: String) = {
    try {
      val s = size.toInt
      if (!Sudoku.alphabet.keySet.contains(s)) {
        Vector.empty
      } else {
        val board = for (n <- 1 to s)
          yield Console.readLine
        fromString(board.mkString)
      }
    } catch {
      case e1: java.lang.NumberFormatException =>
        println("%s is not a valid size. Size can be %s".
          format(size, Sudoku.alphabet.keys.mkString("(", ",", ")")))
        Vector.empty
    }
  }

  private def instructions = {
    println("*********************************************************");
    println("                       SudokuApp                         ");
    println("*********************************************************");
    println(" Usage:                                                  ");
    println(" 1) SudokuApp -s=<string with Sudoku to be solved>       ");
    println(" 2) SudokuApp -f=<file with Sudoku to be solved>         ");
    println(" 2) SudokuApp -c=<size of Sudoku> //typed in the console ");
    println(" Remarks:                                                ");
    println(" *) In both uses, empty cells must be set to '-'         ");
    println(" *) The size of the alphabet can be 9(default), 4 or 16  ");
    println(" Examples:                                               ");
    println(" *) SudokuApp -f=./games/mySudo9.txt                     ");
    println(" *) SudokuApp -c=9                                       ");
    println(" *) SudokuApp -s=-1-4#----#----#9---#                    ");
    println("*********************************************************");
  }

  private def solve(board: Vector[Vector[Char]]) = {
    val sudo = Sudoku.build(board, board.size)
    println("Loaded Sudoku:\n%s".format(sudo))
    SudokuSolver solve sudo match {
      case Some(s) => println(println("Solved Sudoku:\n%s".format(s)))
      case None => println("No solution could be found")
    }
  }
}


text:
@interface JHPageController ()<JHPageMenuViewDelegate, JHPageMenuViewDataSource, UIPageViewControllerDelegate, UIPageViewControllerDataSource>
@property (nonatomic, strong) UIPageViewController *pageViewController;
@property (nonatomic, strong) JHPageMenuView *menuView;
@property (nonatomic, assign) JHPageMenuLocationStyle menuLocationStyle;
@property (nonatomic, weak) UIViewController *navBarController;
@property (nonatomic, assign) NSInteger dataCount;
@property (nonatomic, assign) BOOL isDragPageContrller;// 是否是拖拽pageController完成的页面切换
@end

@implementation JHPageController

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - init

- (instancetype)initWithMenuLocationStyle:(JHPageMenuLocationStyle)menulocationStyle navBarController:(UIViewController *)navBarController {
    if (self == [super init]) {
        _menuLocationStyle = menulocationStyle;
        _navBarController = navBarController;
        [self initialization];
    }
    return self;
}

- (void)initialization {
    [self initializationMenuView];
    [self initializationPageViewController];
}

- (void)initializationMenuView {
    if (self.menuLocationStyle == JHPageMenuLocationStyleNavBar) {
        self.navBarController.navigationItem.titleView = self.menuView;
    } else {
        [self.view addSubview:self.menuView];
        [self.menuView mas_makeConstraints:^(MASConstraintMaker *make) {
            switch (self.menuLocationStyle) {
                case JHPageMenuLocationStyleTop: {
                    make.top.leading.trailing.equalTo(self.view);
                    make.height.mas_equalTo(self.menuView.menuSize.height);
                }
                    break;
                case JHPageMenuLocationStyleBottom: {
                    make.bottom.leading.trailing.equalTo(self.view);
                    make.height.mas_equalTo(self.menuView.menuSize.height);
                }
                    break;
                case JHPageMenuLocationStyleLeft: {
                    make.top.leading.bottom.equalTo(self.view);
                    make.width.mas_equalTo(self.menuView.menuSize.width);
                }
                    break;
                case JHPageMenuLocationStyleRight: {
                    make.top.bottom.trailing.equalTo(self.view);
                    make.width.mas_equalTo(self.menuView.menuSize.width);
                }
                    break;
                case JHPageMenuLocationStyleNavBar:
                    break;
            }
        }];
    }
}

- (void)initializationPageViewController {
    [self.view addSubview:self.pageViewController.view];
    [self.pageViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        switch (self.menuLocationStyle) {
            case JHPageMenuLocationStyleTop: {
                make.leading.trailing.bottom.equalTo(self.view);
                make.top.equalTo(self.menuView.mas_bottom);
            }
                break;
            case JHPageMenuLocationStyleBottom: {
                make.leading.trailing.top.equalTo(self.view);
                make.bottom.equalTo(self.menuView.mas_top);
            }
                break;
            case JHPageMenuLocationStyleLeft: {
                make.top.trailing.bottom.equalTo(self.view);
                make.leading.equalTo(self.menuView.mas_trailing);
            }
                break;
            case JHPageMenuLocationStyleRight: {
                make.leading.top.bottom.equalTo(self.view);
                make.trailing.equalTo(self.menuView.mas_leading);
            }
                break;
            case JHPageMenuLocationStyleNavBar: {
                make.top.leading.trailing.bottom.equalTo(self.view);
            }
                break;
        }
    }];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    // 菜单视图布局
    if (self.menuLocationStyle != JHPageMenuLocationStyleNavBar) {
        [self.menuView mas_updateConstraints:^(MASConstraintMaker *make) {
            switch (self.menuLocationStyle) {
                case JHPageMenuLocationStyleTop: {
                    make.height.mas_equalTo(self.menuView.menuSize.height);
                }
                    break;
                case JHPageMenuLocationStyleBottom: {
                    make.height.mas_equalTo(self.menuView.menuSize.height);
                }
                    break;
                case JHPageMenuLocationStyleLeft: {
                    make.width.mas_equalTo(self.menuView.menuSize.width);
                }
                    break;
                case JHPageMenuLocationStyleRight: {
                    make.width.mas_equalTo(self.menuView.menuSize.width);
                }
                    break;
                case JHPageMenuLocationStyleNavBar:
                    break;
            }
        }];
    }
}

#pragma mark - setter

- (void)setSelectIndex:(NSInteger)selectIndex {
    UIPageViewControllerNavigationDirection direction = selectIndex > self.selectIndex ? UIPageViewControllerNavigationDirectionForward : UIPageViewControllerNavigationDirectionReverse;
    _selectIndex = selectIndex;
    if (self.dataCount == 0) { return; }
    NSAssert(self.selectIndex <= (self.dataCount - 1), @"选中的下标超出了范围");
    [self.menuView selectItemAtIndex:selectIndex withAnimation:YES];
    UIViewController *vc = [self.dataSource pageController:self viewContrlllerAtIndex:selectIndex];
    [self.pageViewController setViewControllers:@[vc] direction:direction animated:YES completion:nil];
}

- (void)setMenuBackgroundColor:(UIColor *)menuBackgroundColor {
    _menuBackgroundColor = menuBackgroundColor;
    self.menuView.backgroundColor = menuBackgroundColor;
}

- (void)setMenuItemSize:(CGSize)menuItemSize {
    _menuItemSize = menuItemSize;
    self.menuView.menuSize = menuItemSize;
    if (self.dataCount == 0) { return; }
    [self.menuView mas_updateConstraints:^(MASConstraintMaker *make) {
        switch (self.menuLocationStyle) {
            case JHPageMenuLocationStyleTop: {
                make.height.mas_equalTo(self.menuView.menuSize.height);
            }
                break;
            case JHPageMenuLocationStyleBottom: {
                make.height.mas_equalTo(self.menuView.menuSize.height);
            }
                break;
            case JHPageMenuLocationStyleLeft: {
                make.width.mas_equalTo(self.menuView.menuSize.width);
            }
                break;
            case JHPageMenuLocationStyleRight: {
                make.width.mas_equalTo(self.menuView.menuSize.width);
            }
                break;
            case JHPageMenuLocationStyleNavBar: {

            }
                break;
        }
    }];
}

- (void)setDecorateSize:(CGSize)decorateSize {
    _decorateSize = decorateSize;
    self.menuView.decorateSize = decorateSize;
}

- (void)setDecorateStyle:(JHPageDecorateStyle)decorateStyle {
    _decorateStyle = decorateStyle;
    self.menuView.decorateStyle = decorateStyle;
}

- (void)setDecorateColor:(UIColor *)decorateColor {
    _decorateColor = decorateColor;
    self.menuView.decorateColor = decorateColor;
}

- (void)setMenuSize:(CGSize)menuSize {
    _menuSize = menuSize;
    self.menuView.frame = CGRectMake(0, 0, menuSize.width, menuSize.height);
}

- (void)setMenuBorderWidth:(CGFloat)menuBorderWidth {
    _menuBorderWidth = menuBorderWidth;
    self.menuView.layer.borderWidth = menuBorderWidth;
}

- (void)setMenuBorderColor:(UIColor *)menuBorderColor {
    _menuBorderColor = menuBorderColor;
    self.menuView.layer.borderColor = menuBorderColor.CGColor;
}

- (void)setMenuCornerRadius:(CGFloat)menuCornerRadius {
    _menuCornerRadius = menuCornerRadius;
    self.menuView.layer.cornerRadius = menuCornerRadius;
}

#pragma mark - getter

- (JHPageMenuView *)menuView {
    if (!_menuView) {
        _menuView = [[JHPageMenuView alloc] init];
        _menuView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        _menuView.scrollDirection = (self.menuLocationStyle == JHPageMenuLocationStyleTop || self.menuLocationStyle == JHPageMenuLocationStyleBottom || self.menuLocationStyle == JHPageMenuLocationStyleNavBar) ? JHPageMenuScrollDirectionHorizontal : JHPageMenuScrollDirectionVertical;
        _menuView.delegate = self;
        _menuView.dataSource = self;
    }
    return _menuView;
}

- (UIPageViewController *)pageViewController {
    if (!_pageViewController) {
        _pageViewController = [[UIPageViewController alloc]initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:(self.menuLocationStyle == JHPageMenuLocationStyleTop || self.menuLocationStyle == JHPageMenuLocationStyleBottom || self.menuLocationStyle == JHPageMenuLocationStyleNavBar) ? UIPageViewControllerNavigationOrientationHorizontal : UIPageViewControllerNavigationOrientationVertical options:nil];
        _pageViewController.delegate = self;
        _pageViewController.dataSource = self;
        [self addChildViewController:_pageViewController];
    }
    return _pageViewController;
}

- (NSInteger)dataCount {
    return [self.dataSource numbersOfViewControllerInPageController:self];
}

#pragma mark - JHMenuView DataSource & Delegate

- (NSInteger)numbersOfItemsInMenuView:(JHPageMenuView *)menuView {
    return self.dataCount;
}

- (JHPageMenuItem *)menuView:(JHPageMenuView *)menuView menuCellForItemAtIndex:(NSInteger)index {
    return [self.dataSource pageController:self menuView:menuView menuItemAtIndex:index];
}

- (UIView *)decorateItemInMenuView:(JHPageMenuView *)menuView {
    if ([self.dataSource respondsToSelector:@selector(decorateItemInPageController:menuView:)]) {
        return [self.dataSource decorateItemInPageController:self menuView:menuView];
    }
    return nil;
}

- (void)menuView:(JHPageMenuView *)menuView didSelectIndex:(NSInteger)index {
    if (!self.isDragPageContrller) {
        __weak typeof(self)weakSelf = self;
        UIViewController *vc = [self.dataSource pageController:self viewContrlllerAtIndex:index];
        if (vc == nil) { return; }

        NSInteger beforeSelectIndex = self.selectIndex;
        _selectIndex = index;
        [self willEnterViewController];
        if (self.selectIndex == 0 && self.selectIndex == beforeSelectIndex) {
            [self.pageViewController setViewControllers:@[vc] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:^(BOOL finished) {
                [weakSelf didEnterViewController];
            }];
        } else if (self.selectIndex > beforeSelectIndex) {
            [self.pageViewController setViewControllers:@[vc] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:^(BOOL finished) {
                [weakSelf didEnterViewController];
            }];
        } else {
            [self.pageViewController setViewControllers:@[vc] direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:^(BOOL finished) {
                [weakSelf didEnterViewController];
            }];
        }
    }
    self.isDragPageContrller = NO;
}

#pragma mark - pageView dataSource & delagate

- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    NSInteger index = [self.dataSource indexOfViewController:viewController];
    if (index == 0 || (index == NSNotFound)) {
        return nil;
    }
    index --;
    return [self.dataSource pageController:self viewContrlllerAtIndex:index];
}

- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    NSInteger index = [self.dataSource indexOfViewController:viewController];
    if (index == self.dataCount - 1 || (index == NSNotFound)) {
        return nil;
    }
    index ++;
    return [self.dataSource pageController:self viewContrlllerAtIndex:index];
}

- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    UIViewController *nextVC = [pendingViewControllers firstObject];
    NSInteger index = [self.dataSource indexOfViewController:nextVC];
    _selectIndex = index;
    [self willEnterViewController];
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (completed && finished) {
        self.isDragPageContrller = YES;
        [self.menuView selectItemAtIndex:self.selectIndex withAnimation:YES];
        [self didEnterViewController];
    }
}

#pragma mark - private

- (void)willEnterViewController {
    [self.delegate pageController:self willEnterViewControllerAtIndex:self.selectIndex];
}

- (void)didEnterViewController {
    [self.delegate pageController:self didEnterViewControllerAtIndex:self.selectIndex];
}

#pragma mark - public

- (void)reloadData {
    if (self.selectIndex > (self.dataCount - 1)) {
        _selectIndex = 0;
    }
    [self.menuView reloadData];
    UIViewController *vc = [self.dataSource pageController:self viewContrlllerAtIndex:self.selectIndex];
    [self.pageViewController setViewControllers:@[vc] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end


text:
from __future__ import annotations

from typing import Sequence

import pytest

from pants.core.util_rules import stripped_source_files
from pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest
from pants.core.util_rules.stripped_source_files import StrippedSourceFileNames, StrippedSourceFiles
from pants.engine.addresses import Address
from pants.engine.fs import EMPTY_SNAPSHOT
from pants.engine.internals.scheduler import ExecutionError
from pants.engine.target import MultipleSourcesField, SourcesPathsRequest, Target
from pants.testutil.rule_runner import QueryRule, RuleRunner

class TargetWithSources(Target):
    alias = "target"
    core_fields = (MultipleSourcesField,)

@pytest.fixture
def rule_runner() -> RuleRunner:
    return RuleRunner(
        rules=[
            *stripped_source_files.rules(),
            QueryRule(SourceFiles, [SourceFilesRequest]),
            QueryRule(StrippedSourceFiles, [SourceFiles]),
            QueryRule(StrippedSourceFileNames, [SourcesPathsRequest]),
        ],
        target_types=[TargetWithSources],
    )

def get_stripped_files(
    rule_runner: RuleRunner,
    request: SourceFiles,
    *,
    source_root_patterns: Sequence[str] = ("src/python", "src/java", "tests/python"),
) -> list[str]:
    rule_runner.set_options([f"--source-root-patterns={repr(source_root_patterns)}"])
    result = rule_runner.request(StrippedSourceFiles, [request])
    return list(result.snapshot.files)

def test_strip_snapshot(rule_runner: RuleRunner) -> None:
    def get_stripped_files_for_snapshot(
        paths: list[str],
        *,
        source_root_patterns: Sequence[str] = ("src/python", "src/java", "tests/python"),
    ) -> list[str]:
        input_snapshot = rule_runner.make_snapshot_of_empty_files(paths)
        request = SourceFiles(input_snapshot, ())
        return get_stripped_files(rule_runner, request, source_root_patterns=source_root_patterns)

    # Normal source roots
    assert get_stripped_files_for_snapshot(["src/python/project/example.py"]) == [
        "project/example.py"
    ]
    assert (
        get_stripped_files_for_snapshot(
            ["src/python/project/example.py"],
        )
        == ["project/example.py"]
    )

    assert get_stripped_files_for_snapshot(["src/java/com/project/example.java"]) == [
        "com/project/example.java"
    ]
    assert get_stripped_files_for_snapshot(["tests/python/project_test/example.py"]) == [
        "project_test/example.py"
    ]

    # Unrecognized source root
    unrecognized_source_root = "no-source-root/example.txt"
    with pytest.raises(ExecutionError) as exc:
        get_stripped_files_for_snapshot([unrecognized_source_root])
    assert f"NoSourceRootError: No source root found for `{unrecognized_source_root}`." in str(
        exc.value
    )

    # Support for multiple source roots
    file_names = ["src/python/project/example.py", "src/java/com/project/example.java"]
    assert get_stripped_files_for_snapshot(file_names) == [
        "com/project/example.java",
        "project/example.py",
    ]

    # Test a source root at the repo root. We have performance optimizations for this case
    # because there is nothing to strip.
    assert get_stripped_files_for_snapshot(
        ["project/f1.py", "project/f2.py"], source_root_patterns=["/"]
    ) == ["project/f1.py", "project/f2.py"]

    assert get_stripped_files_for_snapshot(
        ["dir1/f.py", "dir2/f.py"], source_root_patterns=["/"]
    ) == ["dir1/f.py", "dir2/f.py"]

    # Gracefully handle an empty snapshot
    assert get_stripped_files(rule_runner, SourceFiles(EMPTY_SNAPSHOT, ())) == []

def test_strip_source_file_names(rule_runner: RuleRunner) -> None:
    def assert_stripped_source_file_names(
        address: Address, *, source_root: str, expected: list[str]
    ) -> None:
        rule_runner.set_options([f"--source-root-patterns=['{source_root}']"])
        tgt = rule_runner.get_target(address)
        result = rule_runner.request(
            StrippedSourceFileNames, [SourcesPathsRequest(tgt[MultipleSourcesField])]
        )
        assert set(result) == set(expected)

    rule_runner.write_files(
        {
            "src/java/com/project/example.java": "",
            "src/java/com/project/BUILD": "target(sources=['*.java'])",
            "src/python/script.py": "",
            "src/python/BUILD": "target(sources=['*.py'])",
            "data.json": "",
            # Test a source root at the repo root. We have performance optimizations for this case
            # because there is nothing to strip.
            #
            # Also, gracefully handle an empty sources field.
            "BUILD": "target(name='json', sources=['*.json'])\ntarget(name='empty', sources=[])",
        }
    )
    assert_stripped_source_file_names(
        Address("src/java/com/project"),
        source_root="src/java",
        expected=["com/project/example.java"],
    )
    assert_stripped_source_file_names(
        Address("src/python"), source_root="src/python", expected=["script.py"]
    )
    assert_stripped_source_file_names(
        Address("", target_name="json"), source_root="/", expected=["data.json"]
    )
    assert_stripped_source_file_names(
        Address("", target_name="empty"), source_root="/", expected=[]
    )


text:
package org.elasticsearch.geometry;

import java.util.List;

/**
 * Represents a MultiPoint object on the earth's surface in decimal degrees and optional altitude in meters.
 */
public class MultiPoint extends GeometryCollection<Point> {
    public static final MultiPoint EMPTY = new MultiPoint();

    private MultiPoint() {
    }

    public MultiPoint(List<Point> points) {
        super(points);
    }

    @Override
    public ShapeType type() {
        return ShapeType.MULTIPOINT;
    }

    @Override
    public <T, E extends Exception> T visit(GeometryVisitor<T, E> visitor) throws E {
        return visitor.visit(this);
    }

}


text:
<?php

declare(strict_types = 1);

namespace Tests\Application\Module\BitBucket;

use AppBuilder\Application\Configuration\ValueObject\Parameters;
use AppBuilder\Application\Module\BitBucket\ExternalLibraryBitBucketService;
use AppBuilder\Application\Module\HttpClient\ExternalLibraryHttpClient;
use AppBuilder\Event\Application\BitbucketTicketMappedEvent;
use AppBuilder\Event\Application\JiraTicketMappedEvent;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\StreamInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * @covers \AppBuilder\Application\Module\BitBucket\ExternalLibraryBitBucketService
 */
class ExternalLibraryBitBucketServiceTest extends TestCase
{
    /** @var LoggerInterface */
    private $logger;

    /** @var EventDispatcherInterface | \PHPUnit_Framework_MockObject_MockObject */
    private $dispatcher;

    /** @var Parameters */
    private $applicationParams;

    /** @var Client | \PHPUnit_Framework_MockObject_MockObject */
    private $client;

    protected function setUp() : void
    {
        $this->logger            = $this->createMock(LoggerInterface::class);
        $this->dispatcher        = $this->createMock(EventDispatcherInterface::class);
        $this->applicationParams = $this->createMock(Parameters::class);
        $this->client            = $this->createMock(Client::class);
    }

    /**
     * @test
     * @dataProvider mappedPrAndResponseData
     */
    public function willDispatchEventWithMappedPullRequest(array $mappedRP, array $content) : void
    {
        $event = $this->createMock(JiraTicketMappedEvent::class);
        $event->method('ticket')->willReturn(['id' => 10]);

        /** @var ExternalLibraryHttpClient */
        $httpClient = new ExternalLibraryHttpClient($this->client, $this->applicationParams);

        /** @var ExternalLibraryBitBucketService */
        $bbService = new ExternalLibraryBitBucketService($httpClient, $this->logger, $this->dispatcher);

        /** @var StreamInterface */
        $body = $this->createMock(StreamInterface::class);
        $body->method('getContents')->willReturn(json_encode($content));

        /** @var Response */
        $response = $this->createMock(Response::class);
        $response->method('getBody')->willReturn($body);

        $this->client->method('request')->willReturn($response);

        $this
            ->dispatcher
            ->expects($this->once())
            ->method('dispatch')
            ->with(
                BitbucketTicketMappedEvent::NAME,
                new BitbucketTicketMappedEvent($mappedRP)
            );

        $bbService->onJiraTicketMapped($event);
    }

    public function mappedPrAndResponseData() : array
    {
        $mappedPR = [
            '10' => [
                'pull_request_branch'      => 'bugfix',
                'pull_request_last_update' => '2017-06-13',
                'pull_request_url'         => 'some_url',
                'pull_request_status'      => 'Done',
                'pull_request_name'        => 'Bugfix',
                'repository'               => 'repo',
            ],
        ];

        $content = [
            'detail' => [
                [
                    'pullRequests' => [
                        [
                            'name'   => 'Bugfix',
                            'source' => [
                                'branch'     => 'bugfix',
                                'repository' => [
                                    'name' => 'repo',
                                ],
                            ],
                            'status'     => 'Done',
                            'url'        => 'some_url',
                            'lastUpdate' => '2017-06-13',
                        ],
                    ],
                ],
            ],
        ];

        return [
            'data1' => [$mappedPR, $content],
        ];
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.smslib.smsserver.gateways (SMSLib 3.5.3)
</TITLE>

<META NAME="date" CONTENT="2013-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

SMSLib 3.5.3

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package org.smslib.smsserver.gateways

SMSServer Gateways.

See:

          Description

Class Summary

AGateway
The AGateway abstract class is an abstraction layer between SMSServer and
 SMSLib gateways.

BulkSmsHttp
SMSServer Application Gateway.

ClickatellHttp
SMSServer Application Gateway.

EzTextingHttp
SMSServer Application Gateway.

IPModem
SMSServer Application Gateway.

KannelHttp
SMSServer Application Gateway.

SerialModem
SMSServer Application Gateway.

SMPPGateway
SMSServer Application Gateway.

TestGateway
Gateway mapped to org.smslib.test.TestGateway.

Package org.smslib.smsserver.gateways Description

SMSServer Gateways.

The org.smslib.smsserver.gateways package contains all implemented SMSServer gateway classes.

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

SMSLib 3.5.3

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

(c) 2002-2011, http://smslib.org


text:
#include "Precompiled.h"

#include "ObjectWrapper.h"
#include "Object.h"

#include "Type.h"

namespace ursine
{
    namespace meta
    {
        ObjectWrapper::ObjectWrapper(Object *instance)
            : m_object( instance )
        {
        }

        Type ObjectWrapper::GetType(void) const
        {
            return m_object->GetType( );
        }

        void *ObjectWrapper::GetPtr(void) const
        {
            return m_object;
        }

        int ObjectWrapper::ToInt(void) const
        {
            return int( );
        }

        bool ObjectWrapper::ToBool(void) const
        {
            return bool( );
        }

        float ObjectWrapper::ToFloat(void) const
        {
            return float( );
        }

        double ObjectWrapper::ToDouble(void) const
        {
            return double( );
        }

        std::string ObjectWrapper::ToString(void) const
        {
            return std::string( );
        }

        VariantBase *ObjectWrapper::Clone(void) const
        {
            return new ObjectWrapper( m_object );
        }

        void ObjectWrapper::OnSerialize(Json::object &output) const
        {
            m_object->OnSerialize( output );
        }

        void ObjectWrapper::OnDeserialize(const Json &input)
        {
            m_object->OnDeserialize( input );
        }
    }
}