text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateContactsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->string('subject');
            $table->string('phone')->nullable();
            $table->integer('user_id')->default(0);
            $table->text('message');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}


text:
package org.libreoffice.example.dialog;

import org.libreoffice.example.helper.DialogHelper;

import com.sun.star.awt.XDialog;
import com.sun.star.awt.XDialogEventHandler;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.uno.XComponentContext;

public class ActionOneDialog implements XDialogEventHandler {

	private XDialog dialog;
	private static final String actionOk = "actionOk";
	private String[] supportedActions = new String[] { actionOk };

	public ActionOneDialog(XComponentContext xContext) {
		this.dialog = DialogHelper.createDialog("ActionOneDialog.xdl", xContext, this);
	}

	public void show() {
		dialog.execute();
	}

	private void onOkButtonPressed() {
		dialog.endExecute();
	}

	@Override
	public boolean callHandlerMethod(XDialog dialog, Object eventObject, String methodName) throws WrappedTargetException {
		if (methodName.equals(actionOk)) {
			onOkButtonPressed();
			return true; // Event was handled
		}
		return false; // Event was not handled
	}

	@Override
	public String[] getSupportedMethodNames() {
		return supportedActions;
	}

}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by zad on 17/1/16.
 */
import React, {PropTypes, Component} from 'react';
import classNames from 'classnames';
import isOneOf from '../../utils/isOneOf';
import _remove from 'lodash/remove';

const menuPrefix = 'zad-menu';
const _type = {
  mode: ['vertical', 'inline']
};

export default class Menu extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expandKeys: 'expandKeys' in this.props ? this.props.expandKeys : this.props.defaultExpandKeys,
      selectedKeys: 'selectedKeys' in this.props ? this.props.selectedKeys : this.props.defaultSelectedKeys,
    };
    this._expandSub = this::this._expandSub;
    this._selectItem = this::this._selectItem;
  }

  static propTypes = {
    mode: PropTypes.oneOf(['vertical', 'inline']),
    level: PropTypes.number,
    prefix: PropTypes.string,
    expandKeys: PropTypes.arrayOf(PropTypes.string),
    defaultExpandKeys: PropTypes.arrayOf(PropTypes.string),
    selectedKeys: PropTypes.arrayOf(PropTypes.string),
    defaultSelectedKeys: PropTypes.arrayOf(PropTypes.string),
    onExpandChange: PropTypes.func,
    onSelect: PropTypes.func,
    onlyExpandOneSub: PropTypes.bool,
  };

  static defaultProps = {
    mode: 'inline',
    level: 1,
    prefix: menuPrefix,
    defaultExpandKeys: [],
    defaultSelectedKeys: [],
    onExpandChange: () => undefined,
    onSelect: () => undefined,
    onlyExpandOneSub: false,
  };

  componentWillReceiveProps(nextProps) {
    // 为受控组件时,运行如下代码
    const keys = {};
    if ('selectedKeys' in nextProps) {
      keys.selectedKeys = nextProps.selectedKeys;
    }
    if ('expandKeys' in nextProps) {
      keys.expandKeys = nextProps.expandKeys;
    }
    this.setState(keys);
  }

  renderChildren(props) {
    const {expandKeys, selectedKeys} = this.state;
    return React.Children.map(props.children, (child) => {
      return React.cloneElement(child,
        {
          ...child.props,
          level: props.level,
          prefix: props.prefix,
          expandKeys,
          selectedKeys,
          eventKey: child.key,
          _expandSub: this._expandSub,
          _selectItem: this._selectItem,
        });
    });
  }

  _expandSub(args) {
    const expandKeys = this.state.expandKeys.concat();
    const {eventKey, expand, subParentKey} = args;
    if (!expand) {
      // 当onlyExpandOneSub为true时,清空expandKeys数组
      if (!subParentKey && this.props.onlyExpandOneSub) {
        _remove(expandKeys, (key) => eventKey !== key);
      }
      expandKeys.push(eventKey);
    } else {
      _remove(expandKeys, (key) => eventKey === key);
    }
    if (!('expandKeys' in this.props)) {
      this.setState({expandKeys});
    }
    this.props.onExpandChange(expandKeys);
  }

  _selectItem(args) {
    if (!('selectedKeys' in this.props)) {
      this.setState({
        selectedKeys: args.key,
      });
    }
    this.props.onSelect(args);
  }

  render() {
    const {mode} = this.props;
    const menuClass = classNames(menuPrefix, {
      [`${menuPrefix}-${mode}`]: mode && isOneOf(_type.mode, mode),
    });

    return (
      <ul className={menuClass}>
        {this.renderChildren(this.props)}
      </ul>
    );
  }
}


text:
layout: post
date: 2010-09-06
time: "09:00:00"
authors: ["Greg Wilson"]
title: Getting the Source
tags: ["Community"]
---

In response to several queries: if you'd like to get the source for both the Version 3 material (the old static HTML pages) and the new Version 4 stuff, they're both in our Subversion repository at http://software-carpentry.org/swc. The whole world should have read permission; please let us know if you run into any problems.

And if you're minded to contribute material, we'd welcome help: please contact us by email to talk about what you could do.


text:
package me.jessyan.mvparms.demo.mvp.model;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.OnLifecycleEvent;

import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.mvp.BaseModel;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;
import io.rx_cache2.DynamicKey;
import io.rx_cache2.EvictDynamicKey;
import me.jessyan.mvparms.demo.mvp.contract.UserContract;
import me.jessyan.mvparms.demo.mvp.model.api.cache.CommonCache;
import me.jessyan.mvparms.demo.mvp.model.api.service.UserService;
import me.jessyan.mvparms.demo.mvp.model.entity.User;
import timber.log.Timber;

/**
 * ================================================
 * 展示 Model 的用法
 *
 * @see Model wiki 官方文档
 * Created by JessYan on 09/04/2016 10:56
 * Contact me
 * Follow me
 * ================================================
 */
@ActivityScope
public class UserModel extends BaseModel implements UserContract.Model {
    public static final int USERS_PER_PAGE = 10;

    @Inject
    public UserModel(IRepositoryManager repositoryManager) {
        super(repositoryManager);
    }

    @Override
    public Observable<List<User>> getUsers(int lastIdQueried, boolean update) {
        //使用rxcache缓存,上拉刷新则不读取缓存,加载更多读取缓存
        return Observable.just(mRepositoryManager
                .obtainRetrofitService(UserService.class)
                .getUsers(lastIdQueried, USERS_PER_PAGE))
                .flatMap((Function<Observable<List<User>>, ObservableSource<List<User>>>) listObservable -> mRepositoryManager.obtainCacheService(CommonCache.class)
                        .getUsers(listObservable
                                , new DynamicKey(lastIdQueried)
                                , new EvictDynamicKey(update))
                        .map(listReply -> listReply.getData()));

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void onPause() {
        Timber.d("Release Resource");
    }

}


text:
@interface PodsDummy_UPCarouselFlowLayout : NSObject
@end
@implementation PodsDummy_UPCarouselFlowLayout
@end


text:
..
    This file is part of Invenio.
    Copyright (C) 2020 CERN.

    Invenio is free software; you can redistribute it and/or modify it
    under the terms of the MIT License; see LICENSE file for more details.

.. _user-interface-styling:

User interface styling
======================

In this documentation you will learn how Invenio integrates modern frontend
frameworks and web assets building to display nice looking user interfaces.
You will also read about how to customize the look and feel or add your own
web assets.

.. _semantic-ui-styling:

Semantic UI styling
-------------------

**Scope**

This section explains the basics of how the CSS framework Semantic UI is
integrated into Invenio. Invenio supports multiple CSS frameworks.
The default CSS framework is Semantic UI, and this section only describes
how you can customize the Semantic UI styling. It does not describe how to
replace e.g. Semantic UI with other CSS frameworks like Material Design
or Bootstrap.

**Intended audience**

This section is intended for developers of Invenio instances and modules, who
want to understand the fundamentals of how Semantic UI is integrated into
Invenio, and how to override the Semantic UI default styling.

Developers are expected to have prior experience with CSS and LESS.

**Prerequisites**

* Quick start: The entire section assumes you have followed the Quick Start to
  have a basic Invenio instance.
* Tutuorial: You are recommended to first follow the tutorials on customizing
  the look and feel.

Overview
^^^^^^^^

Semantic UI is a highly customizable CSS framework, that itself can be made to
partially look like other CSS frameworks such as Material Design and Bootstrap.
The section describes the following:

* Developing with Semantic UI - how you efficiently can change styles
  and quickly see the result via e.g. watching for changes.
* Rendering a page - explains how the CSS/JS is loaded on a rendered page.
* Understand the Semantic UI files - explains the build process and provides
  an overview of the files and their purpose.
* Theming - explains the basics behind theming Semantic UI.

Developing with Semantic UI
^^^^^^^^^^^^^^^^^^^^^^^^^^^

First of all, it's important to understand how to develop efficiently with the
Semantic UI.

**Config**

First, verify that the ``APP_THEME`` configuration variable in ``config.py``
is set like below:

.. code-block:: python

    APP_THEME = ['semantic-ui']

**Symlinks**

Assuming you have followed the Quick start, you should first export the
``FLASK_ENV`` environment variable if not already done:

.. code-block:: shell

    cd my-site/
    export FLASK_ENV=development

The ``FLASK_ENV`` variable is used during development to ensure CSS,
JavaScript and other static/assets files are symlinked into their build
location so that if you edit a file the changes are immediately available.

**Static files**

Next, collect all static files into the Flask instance folder
(``<VIRTUALENV>/var/instance/static/``). Usually this is e.g. images which
does not need to be part of the Webpack build.

.. code-block:: shell

    pipenv run invenio collect

**Clean Webpack build**

Once ``FLASK_ENV`` has been set, you need to clean the existing Webpack
project build to ensure that files are properly symlinked. If this step is
not applied, you risk having outdated files in your assets build, and none
of your changes being applied:

.. code-block:: shell

    pipenv run invenio webpack clean buildall

The above does the following:

* Removes the existing Webpack project in ``<VIRTUALENV>/var/instance/assets``.
* Creates the Webpack project in ``<VIRTUALENV>/var/instance/assets`` by
  collecting all assets from all Invenio modules and the Invenio instance.
* Installs the Node modules defined by the Webpack project's ``package.json``
  (e.g. Semantic UI is installed like this).
* Run the Webpack build.

The last two steps, is roughly equivalent of running the following commands:

.. code-block:: shell

    cd <VIRTUALENV>/var/instance/assets
    npm install
    npm run build

**Watching changes**

You now have a clean build of assets where files have been symlinked. You
start watching changes to the files by running:

.. code-block:: shell

    pipenv run invenio webpack run start

Note that this is a long-running operation, so it will "block" the shell
until you stop it, and therefore stop watching for changes.

If you edit a file, the Webpack project will be automatically rebuilt.

In a different shell, you can then start  the server:

.. code-block:: shell

    ./scripts/server

IMPORTANT: Watching for changes only works if you have followed above steps.
In particular:

* Files must have been symlinked by setting ``export FLASK_ENV=development``
  and performing a full wipe and rebuild of static and assets.
* The Python packages (e.g. your Invenio instance) was installed with Python
  develop mode (this is default for the Quick Start guide).
* Newly added/removed files are not automatically taken into account. If you
  add a new file, just must run ``pipenv run invenio webpack create build``.
  If you remove a file, just must rebuild the entire Webpack
  ``pipenv run invenio webpack clean buildall``

Rendering a page
^^^^^^^^^^^^^^^^

Before, diving deeper into how to change and add new styles, it's important
to understand how the CSS/JavaScript files generated by the Webpack project
are being included in the HTML documents.

**Jinja template rendering**

All HTML pages are being rendered in Flask via the Jinja template engine.
Below is a very simplified example of how such as Flask view looks like:

.. code-block:: python

    # a very simplified example of template rendering
    from flask import render_template

    @app.route('/')
    def index():
        return render_template('frontpage.html')

The ``render_template()`` will look for the ``frontpage.html`` in multiple
template search paths (see Web assets build system) and render an HTML
document.

**Including assets in templates**

A Jinja template like ``frontpage.html`` usually extends from a base template
implementing the overall layout called ``page.html``. If we remove all the
complexities, there's two template blocks in the template responsible for
including the built assets: ``css`` and ``javascript`` which looks like below:

.. code-block:: jinja

    {# simplified view of page.html in Invenio-Theme #}
    ...
    {% block css %}
        {{ webpack['theme.css'] }}
    {% endblock %}
    ...
    {% block javascript %}
        {{ webpack['base.js']} }
        {{ webpack['theme.js'] }}
        {{ webpack['i18n_app.js'] }}
    {% endblock %}
    ...

The key assets for Semantic UI is the ``theme.css`` and ``theme.js``. Both
of them come from a single Webpack entry point called ``theme`` defined
in Invenio-Theme.

**Webpack bundles and entry points**

In Invenio-Theme in ``webpack.py`` you'll find a Webpack theme bundle
defining the ``theme`` Webpack entry point. It looks somewhat like this:

.. code-block:: python

    # webpack.py in Invenio-Theme
    from invenio_assets.webpack import WebpackThemeBundle

    theme = WebpackThemeBundle(
        __name__,
        'assets',
        themes={
            'semantic-ui': {
                'entry': {
                    # Webpack entry point
                    'theme': './js/invenio_theme/theme.js',
                    # ...
                },
                'dependencies': {
                    # NPM dependencies
                    'semantic-ui-less': '~2.4.1',
                    'semantic-ui-css': '~2.4.1',
                    # ...
                },
            }
            # ...
        }
    )

The ``theme`` Webpack entry point is what allows you to use
``{{ webpack['theme.js'] }}`` and ``{{ webpack['theme.css'] }}`` in the
Jinja templates. Note that the ``.js`` and ``.css`` extensions is because
Webpack automatically splits CSS/JavaScript into separate files.

If you look inside the file ``./js/invenio_theme/theme.js`` you find the
following lines:

.. code-block:: javascript

    // theme.js in Invenio-Theme
    import "semantic-ui-css/semantic.js";
    import "semantic-ui-less/semantic.less";

.. note::

    Above is what kicks off the entire Semantic UI build. The entire
    customization and everything described in the following sections is started
    from this file. Thus, the ``theme`` Webpack entry point is the absolute
    critical piece which is responsible for the integrating Semantic UI
    in Invenio.

The Semantic UI build
^^^^^^^^^^^^^^^^^^^^^

The previous section shows how Invenio-Theme defines a Webpack entry point
called ``theme`` which is responsible for building the CSS and JavaScript
for Semantic UI.

**Webpack alias for the theme config**

The Webpack entry point ``theme`` relies on a file ``theme.config`` to be
provided by your Invenio instance. The way your Invenio instance provide
this file is via a Webpack bundle. The file looks similar to below:

.. code-block:: python

    # webpack.py in your Invenio instance
    from invenio_assets.webpack import WebpackThemeBundle

    theme = WebpackThemeBundle(
        __name__,
        'assets',
        default='semantic-ui',
        themes={
            'semantic-ui': dict(
                # ...
                aliases={
                    '../../theme.config$': 'less/my_site/theme.config',
                },
            ),
        }
    )

The Webpack bundle defines a Webpack alias ``../../theme.config$``, which
points to the ``theme.config`` file in your Invenio instance. The name exact
name ``../../theme.config$`` is very important because this is the name that
Semantic UI uses to import the config, similar to this

.. code-block:: less

    // Example from Semantic UI code
    @import (multiple) '../../theme.config';

**Theme configuration (``theme.config``)**

The ``theme.js`` in Invenio-Theme is central for the overall Semantic UI
build, however, the ``theme.config`` in your Invenio instance is the central
file for how you customize your Invenio instance's Semantic UI build. A part
of the fille is shown below:

.. code-block:: less

    /*

    ████████╗██╗  ██╗███████╗███╗   ███╗███████╗███████╗
    ╚══██╔══╝██║  ██║██╔════╝████╗ ████║██╔════╝██╔════╝
    ██║   ███████║█████╗  ██╔████╔██║█████╗  ███████╗
    ██║   ██╔══██║██╔══╝  ██║╚██╔╝██║██╔══╝  ╚════██║
    ██║   ██║  ██║███████╗██║ ╚═╝ ██║███████╗███████║
    ╚═╝   ╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝╚══════╝╚══════╝
    */

    /* Global */
    @site        : 'invenio';
    @reset       : 'default';

    /* Elements */
    @button      : 'invenio';
    @container   : 'invenio';

    // ...

    /* Path to site override folder */
    @siteFolder  : '../../less/my_site/site';

    // ...

**Theming overview**

Semantic UI theming inheritance is what provides the powerful customization
options of Semantic UI, and what allows Semantic UI to look partially
like Bootstrap or Material Design.

Semantic UI supports three layers of theme inheritance:

* *Default theme*: Semantic UI comes with defaults styled components, and
  defines a lot of variables that can be overwritten.
* *Package theme*: The packaged themes provides customizations on top of
  the default theme. This is here you can choose between e.g. Bootstrap,
  Material Design or your own packaged theme.
* *Site Theme*: The site theme provides customizations on top of the default
  and package themes. Usually it's here you set e.g. your brand color.

**Site folder**

The ``@siteFolder`` variable in ``theme.config`` is what defines where your
site theme is loaded from. By default, in your Invenio instance, you'll find
site folder next to your ``theme.config`` in ``site``:

.. code-block::

    .
    |-- site
    |   `-- globals
    |       |-- site.overrides
    |       `-- site.variables
    `-- theme.config

By default you'll find two files in there:

* ``globals/site.overrides`` - An ``.overrides`` file specifies additional
  CSS rules to be added to a definition for a theme.
* ``globals/site.variables`` - A ``.variables`` file specifies variables
  which should be adjusted for a theme.

Usually, you can add your custom CSS in ``site.overrides`` and your variable
definitions in ``site.variables``.

**Theme defintions**

The ``theme.config`` specifies theme definitions for specific components.
For instance:

.. code-block:: less

    @site        : 'invenio';

Above, tells Semantic UI to use the *packaged theme* ``invenio``. You can
change it to use e.g. the ``default`` package theme, or other themes like
``bootstrap`` or ``material``.

Overall the theming is divided into:

* Global site-wide overrides/variables that affect all components
  (e.g. fonts, colors, ..)
* Elements overrides/variables for e.g. buttons, labels, and lists.
* Collections overrides/variables for e.g. breadcrumbs, forms and tables.
* Views overrides/variables for e.g. comments, cards, statistics and similar.
* Modules overrides/variables for e.g. accordion, dropdown, modals etc.

For each component, you can choose a specific theme:

.. code-block:: less

    /* Global */
    @site        : 'invenio';
    @reset       : 'default';

    /* Elements */
    @button      : 'material';
    // ...

    /* Collections */
    // ...

    /* Modules */
    // ...

    /* Views */
    // ...

Note, that a theme may not define all components. For instance ``material``
theme defines only ``button`` and ``site`` components thus trying to do
this will fail:

.. code-block:: less

    // This will fail because 'material' theme is not defined for
    // the modal component:
    @modal       : 'material';

**Components and themes**

It's important to understand that you can customize Semantic UI at many
different levels. First of all, Semantic UI has a number of **components**
categorized into globals, elements, collections, views and modules.

Each **component** can be customized by a **theme** that is subject to the
theme inheritance.

As an example, the element component *button* can be customized by:

* Site theme - i.e. adding the files ``site/elements/button.overrides``
  and ``site/elements/button.variables`` in your Invenio instance.
* Package theme - i.e. by changing ``@button : `<theme>`` in ``theme.config``.

**The ``invenio`` packaged theme**

Invenio-Theme defines a **packaged theme** named ``invenio``, which you can
find in ``invenio_theme/assets/semantic-ui/less/invenio_theme/theme``. The
theme overrides some of the defaults for use with Invenio and defines
e.g. variables to make it easier to customize the sign up button and
search button colors.

**Further reading**

* `Semantic UI Glossary <https://semantic-ui.com/introduction/glossary.html>`_
* `Semantic UI Theming <https://semantic-ui.com/usage/theming.html>`_
* `Semantic UI Documentation <https://semantic-ui.com>`_
* `React-SemanticUI Documentation <https://react.semantic-ui.com>`_

Web assets
----------

Most of the user interfaces in Invenio use CSS for the layout and JavaScript
to improve user experience. Such web assets, injected in the Jinja templates,
are transformed from their original format to an optimized version thanks to
Node packages and the Webpack bundler.
For example, style sheets rules are written using the LESS language extension
and then converted to minified CSS, natively understandable by your browser.

Web assets with Python
^^^^^^^^^^^^^^^^^^^^^^

One of the first things to look at when working with modern web applications
is how to install and build web assets. Node packages, managed with
`npm <http://npmjs.org/>`_, and Webpack are probably the most well-known
tools in the front-end development ecosystem.

A common, minimal web assets build could look like:

* ``package.json``:

.. code-block:: json

    {
    "version": "0.0.1",
    "scripts": {
        "build": "webpack --config webpack.config.js"
    }
    "dependencies": {
        "lodash": "^4.17.0"
    }
    }

* ``webpack.config.js``:

.. code-block:: javascript

    var path = require("path");

    module.exports = {
        context: path.resolve(__dirname, "src"),
        entry: "./index.js",
        output: {
            filename: "[name].js",
            path: path.resolve(__dirname, "dist")
        }
    };

With the example above, executing ``npm install && npm run build`` will create
the final JS bundle in a ``dist`` folder.

Invenio uses a few extra packages to integrate web assets building with Python.
Below, you will find a brief introduction to these packages.

**Install npm packages**

Invenio uses `PyNPM <https://pynpm.readthedocs.io>`_ to execute ``npm``
commands with Python. This package's responsibility is to wrap the npm
binary and provide Python APIs for the most common commands, such as ``init``,
``install`` or ``test``. It does not expose command line commands.

**Build npm packages**

The `PyWebpack <https://pywebpack.readthedocs.io>`_ and
`Flask-WebpackExt <https://flask-webpackext.readthedocs.io>`_ packages take
care of integrating Webpack with the Python ecosystem. While the main
responsibility of the former is to wrap a Webpack build and enable its usage
with Python, for the latter is to integrate a Flask application, its
configurations and Jinja templates.

To build the web assets of your Flask project, you will need a folder,
e.g. ``assets``, containing a ``package.json`` and a ``webpack.config.js``
files.
Then, you instantiate a
`WebpackBundleProject <https://pywebpack.readthedocs.io/en/latest/api.html#pywebpack.project.WebpackBundleProject>`_:

.. code-block:: python

    from flask_webpackext import WebpackBundleProject

    project = WebpackBundleProject(
        __name__,
        project_folder="assets",
        config_path="build/config.json"
    )

As done in the example above, you can optionally pass a ``config_path``
file path (or a config ``dict``) parameter. Such Python config can be
injected in the Webpack configuration file to specify the location
of the generated output files and other settings. See
`flask_config <https://flask-webpackext.readthedocs.io/en/latest/api.html#flask_webpackext.project.flask_config>`_
the default configuration.

You can now execute the build. The built web assets will be created in the
``dist`` folder:

.. code-block:: shell

    flask webpack buildall

Along with the built web assets, one of the Webpack output file is
the ``manifest.json``: it contains a map with the name of each asset and
its "hashed" version:

.. code-block:: json

    {
        "main.js": "/static/dist/main.75244bb780acd727ebd3.js"
    }

This file is parsed and made available to the Python application so that
assets can be injected in the Jinja templates simply by their name. At
render time, the file name will be mapped to the hashed one:

.. code-block:: html

    <script src="/static/dist/main.75244bb780acd727ebd3.js"></script>

**Multiple Python packages**

With PyWebpack you can collect and build assets from different Python
packages via entry points. This is useful when having a main Flask
application that uses assets contained in other installed packages,
which is the case of Invenio.
Each Python package declares what assets needs, for example:

.. code-block:: python

    from flask_webpackext import WebpackBundle

    js = WebpackBundle(
        __name__,
        "./modules/module1/static",
        entry={
            "module1-app": "./js/module1-app.js",
        },
        dependencies={
            "lodash": "^4.17.0"
        }
    )

It then exposes them via entry points. In the ``setup.py``:

.. code-block:: python

    setup(
        ...
        entry_points={
            ...
            "webpack_bundles": [
                "mymodule1_js = mymodule.bundles:js",
            ],
    )

The main application, or the package responsible of building web assets,
defines the Webpack project:

.. code-block:: python

    from flask_webpackext import WebpackBundleProject

    project = WebpackBundleProject(
        __name__,
        project_folder="assets",
        config_path="build/config.json",
        bundles=bundles_from_entry_point("invenio_assets.webpack"),
    )

When running ``flask webpack buildall``, Pywebpack will discover all the
declared bundles, collect the dependencies and merge them into a final
``package.json`` in a temporary build folder. It will then run
``npm install`` and invoke the Webpack build.

In this section, you have learned how you can build web assets with npm
and Webpack using PyNPM, PyWebpack and Flask-WebpackExt in a Flask
application. You read more about each package in each documentation.

Invenio web assets
^^^^^^^^^^^^^^^^^^

In the next section you will learn how Invenio uses the web assets
integration with Python explained above and allows you define your own
templates and web assets.

The ``Invenio-Assets`` package defines the main Webpack project and
exposes the entry point name ``invenio_assets.webpack`` that can
be used by other Invenio packages:

.. code-block:: python

    from flask_webpackext import WebpackBundleProject

    project = WebpackBundleProject(
        __name__,
        project_folder="assets",
        config_path="build/config.json",
        bundles=bundles_from_entry_point("invenio_assets.webpack"),
    )

The ``assets`` folder contains:

* the base ``package.json``, which defines all the ``npm`` dependencies
  required to build web assets (webpack and plugins, babel, eslint,
  less/css loaders, etc.). Note that it does not contain CSS or JS
  packages for the Invenio layout;
* the ``build/webpack.config.js`` Webpack configuration file, which defines
  the build process;

The Invenio Webpack configuration includes the optimization of CSS and
JavaScript assets, the creation of the ``manifest.json`` needed for
the Jinja templates and it enables
`chunks <https://webpack.js.org/plugins/split-chunks-plugin/>`_ to minimize
the size of the downloaded assets in each web page.

**Building assets**

When bootstrapping Invenio, the ``/scripts/bootstrap`` will run the commands
``collect`` and ``webpack buildall``. By default, static files such as
Jinja templates, CSS and JavaScript files are copied in the
``<virtualenv>/var/instance/`` ``assets`` and ``static`` folders so that
they are available for the Webpack build. The ``assets`` folder is the
build directory used by Npm and Webpack.

The final CSS, JavaScripts, images and fonts files built by Webpack are
created in the ``static/dist`` folder. Each filename contains an unique
hash, e.g. ``theme.0346fcac8ffc95821e90.css``, which is different
at each build.

This allows to optimize how browsers will download static files,
given that they can be cached without expiration. There is a drawback:
assets cannot be easily added to Jinja templates, for example with
``<script type="application/javascript" src="main.js"></script>``,
because the filename is not known in advance when developing.

**Using assets in templates**

The ``dist/manifest.json`` is the registry of the built web assets and
contains the map with the chunks generated by the Webpack built. Thanks
to this, there is no need to manually add vendors or library bundles to
Jinja templates. Invenio provides some utilities that will automatically
inject assets dependencies to the generated HTML files.
For example, given the following ``WebpackBundle``:

.. code-block:: python

    from flask_webpackext import WebpackBundle

    js = WebpackBundle(
        __name__,
        "./modules/module1/static",
        entry={
            "module1-app": "./js/module1-app.js",
        },
        dependencies={
            "lodash": "^4.17.0",
            "react": "^17.0.0",
        }
    )

The Jinja template will look like:

.. code-block:: jinja

    ...
    {{ webpack['module1-app.js']}}
    ...

.. note:

    As you can see, the ``react`` or ``lodash`` dependencies needed by
    ``module1-app`` are not added to the template: the minimal amount of
    needed chunks will be automatically injected.

Themes
^^^^^^

Invenio comes with the support of multiple UI theming. This is because
the UI framework has been switched from Bootstrap 3 to Semantic UI.
To learn how to change the theme layout or integrate your own them, please
refer to the documentation :ref:`semantic-ui-styling`.

In this section you will learn how Invenio manages multiple themes.

In Invenio-Assets, the ``WebpackThemeBundle`` extends the concepts explained
above with the ``WebpackBundleProject`` configuration. It basically allows
to define multiple ``WebpackBundleProject``, namespaced by the name of
your theme.
In Invenio there are 2 themes defined (see ``Invenio-Theme`` for
more information):

.. code-block:: python

    from invenio_assets.webpack import WebpackThemeBundle

    theme = WebpackThemeBundle(
        __name__,
        "assets",
        default="bootstrap3",
        themes={
            "bootstrap3": dict(
                entry={
                    ...
                },
                dependencies={
                    ...
                }
            ),
            "semantic-ui": dict(
                entry={
                    ...
                },
                dependencies={
                    ...
                }
            ),
        }
    )

As you can see, the 2 themes ``bootstrap3`` and ``semantic-ui`` are listed
in the ``themes`` parameter. They correspond to two different
``WebpackBundleProject``. The global configuration variable ``APP_THEME``
will instruct Invenio, at runtime, which one to use. For example:

.. code-block:: python

    APP_THEME = ["semantic-ui"]

Each Invenio module that adds web assets can provide a different set
of assets per theme. The resolution mechanism ensures that only the web
assets for the current theme will be loaded and injected in Jinja templates.
The ``default`` option is used as a fallback in case that no theme is set
(``APP_THEME`` is not defined or empty).

**Jinja templates**

Jinja templates resolutoin supports themes. As for web assets, you can
create specific Jinja templates for your theme.
When resolving the Jinja template file to use, Invenio will prefix the
file path with the name of the theme that you have defined
with the ``APP_THEME`` configuration.

For example, in Invenio you can have the following:

.. code-block::

    templates/
    semantic-ui/
        <module-name>/
        index.html
    templates/
    <my-theme-name>/
        <module-name>/
        index.html

**Further reading**

* `PyNPM <https://pynpm.readthedocs.io>`_
* `PyWebpack <https://pywebpack.readthedocs.io>`_
* `Flask-WebpackExt <https://flask-webpackext.readthedocs.io>`_
* `Invenio-Assets <https://invenio-assets.readthedocs.io>`_
* `Invenio-Theme <https://invenio-theme.readthedocs.io>`_


text:
package de.develman.mmi.algorithm;

import de.develman.mmi.model.Edge;
import de.develman.mmi.model.Graph;
import de.develman.mmi.model.Vertex;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * Die Klasse NearestNeighbour implementiert den Nearest-Neighbour Algorithmus zur Berechnung der TSP-Tour in einem
 * vollständigen Graphen mit Kantengewichten
 *
 * @author Georg Henkel <georg@develman.de>
 */
public class NearestNeighbour
{
    /**
     * Berechnung einer TSP-Tour
     *
     * @param graph Vollständiger Graph mit Kantengewichten
     * @param startVertex Startknoten
     * @return Liste der Kanten der TSP-Tour
     */
    public List<Edge> findTour(Graph graph, Vertex startVertex)
    {
        List<Edge> tour = new ArrayList<>();

        Vertex vertex = startVertex;
        do
        {
            vertex.setVisited(true);

            Edge bestEdge = getBestEdge(vertex);
            if (bestEdge == null)
            {
                tour.add(vertex.getEdgeTo(startVertex.getKey()));
                break;
            }

            vertex = bestEdge.getSink();
            tour.add(bestEdge);
        }
        while (!allVerticesVisited(graph));

        return tour;
    }

    private boolean allVerticesVisited(Graph graph)
    {
        return graph.getVertices().stream().filter(v -> !v.isVisited()).count() == 0;
    }

    private Edge getBestEdge(Vertex vertex)
    {
        Optional<Edge> foundEdge = vertex.getOutgoingEdges().stream().filter(e -> !e.getSink().isVisited()).sorted(
                Comparator.comparing(Edge::getCapacity)).findFirst();

        Edge bestEdge = null;
        if (foundEdge.isPresent())
        {
            bestEdge = foundEdge.get();
        }

        return bestEdge;
    }
}


text:
package org.elasticsearch.xpack.watcher.actions.index;

import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.xpack.core.ClientHelper;
import org.elasticsearch.xpack.core.watcher.actions.Action;
import org.elasticsearch.xpack.core.watcher.actions.Action.Result.Status;
import org.elasticsearch.xpack.core.watcher.actions.ExecutableAction;
import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils;
import org.elasticsearch.xpack.core.watcher.support.xcontent.XContentSource;
import org.elasticsearch.xpack.core.watcher.watch.Payload;
import org.elasticsearch.xpack.watcher.support.ArrayObjectIterator;

import java.io.IOException;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.xpack.core.watcher.support.Exceptions.illegalState;

public class ExecutableIndexAction extends ExecutableAction<IndexAction> {

    private static final String INDEX_FIELD = "_index";
    private static final String TYPE_FIELD = "_type";
    private static final String ID_FIELD = "_id";

    private final Client client;
    private final TimeValue indexDefaultTimeout;
    private final TimeValue bulkDefaultTimeout;

    public ExecutableIndexAction(IndexAction action, Logger logger, Client client,
                                 TimeValue indexDefaultTimeout, TimeValue bulkDefaultTimeout) {
        super(action, logger);
        this.client = client;
        this.indexDefaultTimeout = action.timeout != null ? action.timeout : indexDefaultTimeout;
        this.bulkDefaultTimeout = action.timeout != null ? action.timeout : bulkDefaultTimeout;
    }

    @Override
    public Action.Result execute(String actionId, WatchExecutionContext ctx, Payload payload) throws Exception {
        Map<String, Object> data = payload.data();
        if (data.containsKey("_doc")) {
            Object doc = data.get("_doc");
            if (doc instanceof Iterable) {
                return indexBulk((Iterable) doc, actionId, ctx);
            }
            if (doc.getClass().isArray()) {
                return indexBulk(new ArrayObjectIterator.Iterable(doc), actionId, ctx);
            }
            if (doc instanceof Map) {
                data = (Map<String, Object>) doc;
            } else {
                throw illegalState("could not execute action [{}] of watch [{}]. failed to index payload data." +
                        "[_data] field must either hold a Map or an List/Array of Maps", actionId, ctx.watch().id());
            }
        }

        if (data.containsKey(INDEX_FIELD) || data.containsKey(TYPE_FIELD) || data.containsKey(ID_FIELD)) {
            data = mutableMap(data);
        }
        IndexRequest indexRequest = new IndexRequest();
        if (action.refreshPolicy != null) {
            indexRequest.setRefreshPolicy(action.refreshPolicy);
        }

        indexRequest.index(getField(actionId, ctx.id().watchId(), "index", data, INDEX_FIELD, action.index));
        indexRequest.id(getField(actionId, ctx.id().watchId(), "id",data, ID_FIELD, action.docId));

        data = addTimestampToDocument(data, ctx.executionTime());
        BytesReference bytesReference;
        try (XContentBuilder builder = jsonBuilder()) {
            indexRequest.source(builder.prettyPrint().map(data));
        }

        if (ctx.simulateAction(actionId)) {
            return new IndexAction.Simulated(indexRequest.index(), indexRequest.id(),
                action.refreshPolicy, new XContentSource(indexRequest.source(), XContentType.JSON));
        }

        IndexResponse response = ClientHelper.executeWithHeaders(ctx.watch().status().getHeaders(), ClientHelper.WATCHER_ORIGIN, client,
                () -> client.index(indexRequest).actionGet(indexDefaultTimeout));
        try (XContentBuilder builder = jsonBuilder()) {
            indexResponseToXContent(builder, response);
            bytesReference = BytesReference.bytes(builder);
        }
        return new IndexAction.Result(Status.SUCCESS, new XContentSource(bytesReference, XContentType.JSON));
    }

    Action.Result indexBulk(Iterable list, String actionId, WatchExecutionContext ctx) throws Exception {
        if (action.docId != null) {
            throw illegalState("could not execute action [{}] of watch [{}]. [doc_id] cannot be used with bulk [_doc] indexing");
        }

        BulkRequest bulkRequest = new BulkRequest();
        if (action.refreshPolicy != null) {
            bulkRequest.setRefreshPolicy(action.refreshPolicy);
        }

        for (Object item : list) {
            if (!(item instanceof Map)) {
                throw illegalState("could not execute action [{}] of watch [{}]. failed to index payload data. " +
                        "[_data] field must either hold a Map or an List/Array of Maps", actionId, ctx.watch().id());
            }

            Map<String, Object> doc = (Map<String, Object>) item;
            if (doc.containsKey(INDEX_FIELD) || doc.containsKey(TYPE_FIELD) || doc.containsKey(ID_FIELD)) {
                doc = mutableMap(doc);
            }

            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index(getField(actionId, ctx.id().watchId(), "index", doc, INDEX_FIELD, action.index));
            indexRequest.id(getField(actionId, ctx.id().watchId(), "id",doc, ID_FIELD, action.docId));

            doc = addTimestampToDocument(doc, ctx.executionTime());
            try (XContentBuilder builder = jsonBuilder()) {
                indexRequest.source(builder.prettyPrint().map(doc));
            }
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = ClientHelper.executeWithHeaders(ctx.watch().status().getHeaders(), ClientHelper.WATCHER_ORIGIN, client,
                () -> client.bulk(bulkRequest).actionGet(bulkDefaultTimeout));
        try (XContentBuilder jsonBuilder = jsonBuilder().startArray()) {
            for (BulkItemResponse item : bulkResponse) {
                itemResponseToXContent(jsonBuilder, item);
            }
            jsonBuilder.endArray();

            // different error states, depending on how successful the bulk operation was
            long failures = Stream.of(bulkResponse.getItems()).filter(BulkItemResponse::isFailed).count();
            if (failures == 0) {
                return new IndexAction.Result(Status.SUCCESS, new XContentSource(BytesReference.bytes(jsonBuilder), XContentType.JSON));
            } else if (failures == bulkResponse.getItems().length) {
                return new IndexAction.Result(Status.FAILURE, new XContentSource(BytesReference.bytes(jsonBuilder), XContentType.JSON));
            } else {
                return new IndexAction.Result(Status.PARTIAL_FAILURE,
                        new XContentSource(BytesReference.bytes(jsonBuilder), XContentType.JSON));
            }
        }
    }

    private Map<String, Object> addTimestampToDocument(Map<String, Object> data, ZonedDateTime executionTime) {
        if (action.executionTimeField != null) {
            data = mutableMap(data);
            data.put(action.executionTimeField, WatcherDateTimeUtils.formatDate(executionTime));
        }
        return data;
    }

    /**
     * Extracts the specified field out of data map, or alternative falls back to the action value
     */
    private String getField(String actionId, String watchId, String name, Map<String, Object> data, String fieldName, String defaultValue) {
        Object obj = data.remove(fieldName);
        if (obj != null) {
            if (defaultValue != null) {
                throw illegalState("could not execute action [{}] of watch [{}]. " +
                                "[ctx.payload.{}] or [ctx.payload._doc.{}] were set together with action [{}] field. Only set one of them",
                        actionId, watchId, fieldName, fieldName, name);
            } else {
                return obj.toString();
            }
        }

        return defaultValue;
    }

    /**
     * Guarantees that the {@code data} is mutable for any code that needs to modify the {@linkplain Map} before using it (e.g., from
     * singleton, immutable {@code Map}s).
     *
     * @param data The map to make mutable
     * @return Always a {@linkplain HashMap}
     */
    private Map<String, Object> mutableMap(Map<String, Object> data) {
        return data instanceof HashMap ? data : new HashMap<>(data);
    }

    private static void itemResponseToXContent(XContentBuilder builder, BulkItemResponse item) throws IOException {
        if (item.isFailed()) {
            builder.startObject()
                    .field("failed", item.isFailed())
                    .field("message", item.getFailureMessage())
                    .field("id", item.getId())
                    .field("index", item.getIndex())
                    .endObject();
        } else {
            indexResponseToXContent(builder, item.getResponse());
        }
    }

    static void indexResponseToXContent(XContentBuilder builder, IndexResponse response) throws IOException {
        builder.startObject()
                .field("created", response.getResult() == DocWriteResponse.Result.CREATED)
                .field("result", response.getResult().getLowercase())
                .field("id", response.getId())
                .field("version", response.getVersion())
                .field("index", response.getIndex())
                .endObject();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Glimpse.Agent.Inspectors;
using Glimpse.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;

namespace Glimpse.Agent.AspNet.Internal.Inspectors.AspNet
{
    public class AjaxInspector : Inspector
    {
        private readonly IGlimpseContextAccessor _context;

        public AjaxInspector(IGlimpseContextAccessor context)
        {
            _context = context;
        }

        public override void Before(HttpContext context)
        {
            var isAjax = StringValues.Empty;
            if (context.Request.Headers.TryGetValue("__glimpse-isAjax", out isAjax) && isAjax == "true")
            {
                context.Response.Headers.Add("__glimpse-id", _context.RequestId.ToString("N"));
            }
        }
    }
}


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

    <parent>
        <groupId>net.wasdev.maven.parent</groupId>
        <artifactId>java7-parent</artifactId>
        <version>1.4</version>
        <relativePath></relativePath>
    </parent>

    <groupId>net.wasdev.wlp.sample</groupId>
    <artifactId>VuohiTest06</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>Liberty Profile Sample - Servlet</name>
    <url>https://wasdev.github.io</url>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>https://raw.github.com/WASdev/sample.servlet/master/LICENSE</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.geronimo.specs</groupId>
                <artifactId>geronimo-servlet_3.0_spec</artifactId>
                <version>1.0</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-servlet_3.0_spec</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.9.1</version>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-bundle</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20140107</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa</artifactId>
            <version>2.6.4</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.16</version>
        </dependency>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>6.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.0</version>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                        <warName>JavaHelloWorldApp</warName>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>net.wasdev.wlp.maven.plugins</groupId>
                    <artifactId>liberty-maven-plugin</artifactId>
                    <version>1.2.1</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>net.wasdev.wlp.maven.plugins</groupId>
                <artifactId>liberty-maven-plugin</artifactId>
                <configuration>
                    <configFile>src/main/wlp/server.xml</configFile>
                    <bootstrapProperties>
                        <appLocation>../../../../../${project.build.finalName}</appLocation>
                    </bootstrapProperties>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
import sys
import paddle.v2 as paddle
from api_v2_vgg import vgg_bn_drop
from api_v2_resnet import resnet_cifar10

def main():
    datadim = 3 * 32 * 32
    classdim = 10

    # PaddlePaddle init
    paddle.init(use_gpu=True, trainer_count=1)

    image = paddle.layer.data(
        name="image", type=paddle.data_type.dense_vector(datadim))

    # Add neural network config
    # option 1. resnet
    net = resnet_cifar10(image, depth=32)
    # option 2. vgg
    # net = vgg_bn_drop(image)

    out = paddle.layer.fc(input=net,
                          size=classdim,
                          act=paddle.activation.Softmax())

    lbl = paddle.layer.data(
        name="label", type=paddle.data_type.integer_value(classdim))
    cost = paddle.layer.classification_cost(input=out, label=lbl)

    # Create parameters
    parameters = paddle.parameters.create(cost)

    # Create optimizer
    momentum_optimizer = paddle.optimizer.Momentum(
        momentum=0.9,
        regularization=paddle.optimizer.L2Regularization(rate=0.0002 * 128),
        learning_rate=0.1 / 128.0,
        learning_rate_decay_a=0.1,
        learning_rate_decay_b=50000 * 100,
        learning_rate_schedule='discexp',
        batch_size=128)

    # End batch and end pass event handler
    def event_handler(event):
        if isinstance(event, paddle.event.EndIteration):
            if event.batch_id % 100 == 0:
                print "\nPass %d, Batch %d, Cost %f, %s" % (
                    event.pass_id, event.batch_id, event.cost, event.metrics)
            else:
                sys.stdout.write('.')
                sys.stdout.flush()
        if isinstance(event, paddle.event.EndPass):
            result = trainer.test(
                reader=paddle.reader.batched(
                    paddle.dataset.cifar.test10(), batch_size=128),
                reader_dict={'image': 0,
                             'label': 1})
            print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics)

    # Create trainer
    trainer = paddle.trainer.SGD(cost=cost,
                                 parameters=parameters,
                                 update_equation=momentum_optimizer)
    trainer.train(
        reader=paddle.reader.batched(
            paddle.reader.shuffle(
                paddle.dataset.cifar.train10(), buf_size=50000),
            batch_size=128),
        num_passes=5,
        event_handler=event_handler,
        reader_dict={'image': 0,
                     'label': 1})

if __name__ == '__main__':
    main()


text:
package io.truthencode.ddo.model.feats

import io.truthencode.ddo.model.classes.HeroicCharacterClass
import io.truthencode.ddo.model.classes.HeroicCharacterClass.Paladin
import io.truthencode.ddo.support.requisite._

/**
 * [[http://ddowiki.com/page/Aura_of_Good Aura of Good]] This Paladin class feature grants a +1
 * bonus to AC and saving throws to all allies within range.
 */
protected[feats] trait AuraOfGood
  extends FeatRequisiteImpl with Passive with GrantsToClass with RequiresAllOfClass {
  self: ClassFeat =>
  override def grantToClass: Seq[(HeroicCharacterClass, Int)] =
    List((Paladin, 1))

  override def anyOfClass: Seq[(HeroicCharacterClass, Int)] = List((Paladin, 1))
}


text:
using System;
using Xamarin.Forms;

namespace Styr.App
{
	public class InputPopUp : ContentPage
	{
		private Entry input;
		private Label titleLabel;
		private Label msgLabel;
		private StackLayout innerBox;
		private Button submitButton;
		private InputPopUpArgs args;

		public InputPopUp(string title, string message, string placeholder, string buttonText, Action<string> onSubmit)
		{
			args = new InputPopUpArgs
			{
				Title = title,
				Message = message,
				Placeholder = placeholder,
				ButtonText = buttonText,
				OnSubmit = onSubmit
			};

			BuildGUI();
		}

		public InputPopUp(InputPopUpArgs ipa)
		{
			args = ipa;
			BuildGUI();
		}

		private void BuildGUI()
		{
			BackgroundColor = new Color(0, 0, 0, 0.3);
			Padding = new Thickness(0, 0, 0, 0);

			input = new Entry
			{
				HorizontalOptions = LayoutOptions.CenterAndExpand,
				Placeholder = args.Placeholder
			};

			titleLabel = new Label
			{
				HorizontalOptions = LayoutOptions.CenterAndExpand,
				Text = args.Title
			};

			msgLabel = new Label
			{
				HorizontalOptions = LayoutOptions.CenterAndExpand,
				Text = args.Message
			};

			submitButton = new Button
			{
				HorizontalOptions = LayoutOptions.CenterAndExpand,
				Text = args.ButtonText
			};
			submitButton.Clicked += (sender, e) => Submit(args.OnSubmit);

			innerBox = new StackLayout
			{
				HorizontalOptions = LayoutOptions.CenterAndExpand,
				VerticalOptions = LayoutOptions.CenterAndExpand,
				BackgroundColor = Color.White,
				Padding = new Thickness(15, 15),
				Children = {
					titleLabel,
					msgLabel,
					input,
					submitButton
				}
			};

			Content = new StackLayout
			{
				HorizontalOptions = LayoutOptions.FillAndExpand,
				VerticalOptions = LayoutOptions.FillAndExpand,
				Children = {
					innerBox
				}
			};

		}

		private void Submit(Action<string> action)
		{
			action(input.Text);
		}
	}

	public class InputPopUpArgs
	{
		public string Title { get; set; }
		public string Message { get; set; }
		public string Placeholder { get; set; }
		public string ButtonText { get; set; }
		public Action<string> OnSubmit { get; set; }
	}
}


text:
namespace realm {
    class Query;
    struct SortOrder;
    class Table;
    class TableView;
}

@class RLMObjectSchema;
@class RLMProperty;
@class RLMSchema;

extern NSString * const RLMPropertiesComparisonTypeMismatchException;
extern NSString * const RLMUnsupportedTypesFoundInPropertyComparisonException;

// apply the given predicate to the passed in query, returning the updated query
void RLMUpdateQueryWithPredicate(realm::Query *query, NSPredicate *predicate, RLMSchema *schema,
                                 RLMObjectSchema *objectSchema);

// return property - throw for invalid column name
RLMProperty *RLMValidatedProperty(RLMObjectSchema *objectSchema, NSString *columnName);

// validate the array of RLMSortDescriptors and convert it to a realm::SortOrder
realm::SortOrder RLMSortOrderFromDescriptors(RLMObjectSchema *objectSchema, NSArray *descriptors);

// This macro validates predicate format with optional arguments
#define RLM_VARARG(PREDICATE_FORMAT, ARGS) \
va_start(ARGS, PREDICATE_FORMAT);          \
va_end(ARGS);                              \
if (PREDICATE_FORMAT && ![PREDICATE_FORMAT isKindOfClass:[NSString class]]) {         \
    NSString *reason = @"predicate must be an NSString with optional format va_list"; \
    [NSException exceptionWithName:RLMExceptionName reason:reason userInfo:nil];       \
}


text:
require 'cproton'
require 'optparse'

FAILED         = 0
CONNECTION_UP  = 1
AUTHENTICATING = 2

$options  = {
  :verbose => false,
  :hostname => "0.0.0.0",
  :port => "5672"
}

OptionParser.new do |opts|
  opts.banner = "Usage: mailserver [options] <server-address> [<server-port>]"

  opts.on("-v", "--verbose", :NONE,
          "Print status messages to stdout") do |f|
    $options[:verbose] = true
  end

  opts.parse!

  $options[:hostname] = ARGV[0] if ARGV.length > 0
  $options[:port] = ARGV[1] if ARGV.length > 1
end

def log(text)
  STDOUT.puts "#{Time.new}: #{text}" if $options[:verbose]
end

class MailServer
  def initialize(hostname, port, verbose)
    @hostname = hostname
    @port = port
    @verbose = verbose
    @counter = 0
    @mailboxes = {}

    @driver = nil
  end

  def setup
    @driver = Cproton::pn_driver
    @listener = Cproton::pn_listener @driver, @hostname, @port, nil
    raise "Error: could not listen on #{@hostname}:#{@port}" if @listener.nil?
  end

  def wait
    log "Driver sleep."
    Cproton::pn_driver_wait @driver, -1
    log "Driver wakeup."
  end

  def accept_connection_requests
    l = Cproton::pn_driver_listener @driver

    while !l.nil?
      log "Accepting connection."
      cxtr = Cproton::pn_listener_accept l
      Cproton::pn_connector_set_context cxtr, AUTHENTICATING
      l = Cproton::pn_driver_listener @driver
    end
  end

  def process_connections
    cxtr = Cproton::pn_driver_connector @driver

    while cxtr
      log "Process connector"

      Cproton::pn_connector_process cxtr

      state = Cproton::pn_connector_context cxtr
      case state
      when AUTHENTICATING
        log "Authenticating..."
        self.authenticate_connector cxtr

      when CONNECTION_UP
        log "Connection established..."
        self.service_connector cxtr

      else
        raise "Unknown connection state #{state}"
      end

      Cproton::pn_connector_process cxtr

      if Cproton::pn_connector_closed cxtr
        log "Closing connector."
        Cproton::pn_connector_free cxtr
      end

      cxtr = Cproton::pn_driver_connector @driver

    end
  end

  def authenticate_connector(cxtr)
    log "Authenticating..."

    sasl = Cproton::pn_connector_sasl cxtr
    state = Cproton::pn_sasl_state sasl
    while [Cproton::PN_SASL_CONF, Cproton::PN_SASL_STEP].include? state

      case state
      when Cproton::PN_SASL_CONF
        log "Authenticating-CONF..."
        Cproton::pn_sasl_mechanisms sasl, "ANONYMOUS"
        Cproton::pn_sasl_server sasl

      when Cproton::PN_SASL_STEP
        log "Authenticating-STEP..."
        mech = Cproton::pn_sasl_remote_mechanisms sasl
        if mech == "ANONYMOUS"
          Cproton::pn_sasl_done sasl, Cproton::PN_SASL_OK
        else
          Cproton::pn_sasl_done sasl, Cproton::PN_SASL_AUTH
        end
      end

      state = Cproton::pn_sasl_state sasl

    end

    case state
    when Cproton::PN_SASL_PASS
      Cproton::pn_connector_set_connection cxtr, Cproton::pn_connection
      Cproton::pn_connector_set_context cxtr, CONNECTION_UP
      log "Authentication-PASSED"

    when Cproton::PN_SASL_FAIL
      Cproton::pn_connector_set_context cxtr, FAILED
      log "Authentication-FAILED"

    else
      log "Authentication-PENDING"
    end

  end

  def service_connector(cxtr)
    log "I/O processing starting."

    conn = Cproton::pn_connector_connection cxtr
    if ((Cproton::pn_connection_state(conn) & Cproton::PN_LOCAL_UNINIT) == Cproton::PN_LOCAL_UNINIT)
      log "Connection opened."
      Cproton::pn_connection_open(conn)
    end

    ssn = Cproton::pn_session_head conn, Cproton::PN_LOCAL_UNINIT
    while ssn
      Cproton::pn_session_open ssn
      log "Session opened."
      ssn = Cproton::pn_session_next ssn, Cproton::PN_LOCAL_UNINIT
    end

    link = Cproton::pn_link_head conn, Cproton::PN_LOCAL_UNINIT
    while link
      setup_link link
      link = Cproton::pn_link_next link, Cproton::PN_LOCAL_UNINIT
    end

    delivery = Cproton::pn_work_head conn
    while delivery
      log "Process delivery #{Cproton::pn_delivery_tag delivery}"
      if Cproton::pn_delivery_readable delivery
        process_receive delivery
      elsif Cproton::pn_delivery_writable delivery
        send_message delivery
      end

      if Cproton::pn_delivery_updated delivery
        log "Remote disposition for #{Cproton::pn_delivery_tag delivery}: #{Cproton::pn_delivery_remote_state delivery}"
        Cproton::pn_delivery_settle(delivery) if Cproton::pn_delivery_remote_state delivery
      end

      delivery = Cproton::pn_work_next delivery
    end

    link = Cproton::pn_link_head conn, Cproton::PN_LOCAL_ACTIVE | Cproton::PN_REMOTE_CLOSED
    while link
      Cproton::pn_link_close link
      log "Link closed."
      link = Cproton::pn_link_next link, Cproton::PN_LOCAL_ACTIVE | Cproton::PN_REMOTE_CLOSED
    end

    ssn = Cproton::pn_session_head conn, Cproton::PN_LOCAL_ACTIVE | Cproton::PN_REMOTE_CLOSED
    while ssn
      Cproton::pn_session_close ssn
      log "Session closed."
      ssn = Cproton::pn_session_next ssn, Cproton::PN_LOCAL_ACTIVE | Cproton::PN_REMOTE_CLOSED
    end

    if Cproton::pn_connection_state(conn) == (Cproton::PN_LOCAL_ACTIVE | Cproton::PN_REMOTE_CLOSED)
      log "Connection closed."
      Cproton::pn_connection_close conn
    end

  end

  def process_receive(delivery)
    link = Cproton::pn_delivery_link delivery
    mbox = Cproton::pn_link_remote_target link
    (rc, msg) = Cproton::pn_link_recv link, 1024

    log "Message received #{rc}"

    while rc >= 0
      unless @mailboxes.include? mbox
        log "Error: cannot send to mailbox #{mbox} - dropping message."
      else
        @mailboxes[mbox] << msg
        log "Mailbox #{mbox} contains: #{@mailboxes[mbox].size}"
      end

      (rc, msg) = Cproton::pn_link_recv link, 1024
    end

    log "Messages accepted."

    Cproton::pn_delivery_update delivery, Cproton::PN_ACCEPTED
    Cproton::pn_delivery_settle delivery
    Cproton::pn_link_advance link

    Cproton::pn_link_flow(link, 1) if Cproton::pn_link_credit(link).zero?
  end

  def send_message(delivery)
    link = Cproton::pn_delivery_link delivery
    mbox = Cproton::pn_link_remote_source link
    log "Request for Mailbox=#{mbox}"

    if @mailboxes.include?(mbox) && !@mailboxes[mbox].empty?
      msg = @mailboxes[mbox].first
      @mailboxes[mbox].delete_at 0
      log "Fetching message #{msg}"
    else
      log "Warning: mailbox #{mbox} is empty, sending empty message"
      msg = ""
    end

    sent = Cproton::pn_link_send link, msg
    log "Message sent: #{sent}"

    if Cproton::pn_link_advance link
      Cproton::pn_delivery link, "server-delivery-#{@counter}"
      @counter += 1
    end
  end

  def setup_link(link)
    r_tgt = Cproton::pn_link_remote_target link
    r_src = Cproton::pn_link_remote_source link

    if Cproton::pn_link_is_sender link
      log "Opening link to read from mailbox: #{r_src}"

      unless @mailboxes.include? r_src
        log "Error: mailbox #{r_src} does not exist!"
        r_src = nil
      end
    else
      log "Opening link to write to mailbox: #{r_tgt}"

      @mailboxes[r_tgt] = [] unless @mailboxes.include? r_tgt
    end

    Cproton::pn_link_set_target link, r_tgt
    Cproton::pn_link_set_source link, r_src

    if Cproton::pn_link_is_sender link
      Cproton::pn_delivery link, "server-delivery-#{@counter}"
      @counter += 1
    else
      Cproton::pn_link_flow link, 1
    end

    Cproton::pn_link_open link

  end

end

#------------------
# Begin entry point
#------------------

if __FILE__ == $PROGRAM_NAME
  server = MailServer.new($options[:hostname],
                          $options[:port],
                          $options[:verbose])

  server.setup
  loop do
    server.wait
    server.accept_connection_requests
    server.process_connections
  end
end


text:
package org.eclipse.ceylon.compiler.java.test.structure.ee;

import org.eclipse.ceylon.compiler.java.test.CompilerTests;
import org.junit.Test;

public class EeTests extends CompilerTests {

    @Test
    public void testNoFinalMethods() {
        compareWithJavaSource("NoFinalMethods");
    }

    @Test
    public void testPublicImplicitCtor() {
        compareWithJavaSource("PublicImplicitCtor");
    }

    @Test
    public void testUncheckedLate() {
        compareWithJavaSource("UncheckedLate");
    }

    @Test
    public void testJavaBoxes() {
        compareWithJavaSource("JavaBoxes");
    }

    @Test
    public void testJavaCollectionBoxes() {
        compareWithJavaSource("JavaCollectionBoxes");
    }

    @Test
    public void testEeModeEnabling() {
        compareWithJavaSource("enabledModule/Class");
        compareWithJavaSource("enabledModuleMaven/Class");
        compareWithJavaSource("enabledPackage/Class.src",
                "enabledPackage/Class.ceylon",
                "enabledPackage/package.ceylon");
        compareWithJavaSource("enabledClass/enabledClass");
    }

    @Test
    public void testEntityExample() {
        // don't want no stinkin' warnings about late and things not being properly initialized
        compilesWithoutWarnings("EntityExample.ceylon");
        compareWithJavaSource("EntityExample");
    }
}


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

<title>MainGUIController</title>
<meta name="date" content="2015-04-17">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

application

Class MainGUIController

java.lang.Object

application.MainGUIController

public class MainGUIController
extends java.lang.Object

The GUI controller for the main window.
 Controls all the buttons and menus etc

Author:

Sam Dark

Field Summary

Fields

Modifier and Type
Field and Description

private javafx.scene.control.Button
configCreateButton

private javafx.collections.ObservableList<java.lang.String>
configs

The list of possible configs that can be loaded (for the drop down box)

private javafx.scene.control.ChoiceBox
configSelect

private MainApp
mainApp

The main application, used to minimise it when the simulation or config window is opened

private MainSimulation
mainSim

The simulation running the physics (not config simulation or config window)

private javafx.scene.control.Button
runButton

Constructor Summary

Constructors

Constructor and Description

MainGUIController()

Initialise without a simulation or application

MainGUIController(MainApp inpApp,
                 MainSimulation inpSim)

Initialise with a simulation and application

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
initConfigFilesList()

Initialises the list of configs by getting all the config filenames in the config folder

private void
initialize()

void
setMainApp(MainApp inpApp)

Sets the application that is minimised when another window is opened

void
setMainSim(MainSimulation inpSim)

Sets the simulation used to run the physics (not config creator) with

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

runButton

private javafx.scene.control.Button runButton

configSelect

private javafx.scene.control.ChoiceBox configSelect

configCreateButton

private javafx.scene.control.Button configCreateButton

mainApp

private MainApp mainApp

The main application, used to minimise it when the simulation or config window is opened

mainSim

private MainSimulation mainSim

The simulation running the physics (not config simulation or config window)

configs

private javafx.collections.ObservableList<java.lang.String> configs

The list of possible configs that can be loaded (for the drop down box)

Constructor Detail

MainGUIController

public MainGUIController()

Initialise without a simulation or application

MainGUIController

public MainGUIController(MainApp inpApp,
                         MainSimulation inpSim)

Initialise with a simulation and application

Parameters:

inpApp - The input application. This is minimised when a simulation is run.

inpSim - The simulation to run the physics

Method Detail

setMainApp

public void setMainApp(MainApp inpApp)

Sets the application that is minimised when another window is opened

Parameters:

inpApp - The application to set to

setMainSim

public void setMainSim(MainSimulation inpSim)

Sets the simulation used to run the physics (not config creator) with

Parameters:

inpSim - The simulation to use

initialize

private void initialize()

initConfigFilesList

public void initConfigFilesList()

Initialises the list of configs by getting all the config filenames in the config folder

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

namespace Box\Mod\Page\Api;

class AdminTest extends \BBTestCase {

    /**
     * @var \Box\Mod\Page\Api\Admin
     */
    protected $api = null;

    public function setup(): void
    {
        $this->api = new \Box\Mod\Page\Api\Admin();
    }

    public function testgetDi()
    {
        $di = new \Box_Di();
        $this->api->setDi($di);
        $getDi = $this->api->getDi();
        $this->assertEquals($di, $getDi);
    }

    public function testget_pairs()
    {
        $serviceMock = $this->getMockBuilder('\Box\Mod\Page\Service')->getMock();

        $serviceMock->expects($this->atLeastOnce())
            ->method('getPairs')
            ->will($this->returnValue(array()));

        $this->api->setService($serviceMock);
        $result = $this->api->get_pairs();
        $this->assertIsArray($result);
    }

}