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

import { Injectable } from '@angular/core';
import { CoreSitesProvider, CoreSiteSchema } from '@providers/sites';
import { CoreTextUtilsProvider } from '@providers/utils/text';
import { CoreTimeUtilsProvider } from '@providers/utils/time';
import { CoreUtilsProvider } from '@providers/utils/utils';
import { CoreAppProvider } from '@providers/app';
import { CorePushNotificationsProvider } from '@core/pushnotifications/providers/pushnotifications';

/**
 * Helper to manage logging to Moodle.
 */
@Injectable()
export class CoreCourseLogHelperProvider {

    // Variables for database.
    static ACTIVITY_LOG_TABLE = 'course_activity_log';
    protected siteSchema: CoreSiteSchema = {
        name: 'CoreCourseLogHelperProvider',
        version: 1,
        tables: [
            {
                name: CoreCourseLogHelperProvider.ACTIVITY_LOG_TABLE,
                columns: [
                    {
                        name: 'component',
                        type: 'TEXT'
                    },
                    {
                        name: 'componentid',
                        type: 'INTEGER'
                    },
                    {
                        name: 'ws',
                        type: 'TEXT'
                    },
                    {
                        name: 'data',
                        type: 'TEXT'
                    },
                    {
                        name: 'time',
                        type: 'INTEGER'
                    }
                ],
                primaryKeys: ['component', 'componentid', 'ws', 'time']
            }
        ]
    };

    constructor(protected sitesProvider: CoreSitesProvider, protected timeUtils: CoreTimeUtilsProvider,
            protected textUtils: CoreTextUtilsProvider, protected utils: CoreUtilsProvider,
            protected appProvider: CoreAppProvider, protected pushNotificationsProvider: CorePushNotificationsProvider) {
        this.sitesProvider.registerSiteSchema(this.siteSchema);
    }

    /**
     * Delete the offline saved activity logs.
     *
     * @param component Component name.
     * @param componentId Component ID.
     * @param siteId Site ID. If not defined, current site.
     * @return Promise resolved when deleted, rejected if failure.
     */
    protected deleteLogs(component: string, componentId: number, siteId?: string): Promise<any> {
        return this.sitesProvider.getSite(siteId).then((site) => {

            return site.getDb().deleteRecords(CoreCourseLogHelperProvider.ACTIVITY_LOG_TABLE,
                {component: component, componentid: componentId});
        });
    }

    /**
     * Delete a WS based log.
     *
     * @param component Component name.
     * @param componentId Component ID.
     * @param ws WS name.
     * @param siteId Site ID. If not defined, current site.
     * @return Promise resolved when deleted, rejected if failure.
     */
    protected deleteWSLogsByComponent(component: string, componentId: number, ws: string, siteId?: string): Promise<any> {
        return this.sitesProvider.getSite(siteId).then((site) => {

            return site.getDb().deleteRecords(CoreCourseLogHelperProvider.ACTIVITY_LOG_TABLE,
                {component: component, componentid: componentId, ws: ws});
        });
    }

    /**
     * Delete the offline saved activity logs using call data.
     *
     * @param ws WS name.
     * @param data Data to send to the WS.
     * @param siteId Site ID. If not defined, current site.
     * @return Promise resolved when deleted, rejected if failure.
     */
    protected deleteWSLogs(ws: string, data: any, siteId?: string): Promise<any> {
        return this.sitesProvider.getSite(siteId).then((site) => {

            return site.getDb().deleteRecords(CoreCourseLogHelperProvider.ACTIVITY_LOG_TABLE,
                {ws: ws, data: this.utils.sortAndStringify(data)});
        });
    }

    /**
     * Get all the offline saved activity logs.
     *
     * @param siteId Site ID. If not defined, current site.
     * @return Promise resolved with the list of offline logs.
     */
    protected getAllLogs(siteId?: string): Promise<any[]> {
        return this.sitesProvider.getSite(siteId).then((site) => {

            return site.getDb().getAllRecords(CoreCourseLogHelperProvider.ACTIVITY_LOG_TABLE);
        });
    }

    /**
     * Get the offline saved activity logs.
     *
     * @param component Component name.
     * @param componentId Component ID.
     * @param siteId Site ID. If not defined, current site.
     * @return Promise resolved with the list of offline logs.
     */
    protected getLogs(component: string, componentId: number, siteId?: string): Promise<any[]> {
        return this.sitesProvider.getSite(siteId).then((site) => {

            return site.getDb().getRecords(CoreCourseLogHelperProvider.ACTIVITY_LOG_TABLE,
                {component: component, componentid: componentId});
        });
    }

    /**
     * Perform log online. Data will be saved offline for syncing.
     *
     * @param ws WS name.
     * @param data Data to send to the WS.
     * @param component Component name.
     * @param componentId Component ID.
     * @param siteId Site ID. If not defined, current site.
     * @return Promise resolved when done.
     */
    log(ws: string, data: any, component: string, componentId: number, siteId?: string): Promise<any> {
        return this.sitesProvider.getSite(siteId).then((site) => {
            if (!this.appProvider.isOnline()) {
                // App is offline, store the action.
                return this.storeOffline(ws, data, component, componentId, site.getId());
            }

            return this.logOnline(ws, data, site.getId()).catch((error) => {
                if (this.utils.isWebServiceError(error)) {
                    // The WebService has thrown an error, this means that responses cannot be submitted.
                    return Promise.reject(error);
                }

                // Couldn't connect to server, store in offline.
                return this.storeOffline(ws, data, component, componentId, site.getId());
            });
        });
    }

    /**
     * Perform the log online.
     *
     * @param ws WS name.
     * @param data Data to send to the WS.
     * @param siteId Site ID. If not defined, current site.
     * @return Promise resolved when log is successfully submitted. Rejected with object containing
     *         the error message (if any) and a boolean indicating if the error was returned by WS.
     */
    protected logOnline(ws: string, data: any, siteId?: string): Promise<any> {
        return this.sitesProvider.getSite(siteId).then((site) => {
            // Clone to have an unmodified data object.
            const wsData = Object.assign({}, data);

            return site.write(ws, wsData).then((response) => {
                if (!response.status) {
                    return Promise.reject(this.utils.createFakeWSError(''));
                }

                // Remove all the logs performed.
                // TODO: Remove this lines when time is accepted in logs.
                return this.deleteWSLogs(ws, data, siteId);
            });
        });
    }

    /**
     * Perform log online. Data will be saved offline for syncing.
     * It also triggers a Firebase view_item event.
     *
     * @param ws WS name.
     * @param data Data to send to the WS.
     * @param component Component name.
     * @param componentId Component ID.
     * @param name Name of the viewed item.
     * @param category Category of the viewed item.
     * @param eventData Data to pass to the Firebase event.
     * @param siteId Site ID. If not defined, current site.
     * @return Promise resolved when done.
     */
    logSingle(ws: string, data: any, component: string, componentId: number, name?: string, category?: string, eventData?: any,
            siteId?: string): Promise<any> {
        this.pushNotificationsProvider.logViewEvent(componentId, name, category, ws, eventData, siteId);

        return this.log(ws, data, component, componentId, siteId);
    }

    /**
     * Perform log online. Data will be saved offline for syncing.
     * It also triggers a Firebase view_item_list event.
     *
     * @param ws WS name.
     * @param data Data to send to the WS.
     * @param component Component name.
     * @param componentId Component ID.
     * @param category Category of the viewed item.
     * @param eventData Data to pass to the Firebase event.
     * @param siteId Site ID. If not defined, current site.
     * @return Promise resolved when done.
     */
    logList(ws: string, data: any, component: string, componentId: number, category: string, eventData?: any, siteId?: string)
            : Promise<any> {
        this.pushNotificationsProvider.logViewListEvent(category, ws, eventData, siteId);

        return this.log(ws, data, component, componentId, siteId);
    }

    /**
     * Save activity log for offline sync.
     *
     * @param ws WS name.
     * @param data Data to send to the WS.
     * @param component Component name.
     * @param componentId Component ID.
     * @param siteId Site ID. If not defined, current site.
     * @return Resolved with the inserted rowId field.
     */
    protected storeOffline(ws: string, data: any, component: string, componentId: number, siteId?: string):
            Promise<number> {
        return this.sitesProvider.getSite(siteId).then((site) => {
            const log = {
                    ws: ws,
                    data: this.utils.sortAndStringify(data),
                    component: component,
                    componentid: componentId,
                    time: this.timeUtils.timestamp()
                };

            return site.getDb().insertRecord(CoreCourseLogHelperProvider.ACTIVITY_LOG_TABLE, log);
        });
    }

    /**
     * Sync all the offline saved activity logs.
     *
     * @param siteId Site ID. If not defined, current site.
     * @return Promise resolved when done.
     */
    syncSite(siteId?: string): Promise<any> {
        return this.sitesProvider.getSite(siteId).then((site) => {
            const siteId = site.getId();

            return this.getAllLogs(siteId).then((logs) => {
                const unique = [];

                // TODO: When time is accepted on log, do not discard same logs.
                logs.forEach((log) => {
                    // Just perform unique syncs.
                    const found = unique.find((doneLog) => {
                        return log.component == doneLog.component && log.componentid == doneLog.componentid &&
                            log.ws == doneLog.ws && log.data == doneLog.data;
                    });

                    if (!found) {
                        unique.push(log);
                    }
                });

                return this.syncLogs(unique, siteId);
            });
        });
    }

    /**
     * Sync the offline saved activity logs.
     *
     * @param component Component name.
     * @param componentId Component ID.
     * @param siteId Site ID. If not defined, current site.
     * @return Promise resolved when done.
     */
    syncIfNeeded(component: string, componentId: number, siteId?: string): Promise<any> {
        return this.sitesProvider.getSite(siteId).then((site) => {
            const siteId = site.getId();

            return this.getLogs(component, componentId, siteId).then((logs) => {
                const unique = [];

                // TODO: When time is accepted on log, do not discard same logs.
                logs.forEach((log) => {
                    // Just perform unique syncs.
                    const found = unique.find((doneLog) => {
                        return log.ws == doneLog.ws && log.data == doneLog.data;
                    });

                    if (!found) {
                        unique.push(log);
                    }
                });

                return this.syncLogs(unique, siteId);
            });
        });
    }

    /**
     * Sync and delete given logs.
     *
     * @param logs Array of log objects.
     * @param siteId Site Id.
     * @return Promise resolved when done.
     */
    protected syncLogs(logs: any[], siteId: string): Promise<any> {
        return Promise.all(logs.map((log) => {
            const data = this.textUtils.parseJSON(log.data);

            return this.logOnline(log.ws, data, siteId).catch((error) => {
                const promise = this.utils.isWebServiceError(error) ? this.deleteWSLogs(log.ws, data, siteId) : Promise.resolve();

                return promise.catch(() => {
                    // Ignore errors.
                }).then(() => {
                    // The WebService has thrown an error, this means that responses cannot be submitted.
                    return Promise.reject(error);
                });
            }).then(() => {
                return this.deleteWSLogsByComponent(log.component, log.componentid, log.ws, siteId);
            });
        }));
    }
}


text:
#include <aws/ssm/model/ResolvedTargets.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SSM
{
namespace Model
{

ResolvedTargets::ResolvedTargets() :
    m_parameterValuesHasBeenSet(false),
    m_truncated(false),
    m_truncatedHasBeenSet(false)
{
}

ResolvedTargets::ResolvedTargets(JsonView jsonValue) :
    m_parameterValuesHasBeenSet(false),
    m_truncated(false),
    m_truncatedHasBeenSet(false)
{
  *this = jsonValue;
}

ResolvedTargets& ResolvedTargets::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ParameterValues"))
  {
    Aws::Utils::Array<JsonView> parameterValuesJsonList = jsonValue.GetArray("ParameterValues");
    for(unsigned parameterValuesIndex = 0; parameterValuesIndex < parameterValuesJsonList.GetLength(); ++parameterValuesIndex)
    {
      m_parameterValues.push_back(parameterValuesJsonList[parameterValuesIndex].AsString());
    }
    m_parameterValuesHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Truncated"))
  {
    m_truncated = jsonValue.GetBool("Truncated");

    m_truncatedHasBeenSet = true;
  }

  return *this;
}

JsonValue ResolvedTargets::Jsonize() const
{
  JsonValue payload;

  if(m_parameterValuesHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> parameterValuesJsonList(m_parameterValues.size());
   for(unsigned parameterValuesIndex = 0; parameterValuesIndex < parameterValuesJsonList.GetLength(); ++parameterValuesIndex)
   {
     parameterValuesJsonList[parameterValuesIndex].AsString(m_parameterValues[parameterValuesIndex]);
   }
   payload.WithArray("ParameterValues", std::move(parameterValuesJsonList));

  }

  if(m_truncatedHasBeenSet)
  {
   payload.WithBool("Truncated", m_truncated);

  }

  return payload;
}

} // namespace Model
} // namespace SSM
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
package com.twu.biblioteca;

public class Quit implements OperationOnLibrarry {

    @Override
    public void execute()
    {
        System.exit(0);
    }
}


text:
<?php
namespace User\Domain\User\Validator\Contracts;

use Inventory\Domain\Warehouse\Validator\Contracts\WarehouseValidatorInterface;
use User\Domain\User\BaseUser;
use InvalidArgumentException;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class UserValidatorCollection implements WarehouseValidatorInterface
{

    private $validators;

    public function add(UserValidatorInterface $validator)
    {
        if (! $validator instanceof UserValidatorInterface) {
            throw new InvalidArgumentException("Header Validator is required!");
        }

        $this->validators[] = $validator;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Inventory\Domain\Warehouse\Validator\Contracts\WarehouseValidatorInterface::validate()
     */
    public function validate(BaseUser $rootEntity)
    {
        if (count($this->validators) == 0) {
            throw new InvalidArgumentException("User Validator is required! but none is given.");
        }

        foreach ($this->validators as $validator) {

            // var_dump(\get_class($validator));
            /**
             *
             * @var UserValidatorInterface $validator ;
             */
            $validator->validate($rootEntity);
        }
    }
}


text:
package cn.fuyoushuo.fqbb;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import cn.fuyoushuo.fqbb.commonlib.utils.Constants;
import cn.fuyoushuo.fqbb.domain.ext.UserLocalInterceptor;
import cn.fuyoushuo.fqbb.domain.httpservice.AlimamaHttpService;
import cn.fuyoushuo.fqbb.domain.httpservice.FqbbHttpService;
import cn.fuyoushuo.fqbb.domain.httpservice.FqbbLocalHttpService;
import cn.fuyoushuo.fqbb.domain.httpservice.JifenBaoHttpService;
import cn.fuyoushuo.fqbb.domain.httpservice.TaoBaoSearchHttpService;
import cn.fuyoushuo.fqbb.domain.httpservice.TaoBaoSuggestHttpService;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @Project CommonProject
 * @Packate com.micky.commonproj.domain.service
 *
 * @Description Retrofit 服务管理
 *
 * @Author Micky Liu
 * @Email mickyliu@126.com
 * @Date 2015-12-22 14:43
 * @Version 1.0
 */
public class ServiceManager {

    private static HashMap<String, Object> mServiceMap = new HashMap<String, Object>();

    public static Context context = MyApplication.getContext();

    /**
     *  创建Retrofit Service
     * @param t Service类型
     * @param <T>
     * @return
     */
    public static <T> T createService(Class<T> t) {
        T service = (T) mServiceMap.get(t.getName());

        if (service == null) {
            OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();

            if (Constants.DEBUG) {
                //日志处理
                HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String s) {
                       Logger.getLogger(getClass()).debug(s);
                    }
                });
                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                clientBuilder.addInterceptor(loggingInterceptor);
            }

            //缓存处理
            final File baseDir = context.getCacheDir();
            if (baseDir != null) {
                final File cacheDir = new File(baseDir, "HttpResponseCache");
                clientBuilder.cache(new Cache(cacheDir, Constants.HTTP_RESPONSE_DISK_CACHE_MAX_SIZE));
            }
            if(t.getName().equals(FqbbLocalHttpService.class.getName())){
                clientBuilder.interceptors().add(new UserLocalInterceptor());
            }
             clientBuilder.interceptors().add(new ServiceInterceptor());

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(getEndPoint(t))
                    .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(clientBuilder.build())
                    .build();

            service = retrofit.create(t);
            mServiceMap.put(t.getName(), service);
        }
        return service;
    }

    /**
     *  获取EndPoint URL
     * @param t Service类型
     * @param <T>
     * @return
     */
    public static <T> String getEndPoint(Class<T> t) {
        String endPoint = "";
        if (t.getName().equals(FqbbHttpService.class.getName())) {
            endPoint = Constants.ENDPOINT_FQBB;
        }
        else if(t.getName().equals(TaoBaoSearchHttpService.class.getName()))
        {
            endPoint = Constants.ENDPOINT_TAOBAO_SEARCH;
        }
        else if(t.getName().equals(AlimamaHttpService.class.getName()))
        {
            endPoint = Constants.ENDPOINT_ALIMAMA_SEARCH;
        }
        else if(t.getName().equals(JifenBaoHttpService.class.getName()))
        {
            endPoint = Constants.ENDPOINT_JIFENBAO_SEARCH;
        }
        else if(t.getName().equals(TaoBaoSuggestHttpService.class.getName()))
        {
            endPoint = Constants.ENDPOINT_TAOBAO_SUGGESTS;
        }
        else if(t.getName().equals(FqbbLocalHttpService.class.getName()))
        {
            endPoint = Constants.ENDPOINT_FQBB_LOCAL;
        }
        if ("".equals(endPoint)) {
            throw new IllegalArgumentException("Error: Can't get end point url. Please configure at the method " + ServiceManager.class.getSimpleName() + ".getEndPoint(T t)");
        }
        return endPoint;
    }

    /**
     * OkHttpClient的拦截器
     */
    static class ServiceInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            return response;
        }
    }
}


text:
.. _ray-job-sdk:

Python SDK Overview
^^^^^^^^^^^^^^^^^^^

The Ray Jobs Python SDK is the recommended way to submit jobs programmatically. Jump to the :ref:`API Reference <ray-job-submission-sdk-ref>`, or continue reading for a quick overview.

Setup
-----

Ray Jobs is available in versions 1.9+ and requires a full installation of Ray. You can do this by running:

.. code-block:: shell

    pip install ray[default]

See the :ref:`installation guide <installation>` for more details on installing Ray.

To run a Ray Job, we also need to be able to send HTTP requests to a Ray Cluster.
For convenience, this guide will assume that you are using a local Ray Cluster, which we can start by running:

.. code-block:: shell

    ray start --head
    # ...
    # 2022-08-10 09:54:57,664   INFO services.py:1476 -- View the Ray dashboard at http://127.0.0.1:8265
    # ...

This will create a Ray head node on our local machine that we can use for development purposes.
Note the Ray Dashboard URL that is printed when starting or connecting to a Ray Cluster; we will use this URL later to submit a Ray Job.
See :ref:`Using a Remote Cluster <jobs-remote-cluster>` for tips on port-forwarding if using a remote cluster.
For more details on production deployment scenarios, check out the guides for deploying Ray on :ref:`VMs <vm-cluster-quick-start>` and :ref:`Kubernetes <kuberay-quickstart>`.

Submitting a Ray Job
--------------------

Let's start with a sample script that can be run locally. The following script uses Ray APIs to submit a task and print its return value:

.. code-block:: python

    # script.py
    import ray

    @ray.remote
    def hello_world():
        return "hello world"

    ray.init()
    print(ray.get(hello_world.remote()))

SDK calls are made via a ``JobSubmissionClient`` object.  To initialize the client, provide the Ray cluster head node address and the port used by the Ray Dashboard (``8265`` by default). For this example, we'll use a local Ray cluster, but the same example will work for remote Ray cluster addresses.

.. code-block:: python

    from ray.job_submission import JobSubmissionClient

    # If using a remote cluster, replace 127.0.0.1 with the head node's IP address.
    client = JobSubmissionClient("http://127.0.0.1:8265")
    job_id = client.submit_job(
        # Entrypoint shell command to execute
        entrypoint="python script.py",
        # Path to the local directory that contains the script.py file
        runtime_env={"working_dir": "./"}
    )
    print(job_id)

.. tip::

    By default, the Ray job server will generate a new ``job_id`` and return it, but you can alternatively choose a unique ``job_id`` string first and pass it into :code:`submit_job`.
    In this case, the Job will be executed with your given id, and will throw an error if the same ``job_id`` is submitted more than once for the same Ray cluster.

Because job submission is asynchronous, the above call will return immediately with output like the following:

.. code-block:: bash

    raysubmit_g8tDzJ6GqrCy7pd6

Now we can write a simple polling loop that checks the job status until it reaches a terminal state (namely, ``JobStatus.SUCCEEDED``, ``JobStatus.STOPPED``, or ``JobStatus.FAILED``).
We can also get the output of the job by calling ``client.get_job_logs``.

.. code-block:: python

    from ray.job_submission import JobSubmissionClient, JobStatus
    import time

    # If using a remote cluster, replace 127.0.0.1 with the head node's IP address.
    client = JobSubmissionClient("http://127.0.0.1:8265")
    job_id = client.submit_job(
        # Entrypoint shell command to execute
        entrypoint="python script.py",
        # Path to the local directory that contains the script.py file
        runtime_env={"working_dir": "./"}
    )
    print(job_id)

    def wait_until_status(job_id, status_to_wait_for, timeout_seconds=5):
        start = time.time()
        while time.time() - start <= timeout_seconds:
            status = client.get_job_status(job_id)
            print(f"status: {status}")
            if status in status_to_wait_for:
                break
            time.sleep(1)

    wait_until_status(job_id, {JobStatus.SUCCEEDED, JobStatus.STOPPED, JobStatus.FAILED})
    logs = client.get_job_logs(job_id)
    print(logs)

The output should look something like this:

.. code-block:: bash

    raysubmit_pBwfn5jqRE1E7Wmc
    status: PENDING
    status: PENDING
    status: RUNNING
    status: RUNNING
    status: RUNNING
    2022-08-22 15:05:55,652 INFO worker.py:1203 -- Using address 127.0.0.1:6379 set in the environment variable RAY_ADDRESS
    2022-08-22 15:05:55,652 INFO worker.py:1312 -- Connecting to existing Ray cluster at address: 127.0.0.1:6379...
    2022-08-22 15:05:55,660 INFO worker.py:1487 -- Connected to Ray cluster. View the dashboard at http://127.0.0.1:8265.
    hello world

Interacting with Long-running Jobs
----------------------------------

In addition to getting the current status and output of a job, a submitted job can also be stopped by the user before it finishes executing.

.. code-block:: python

    job_id = client.submit_job(
        # Entrypoint shell command to execute
        entrypoint="python -c 'import time; print(\"Sleeping...\"); time.sleep(60)'"
    )
    wait_until_status(job_id, {JobStatus.RUNNING})
    print(f'Stopping job {job_id}')
    client.stop_job(job_id)
    wait_until_status(job_id, {JobStatus.SUCCEEDED, JobStatus.STOPPED, JobStatus.FAILED})
    logs = client.get_job_logs(job_id)
    print(logs)

The output should look something like the following:

.. code-block:: bash

    status: PENDING
    status: PENDING
    status: RUNNING
    Stopping job raysubmit_VYCZZ2BQb4tfeCjq
    status: STOPPED
    Sleeping...

To get information about all jobs, call ``client.list_jobs()``.  This returns a ``Dict[str, JobInfo]`` object mapping Job IDs to their information.

Job information (status and associated metadata) is stored on the cluster indefinitely.
To delete this information, you may call ``client.delete_job(job_id)`` for any job that is already in a terminal state.
See the :ref:`SDK API Reference <ray-job-submission-sdk-ref>` for more details.

Dependency Management
---------------------

Similar to the :ref:`Jobs CLI <jobs-quickstart>`, we can also package our application's dependencies by using a Ray :ref:`runtime environment <runtime-environments>`.
Using the Python SDK, the syntax looks something like this:

.. code-block:: python

    job_id = client.submit_job(
        # Entrypoint shell command to execute
        entrypoint="python script.py",
        # Runtime environment for the job, specifying a working directory and pip package
        runtime_env={
            "working_dir": "./",
            "pip": ["requests==2.26.0"]
        }
    )

.. tip::

    Instead of a local directory (``"./"`` in this example), you can also specify remote URIs for your job's working directory, such as S3 buckets or Git repositories. See :ref:`remote-uris` for details.

For full details, see the :ref:`API Reference <ray-job-submission-sdk-ref>`.

Specifying CPU and GPU resources
--------------------------------

We recommend doing heavy computation within Ray tasks, actors, or Ray libraries, not directly in the top level of your entrypoint script.
No extra configuration is needed to do this.

However, if you need to do computation directly in the entrypoint script and would like to reserve CPU and GPU resources for the entrypoint script, you may specify the ``entrypoint_num_cpus``, ``entrypoint_num_gpus`` and ``entrypoint_resources`` arguments to ``submit_job``.  These arguments function
identically to the ``num_cpus``, ``num_gpus``, and ``resources`` arguments to ``@ray.remote()`` decorator for tasks and actors as described in :ref:`resource-requirements`.

.. code-block:: python

    job_id = client.submit_job(
        entrypoint="python script.py",
        runtime_env={
            "working_dir": "./",
        }
        # Reserve 1 GPU for the entrypoint script
        entrypoint_num_gpus=1
    )

The same arguments are also available as options ``--entrypoint-num-cpus``, ``--entrypoint-num-gpus``, and ``--entrypoint-resources`` to ``ray job submit`` in the Jobs CLI; see :ref:`Ray Job Submission CLI Reference <ray-job-submission-cli-ref>`.

If ``num_gpus`` is not specified, GPUs will still be available to the entrypoint script, but Ray will not provide isolation in terms of visible devices.
To be precise, the environment variable ``CUDA_VISIBLE_DEVICES`` will not be set in the entrypoint script; it will only be set inside tasks and actors that have `num_gpus` specified in their ``@ray.remote()`` decorator.

.. note::

    Resources specified by ``entrypoint_num_cpus``, ``entrypoint_num_gpus``, and ``entrypoint_resources`` are separate from any resources specified
    for tasks and actors within the job.

    For example, if you specify ``entrypoint_num_gpus=1``, then the entrypoint script will be scheduled on a node with at least 1 GPU,
    but if your script also contains a Ray task defined with ``@ray.remote(num_gpus=1)``, then the task will be scheduled to use a different GPU (on the same node if the node has at least 2 GPUs, or on a different node otherwise).

.. note::

    As with the ``num_cpus``, ``num_gpus``, and ``resources`` arguments to ``@ray.remote()`` described in :ref:`resource-requirements`, these arguments only refer to logical resources used for scheduling purposes. The actual CPU and GPU utilization is not controlled or limited by Ray.

.. note::

    By default, 0 CPUs and 0 GPUs are reserved for the entrypoint script.


text:
SRCDIR=src/main/c

all: clean native java

java:
	mvn package

mktargetdir:
	mkdir target

native: mktargetdir
	g++ -g -I$(SRCDIR) -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/linux -shared -fPIC $(SRCDIR)/assembler.cpp -o target/libAbra.so

standalone:
	g++ -g -I$(SRCDIR) -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/linux $(SRCDIR)/assembler.cpp -o abra

clean:
	rm -rf target
	mvn clean

# TODO: Parameterize version
javah: java
	javah -classpath target/abra-0.53-SNAPSHOT.jar abra.NativeAssembler


text:
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

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

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

<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>
  <groupId>org.apache.maven.plugin.projectinfo.tests</groupId>
  <artifactId>issue-management</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>issue management project info</name>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <issueManagement>
    <system>jira</system>
    <url>http://localhost/jira</url>
  </issueManagement>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-project-info-reports-plugin</artifactId>
        <configuration>
          <outputDirectory>target/test-harness/issue-management</outputDirectory>
          <localRepository>${localRepository}</localRepository>
          <project implementation="org.apache.maven.report.projectinfo.stubs.IssueManagementStub"/>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
{-# LANGUAGE FlexibleContexts  #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections     #-}
{-# LANGUAGE ViewPatterns      #-}

-- | Compile FFI definitions.

module Fay.Compiler.FFI
  (emitFayToJs
  ,emitJsToFay
  ,compileFFIExp
  ,jsToFayHash
  ,fayToJsHash
  ,typeArity
  ) where

import           Fay.Compiler.Prelude

import           Fay.Compiler.Misc
import           Fay.Compiler.Print                     (printJSString)
import           Fay.Compiler.QName
import           Fay.Exts.NoAnnotation                  (unAnn)
import qualified Fay.Exts.NoAnnotation                  as N
import qualified Fay.Exts.Scoped                        as S
import           Fay.Types

import           Control.Monad.Except
import           Control.Monad.Writer
import           Data.Generics.Schemes
import           Language.ECMAScript3.Parser            as JS
import           Language.ECMAScript3.Syntax
import           Language.Haskell.Exts.Annotated        (SrcSpanInfo, prettyPrint)
import           Language.Haskell.Exts.Annotated.Syntax

-- | Compile an FFI expression (also used when compiling top level definitions).
compileFFIExp :: SrcSpanInfo -> Maybe (Name a) -> String -> S.Type -> Compile JsExp
compileFFIExp loc (fmap unAnn -> nameopt) formatstr sig' =
  -- substitute newtypes with their child types before calling
  -- real compileFFI
  compileFFI' . unAnn =<< rmNewtys sig'
  where
    rmNewtys :: S.Type -> Compile N.Type
    rmNewtys typ = case typ of
      TyForall _ b c t  -> TyForall () (fmap (map unAnn) b) (fmap unAnn c) <$> rmNewtys t
      TyFun _ t1 t2     -> TyFun () <$> rmNewtys t1 <*> rmNewtys t2
      TyTuple _ b tl    -> TyTuple () b <$> mapM rmNewtys tl
      TyList _ t        -> TyList () <$> rmNewtys t
      TyApp _ t1 t2     -> TyApp () <$> rmNewtys t1 <*> rmNewtys t2
      t@TyVar{}         -> return $ unAnn t
      TyCon _ qname     -> maybe (TyCon () (unAnn qname)) snd <$> lookupNewtypeConst qname
      TyParen _ t       -> TyParen () <$> rmNewtys t
      TyInfix _ t1 q t2 -> flip (TyInfix ()) (unAnn q) <$> rmNewtys t1 <*> rmNewtys t2
      TyKind _ t k      -> flip (TyKind ()) (unAnn k) <$> rmNewtys t
      TyPromoted {}     -> return $ unAnn typ
      TyParArray _ t    -> TyParArray () <$> rmNewtys t
      TyEquals _ t1 t2  -> TyEquals () <$> rmNewtys t1 <*> rmNewtys t2
      TySplice {}       -> return $ unAnn typ
      TyBang _ bt t     -> TyBang () (unAnn bt) <$> rmNewtys t
    compileFFI' :: N.Type -> Compile JsExp
    compileFFI' sig = do
      let name = fromMaybe "<exp>" nameopt
      inner <- formatFFI loc formatstr (zip params funcFundamentalTypes)
      case JS.parse JS.expression (prettyPrint name) (printJSString (wrapReturn inner)) of
        Left err -> throwError (FfiFormatInvalidJavaScript loc inner (show err))
        Right exp  -> do
          config' <- config id
          when (configGClosure config') $ warnDotUses loc inner exp
          return (body inner)
      where
        body inner = foldr wrapParam (wrapReturn inner) params
        wrapParam pname inner = JsFun Nothing [pname] [] (Just inner)
        params = zipWith const uniqueNames [1..typeArity sig]
        wrapReturn :: String -> JsExp
        wrapReturn inner = thunk $
          case lastMay funcFundamentalTypes of
            -- Returns a "pure" value;
            Just{} -> jsToFay SerializeAnywhere returnType (JsRawExp inner)
            -- Base case:
            Nothing -> JsRawExp inner
        funcFundamentalTypes = functionTypeArgs sig
        returnType = last funcFundamentalTypes

-- | Warn about uses of naked x.y which will not play nicely with Google Closure.
warnDotUses :: SrcSpanInfo -> String -> Expression SourcePos -> Compile ()
warnDotUses srcSpanInfo string expr =
  when anyrefs $
    warn $ printSrcSpanInfo srcSpanInfo ++ ":\nDot ref syntax used in FFI JS code: " ++ string

  where
    anyrefs = not (null (listify dotref expr)) ||
                  not (null (listify ldot expr))

    dotref :: Expression SourcePos -> Bool
    dotref x = case x of
      DotRef _ (VarRef _ (Id _ name)) _
         | name `elem` globalNames -> False
      DotRef{}                     -> True
      _                            -> False

    ldot :: LValue SourcePos -> Bool
    ldot x =
      case x of
        LDot _ (VarRef _ (Id _ name)) _
         | name `elem` globalNames -> False
        LDot{}                     -> True
        _                          -> False

    globalNames = ["Math","console","JSON"]

-- | Make a Fay→JS encoder.
emitFayToJs :: Name a -> [TyVarBind b] -> [([Name c], Type d)] -> Compile ()
emitFayToJs (unAnn -> name) (map unAnn -> tyvars) (explodeFields -> fieldTypes) = do
  qname <- qualify name
  let ctrName = printJSString $ unQual qname
  tell $ mempty { writerFayToJs = [(ctrName, translator)] }

  where
    translator =
      JsFun Nothing
            [JsNameVar "type", argTypes, transcodingObjForced]
            (obj : fieldStmts (map (getIndex name tyvars) fieldTypes))
            (Just $ JsName obj_)

    obj :: JsStmt
    obj = JsVar obj_ $
      JsObj [("instance",JsLit (JsStr (printJSString (unAnn name))))]

    fieldStmts :: [(Int,(N.Name,N.Type))] -> [JsStmt]
    fieldStmts [] = []
    fieldStmts ((i,fieldType):fts) =
      JsVar obj_v field :
        JsIf (JsNeq JsUndefined (JsName obj_v))
          [JsSetPropExtern obj_ decl (JsName obj_v)]
          [] :
        fieldStmts fts
      where
        obj_v = JsNameVar $ UnQual () (Ident () $ "obj_" ++ d)
        decl = JsNameVar $ UnQual () (Ident () d)
        (d, field) = declField i fieldType

    obj_ = JsNameVar "obj_"

    -- Declare/encode Fay→JS field
    declField :: Int -> (N.Name,N.Type) -> (String,JsExp)
    declField i (fname,typ) =
      (prettyPrint fname
      ,fayToJs (SerializeUserArg i)
               (argType typ)
               (JsGetProp (JsName transcodingObjForced)
                          (JsNameVar (UnQual () fname))))

-- | A name used for transcoding.
transcodingObj :: JsName
transcodingObj = JsNameVar "obj"

-- | The name used for the forced version of a transcoding variable.
transcodingObjForced :: JsName
transcodingObjForced = JsNameVar "_obj"

-- | Get arg types of a function type.
functionTypeArgs :: N.Type -> [FundamentalType]
functionTypeArgs t = case t of
  TyForall _ _ _ i -> functionTypeArgs i
  TyFun _ a b      -> argType a : functionTypeArgs b
  TyParen _ st     -> functionTypeArgs st
  r                -> [argType r]

-- | Convert a Haskell type to an internal FFI representation.
argType :: N.Type -> FundamentalType
argType t = case t of
  TyCon _ (UnQual _ (Ident _ "String"))                -> StringType
  TyCon _ (UnQual _ (Ident _ "Double"))                -> DoubleType
  TyCon _ (UnQual _ (Ident _ "Int"))                   -> IntType
  TyCon _ (UnQual _ (Ident _ "Bool"))                  -> BoolType
  TyApp _ (TyCon _ (UnQual _ (Ident _ "Ptr"))) _       -> PtrType
  TyApp _ (TyCon _ (UnQual _ (Ident _ "Automatic"))) _ -> Automatic
  TyApp _ (TyCon _ (UnQual _ (Ident _ "Defined"))) a   -> Defined (argType a)
  TyApp _ (TyCon _ (UnQual _ (Ident _ "Nullable"))) a  -> Nullable (argType a)
  TyApp _ (TyCon _ (UnQual _ (Ident _ "Fay"))) a       -> JsType (argType a)
  TyFun _ x xs                  -> FunctionType (argType x : functionTypeArgs xs)
  TyList _ x                    -> ListType (argType x)
  TyTuple _ _ xs                -> TupleType (map argType xs)
  TyParen _ st                  -> argType st
  TyApp _ op arg                -> userDefined (reverse (arg : expandApp op))
  _                     ->
    -- No semantic point to this, merely to avoid GHC's broken
    -- warning.
    case t of
      TyCon _ (UnQual _ user)   -> UserDefined user []
      _ -> UnknownType

-- | Expand a type application.
expandApp :: N.Type -> [N.Type]
expandApp (TyParen _ t) = expandApp t
expandApp (TyApp _ op arg) = arg : expandApp op
expandApp x = [x]

-- | Generate a user-defined type.
userDefined :: [N.Type] -> FundamentalType
userDefined (TyCon _ (UnQual _ name):typs) = UserDefined name (map argType typs)
userDefined _ = UnknownType

-- | Translate: JS → Fay.
jsToFay :: SerializeContext -> FundamentalType -> JsExp -> JsExp
jsToFay = translate "jsToFay"
-- | Translate: Fay → JS.
fayToJs :: SerializeContext -> FundamentalType -> JsExp -> JsExp
fayToJs = translate "fayToJs"

-- | Make a translator.
translate :: String -> SerializeContext -> FundamentalType -> JsExp -> JsExp
translate method context typ exp = case typ of
  -- Unserialized types
  PtrType     -> exp
  -- Flat types
  StringType -> flat "string"
  DoubleType -> flat "double"
  IntType    -> flat "int"
  BoolType   -> flat "bool"
  -- Collapse monad
  JsType x | method == "jsToFay" -> js x
  -- Otherwise recursive stuff needs the big guns
  _ -> recursive

  where flat specialize =
          JsApp (JsName (JsBuiltIn (Ident () (method ++ "_" ++ specialize))))
                [exp]
        recursive =
          JsApp (JsName (JsBuiltIn (Ident () method)))
                [typeRep context typ
                ,exp]
        js ty' =
          JsNew (JsBuiltIn "Monad")
                [translate method context ty' exp]

-- | Get a JS-representation of a fundamental type for encoding/decoding.
typeRep :: SerializeContext -> FundamentalType -> JsExp
typeRep context typ = case typ of
  FunctionType xs     -> JsList [JsLit $ JsStr "function",JsList (map (typeRep context) xs)]
  JsType x            -> JsList [JsLit $ JsStr "action",JsList [typeRep context x]]
  ListType x          -> JsList [JsLit $ JsStr "list",JsList [typeRep context x]]
  TupleType xs        -> JsList [JsLit $ JsStr "tuple",JsList (map (typeRep context) xs)]
  UserDefined name xs -> JsList [JsLit $ JsStr "user"
                                ,JsLit $ JsStr (unname name)
                                ,JsList (zipWith (\t i -> typeRep (setArg i context) t) xs [0..])]
  Defined x           -> JsList [JsLit $ JsStr "defined",JsList [typeRep context x]]
  Nullable x          -> JsList [JsLit $ JsStr "nullable",JsList [typeRep context x]]
  _ -> nom

  where
    setArg i SerializeUserArg{}   = SerializeUserArg i
    setArg _ c = c
    ret = JsList . return . JsLit . JsStr
    nom = case typ of
      StringType -> ret "string"
      DoubleType -> ret "double"
      PtrType    -> ret "ptr"
      Automatic  -> ret "automatic"
      IntType    -> ret "int"
      BoolType   -> ret "bool"
      DateType   -> ret "date"
      _          ->
        case context of
          SerializeAnywhere -> ret "unknown"
          SerializeUserArg i ->
            let args = JsName argTypes
                automatic = JsIndex 0 (JsName JsParametrizedType)
                thisArg = JsIndex i args
            in JsTernaryIf (JsInfix "&&" args thisArg)
                           thisArg
                           (JsTernaryIf (JsEq automatic (JsLit "automatic"))
                                        (ret "automatic")
                                        (ret "unknown"))

-- | Get the arity of a type.
typeArity :: Type a -> Int
typeArity t = case t of
  TyForall _ _ _ i -> typeArity i
  TyFun _ _ b      -> 1 + typeArity b
  TyParen _ st     -> typeArity st
  _              -> 0

-- | Format the FFI  format string with the given arguments.
formatFFI :: SrcSpanInfo                -- ^ Source Location.
          -> String                     -- ^ The format string.
          -> [(JsName,FundamentalType)] -- ^ Arguments.
          -> Compile String             -- ^ The JS code.
formatFFI loc formatstr args = go formatstr where
  go ('%':'*':xs) = do
    these <- mapM inject (zipWith const [1..] args)
    rest <- go xs
    return (intercalate "," these ++ rest)
  go ('%':'%':xs) = do
    rest <- go xs
    return ('%' : rest)
  go ['%'] = throwError (FfiFormatIncompleteArg loc)
  go ('%':(span isDigit -> (op,xs))) =
    case readMay op of
     Nothing -> throwError (FfiFormatBadChars loc op)
     Just n -> do
       this <- inject n
       rest <- go xs
       return (this ++ rest)
  go (x:xs) = do rest <- go xs
                 return (x : rest)
  go [] = return []

  inject n =
    case listToMaybe (drop (n-1) args) of
      Nothing -> throwError (FfiFormatNoSuchArg loc n)
      Just (arg,typ) ->
        return (printJSString (fayToJs SerializeAnywhere typ (JsName arg)))

-- | Generate n name-typ pairs from the given list.
explodeFields :: [([a], t)] -> [(a, t)]
explodeFields = concatMap $ \(names,typ) -> map (,typ) names

-- | Generate Fay→JS encoding.
fayToJsHash :: [(String, JsExp)] -> [JsStmt]
fayToJsHash cases = [JsExpStmt $ JsApp (JsName $ JsBuiltIn "objConcat") [JsName $ JsBuiltIn "fayToJsHash", JsObj cases]]

-- | Generate JS→Fay decoding.
jsToFayHash :: [(String, JsExp)] -> [JsStmt]
jsToFayHash cases = [JsExpStmt $ JsApp (JsName $ JsBuiltIn "objConcat") [JsName $ JsBuiltIn "jsToFayHash", JsObj cases]]

-- | Make a JS→Fay decoder.
emitJsToFay :: Name a -> [TyVarBind b] -> [([Name c],Type d)] -> Compile ()
emitJsToFay (unAnn -> name) (map unAnn -> tyvars) (map (unAnn *** unAnn) . explodeFields -> fieldTypes) = do
  qname <- qualify name
  tell (mempty { writerJsToFay = [(printJSString (unAnn name), translator qname)] })

  where
    translator qname =
      JsFun Nothing [JsNameVar "type", argTypes, transcodingObj] []
            (Just $ JsNew (JsConstructor qname)
                          (map (decodeField . getIndex name tyvars) fieldTypes))
    -- Decode JS→Fay field
    decodeField :: (Int,(N.Name,N.Type)) -> JsExp
    decodeField (i,(fname,typ)) =
      jsToFay (SerializeUserArg i)
              (argType typ)
              (JsGetPropExtern (JsName transcodingObj)
                               (prettyPrint fname))

-- | The argument types used in serialization of parametrized user-defined types.
argTypes :: JsName
argTypes = JsNameVar "argTypes"

-- | Get the index of a name from the set of type variables bindings.
getIndex :: Name a -> [TyVarBind b] -> (Name c,Type d) -> (Int,(N.Name,N.Type))
getIndex (unAnn -> name) (map unAnn -> tyvars) (unAnn -> sname,unAnn -> ty) =
  case ty of
    TyVar _ tyname -> case elemIndex tyname (map tyvar tyvars) of
      Nothing -> error $ "unknown type variable " ++ prettyPrint tyname ++
                         " for " ++ prettyPrint name ++ "." ++ prettyPrint sname ++ "," ++
                         " vars were: " ++ unwords (map prettyPrint tyvars) ++ ", rest: " ++ show tyvars
      Just i -> (i,(sname,ty))
    _ -> (0,(sname,ty))

-- | Extract the name from a possibly-kinded tyvar.
tyvar :: N.TyVarBind -> N.Name
tyvar (UnkindedVar _ v) = v
tyvar (KindedVar _ v _) = v


text:
$(function() {
	if(get_menu_param("id")) {
		// 编辑状态
		$.getJSON(
			"ajax_book_get?id=" + get_menu_param("id") + "&random=" + Math.random(),
			function(data) {
				$("#title").html("修改数据");
				$("#bookTitle").val(data.data.book_title);
				$("#bookAuthor").val(data.data.book_author);
//				$("#bookVideo").val(data.data.book_video);
				$("#bookPicture").val(data.data.book_picture);
				$('#bookPicture').ckeditor();
				$("#bookContent").val(data.data.book_content);
				$('#bookContent').ckeditor();
				$("#btn_submit").val("更新");
			}
		);
	}
	else
	{
		$('#bookPicture').ckeditor();
		$('#bookContent').ckeditor();
	}

	$("#btn_submit").click(function() {

		var bookTitle = $("#bookTitle").val();
		var bookAuthor = $("#bookAuthor").val();
//		var bookVideo = $("#bookVideo").val();
		var bookPicture = $("#bookPicture").val();
		var bookContent = $("#bookContent").val();

		var msg = "";
		if(bookTitle == "")
			msg += "标题不能为空\n";
		if(bookAuthor == "")
			msg += "作者不能为空\n";
		if(msg != "")
			alert(msg);
		else {

			var type = get_menu_param("type");

			var obj = null;
			if(get_menu_param("id")) {
				var id = get_menu_param("id");
				// 添加数据
				obj = { id: id, bookTitle:bookTitle, bookAuthor:bookAuthor, bookPicture: bookPicture, bookContent:bookContent, type: type, random: Math.random() };
			}
			else
			{
				// 更新数据
				obj = { bookTitle:bookTitle, bookAuthor:bookAuthor, bookPicture: bookPicture, bookContent:bookContent, type: type, random: Math.random() };
			}

			$.post(
				"ajax_book_add",
				obj,
				function(data) {

					if(!get_menu_param("id"))
						$("#menu_param").val("type:" + get_menu_param("type"));
					else {
						var page = 1;
						if(get_menu_param("page"))
							page = get_menu_param("page");
						$("#menu_param").val("type:" + get_menu_param("type") + ",page:" + page);
					}
					$("#center-column").load("../../static/admin/admin_templates/book_recommend_list.html?random=" + Math.random());
				},
				"json"
			);
		}

	});

	$("#btn_back").click(function() {
		$("#center-column").load("../../static/admin/admin_templates/book_recommend_list.html?random=" + Math.random());
	});
});


text:
namespace gpmd
{
using namespace gpos;

//---------------------------------------------------------------------------
//	@class:
//		CMDIdScCmp
//
//	@doc:
//		Class for representing ids of scalar comparison operators
//
//---------------------------------------------------------------------------
class CMDIdScCmp : public IMDId
{
private:
	// mdid of source type
	CMDIdGPDB *m_mdid_left;

	// mdid of destinatin type
	CMDIdGPDB *m_mdid_right;

	// comparison type
	IMDType::ECmpType m_comparision_type;

	// buffer for the serialized mdid
	WCHAR m_mdid_array[GPDXL_MDID_LENGTH];

	// string representation of the mdid
	CWStringStatic m_str;

	// private copy ctor
	CMDIdScCmp(const CMDIdScCmp &);

	// serialize mdid
	void Serialize();

public:
	// ctor
	CMDIdScCmp(CMDIdGPDB *left_mdid, CMDIdGPDB *right_mdid,
			   IMDType::ECmpType cmp_type);

	// dtor
	virtual ~CMDIdScCmp();

	virtual EMDIdType
	MdidType() const
	{
		return EmdidScCmp;
	}

	// string representation of mdid
	virtual const WCHAR *GetBuffer() const;

	// source system id
	virtual CSystemId
	Sysid() const
	{
		return m_mdid_left->Sysid();
	}

	// left type id
	IMDId *GetLeftMdid() const;

	// right type id
	IMDId *GetRightMdid() const;

	IMDType::ECmpType
	ParseCmpType() const
	{
		return m_comparision_type;
	}

	// equality check
	virtual BOOL Equals(const IMDId *mdid) const;

	// computes the hash value for the metadata id
	virtual ULONG HashValue() const;

	// is the mdid valid
	virtual BOOL
	IsValid() const
	{
		return IMDId::IsValid(m_mdid_left) && IMDId::IsValid(m_mdid_right) &&
			   IMDType::EcmptOther != m_comparision_type;
	}

	// serialize mdid in DXL as the value of the specified attribute
	virtual void Serialize(CXMLSerializer *xml_serializer,
						   const CWStringConst *attribute_str) const;

	// debug print of the metadata id
	virtual IOstream &OsPrint(IOstream &os) const;

	// const converter
	static const CMDIdScCmp *
	CastMdid(const IMDId *mdid)
	{
		GPOS_ASSERT(NULL != mdid && EmdidScCmp == mdid->MdidType());

		return dynamic_cast<const CMDIdScCmp *>(mdid);
	}

	// non-const converter
	static CMDIdScCmp *
	CastMdid(IMDId *mdid)
	{
		GPOS_ASSERT(NULL != mdid && EmdidScCmp == mdid->MdidType());

		return dynamic_cast<CMDIdScCmp *>(mdid);
	}
};
}  // namespace gpmd

#endif	// !GPMD_CMDIdScCmpFunc_H

// EOF


text:
describe Halo::Halo5::Metadata do
  subject(:client) { Halo.halo5 }

  before do
    Halo.configure do |config|
      config.api_key = ENV['HALO_API_KEY']
      config.region  = ENV['HALO_REGION']
      config.redis   = nil
    end
  end

  describe 'campaign_missions request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/campaign_missions') { client.metadata.campaign_missions }
    end

    it 'returns a list of all campaign missions' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'commendations request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/commendations') { client.metadata.commendations }
    end

    it 'returns a list of all commendations' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'company_commendations request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/company_commendations') { client.metadata.company_commendations }
    end

    it 'returns a list of all company_commendations' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'csr_designations request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/csr_designations') { client.metadata.csr_designations }
    end

    it 'returns a list of all csr_designations' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'enemies request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/enemies') { client.metadata.enemies }
    end

    it 'returns a list of all enemies' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'flexible_stats request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/flexible_stats') { client.metadata.flexible_stats }
    end

    it 'returns a list of all flexible_stats' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'game_base_variants request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/game_base_variants') { client.metadata.game_base_variants }
    end

    it 'returns a list of all game_base_variants' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'game_variant request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/game_variant') { client.metadata.game_variant('1571fdac-e0b4-4ebc-a73a-6e13001b71d3') }
    end

    it 'returns a game_variant' do
      expect(response).to be_kind_of(Hash)
      expect(response).to have_key 'contentId'
    end
  end

  describe 'impulses request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/impulses') { client.metadata.impulses }
    end

    it 'returns a list of all impulses' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'map_variant request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/map') { client.metadata.map_variant('c93d708f-f206-11e4-a815-24be05e24f7e') }
    end

    it 'returns a map_variant' do
      expect(response).to be_kind_of(Hash)
      expect(response).to have_key 'id'
    end
  end

  describe 'maps request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/maps') { client.metadata.maps }
    end

    it 'returns a list of all maps' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'medals request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/medals') { client.metadata.medals }
    end

    it 'returns a list of all medals' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'playlists request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/playlists') { client.metadata.playlists }
    end

    it 'returns a list of all playlists' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'requisition request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/requisition') { client.metadata.requisition('123456') }
    end

    xit 'returns a requisition' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'requisition_pack request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/requisition_pack') { client.metadata.requisition_pack('123456') }
    end

    xit 'returns a requisition pack' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'seasons request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/seasons') { client.metadata.seasons }
    end

    it 'returns a list of all seasons' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'skulls request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/skulls') { client.metadata.skulls }
    end

    it 'returns a list of all skulls' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'spartan_ranks request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/spartan_ranks') { client.metadata.spartan_ranks }
    end

    it 'returns a list of all spartan_ranks' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'team_colors request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/team_colors') { client.metadata.team_colors }
    end

    it 'returns a list of all team_colors' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'vehicles request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/vehicles') { client.metadata.vehicles }
    end

    it 'returns a list of all vehicles' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end

  describe 'weapons request' do
    let(:response) do
      VCR.use_cassette('halo5/metadata/weapons') { client.metadata.weapons }
    end

    it 'returns a list of all weapons' do
      expect(response).to be_kind_of(Array)
      expect(response.first).to have_key 'id'
    end
  end
end


text:
package org.ovirt.engine.ui.webadmin.widget.table.cell;

import org.ovirt.engine.core.common.businessentities.gluster.GlusterSnapshotStatus;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeSnapshotEntity;
import org.ovirt.engine.ui.common.widget.table.cell.AbstractCell;
import org.ovirt.engine.ui.webadmin.ApplicationResources;
import org.ovirt.engine.ui.webadmin.ApplicationTemplates;
import org.ovirt.engine.ui.webadmin.gin.AssetProvider;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.AbstractImagePrototype;

public class GlusterVolumeSnapshotStatusCell extends AbstractCell<GlusterVolumeSnapshotEntity> {

    private final static ApplicationTemplates templates = AssetProvider.getTemplates();
    private final static ApplicationResources resources = AssetProvider.getResources();

    @Override
    public void render(Context context, GlusterVolumeSnapshotEntity snapshot, SafeHtmlBuilder sb, String id) {
        // Nothing to render if no snapshot is provided:
        if (snapshot == null) {
            return;
        }

        // Find the image corresponding to the status of the brick:
        GlusterSnapshotStatus status = snapshot.getStatus();
        ImageResource statusImage = null;

        switch (status) {
        case ACTIVATED:
            statusImage = resources.upImage();
            break;
        case DEACTIVATED:
            statusImage = resources.downImage();
            break;
        case UNKNOWN:
            statusImage = resources.questionMarkImage();
            break;
        default:
            statusImage = resources.downImage();
        }

        // Generate the HTML for the image:
        SafeHtml statusImageHtml =
                SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(statusImage).getHTML());
        sb.append(templates.statusTemplate(statusImageHtml, id, status.toString()));
    }
}


text:
Get the MCPC mini-game Lucky Block Wars for your PocketMine server

The aim of this mini-game is to break Lucky Blocks and to kill your opponents.
But take care: These Lucky Blocks are full of unlucky or lucky surprises!


text:
/*
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include "libavutil/mem.h"
#include "libavutil/audio_fifo.c"

#define MAX_CHANNELS    32

typedef struct TestStruct {
    const enum AVSampleFormat format;
    const int nb_ch;
    void const *data_planes[MAX_CHANNELS];
    const int nb_samples_pch;
} TestStruct;

static const uint8_t data_U8 [] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11                        };
static const int16_t data_S16[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11                        };
static const float   data_FLT[] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0};

static const TestStruct test_struct[] = {
    {.format = AV_SAMPLE_FMT_U8   , .nb_ch = 1, .data_planes = {data_U8 ,             }, .nb_samples_pch = 12},
    {.format = AV_SAMPLE_FMT_U8P  , .nb_ch = 2, .data_planes = {data_U8 , data_U8 +6, }, .nb_samples_pch = 6 },
    {.format = AV_SAMPLE_FMT_S16  , .nb_ch = 1, .data_planes = {data_S16,             }, .nb_samples_pch = 12},
    {.format = AV_SAMPLE_FMT_S16P , .nb_ch = 2, .data_planes = {data_S16, data_S16+6, }, .nb_samples_pch = 6 },
    {.format = AV_SAMPLE_FMT_FLT  , .nb_ch = 1, .data_planes = {data_FLT,             }, .nb_samples_pch = 12},
    {.format = AV_SAMPLE_FMT_FLTP , .nb_ch = 2, .data_planes = {data_FLT, data_FLT+6, }, .nb_samples_pch = 6 }
};

static void free_data_planes(AVAudioFifo *afifo, void **output_data)
{
    int i;
    for (i = 0; i < afifo->nb_buffers; ++i){
        av_freep(&output_data[i]);
    }
    av_freep(&output_data);
}

static void ERROR(const char *str)
{
    fprintf(stderr, "%s\n", str);
    exit(1);
}

static void print_audio_bytes(const TestStruct *test_sample, void **data_planes, int nb_samples)
{
    int p, b, f;
    int byte_offset      = av_get_bytes_per_sample(test_sample->format);
    int buffers          = av_sample_fmt_is_planar(test_sample->format)
                                         ? test_sample->nb_ch : 1;
    int line_size        = (buffers > 1) ? nb_samples * byte_offset
                                         : nb_samples * byte_offset * test_sample->nb_ch;
    for (p = 0; p < buffers; ++p){
        for(b = 0; b < line_size; b+=byte_offset){
            for (f = 0; f < byte_offset; f++){
                int order = !HAVE_BIGENDIAN ? (byte_offset - f - 1) : f;
                printf("%02x", *((uint8_t*)data_planes[p] + b + order));
            }
            putchar(' ');
        }
        putchar('\n');
    }
}

static int read_samples_from_audio_fifo(AVAudioFifo* afifo, void ***output, int nb_samples)
{
    int i;
    int samples        = FFMIN(nb_samples, afifo->nb_samples);
    int tot_elements   = !av_sample_fmt_is_planar(afifo->sample_fmt)
                         ? samples : afifo->channels * samples;
    void **data_planes = av_malloc_array(afifo->nb_buffers, sizeof(void*));
    if (!data_planes)
        ERROR("failed to allocate memory!");
    if (*output)
        free_data_planes(afifo, *output);
    *output            = data_planes;

    for (i = 0; i < afifo->nb_buffers; ++i){
        data_planes[i] = av_malloc_array(tot_elements, afifo->sample_size);
        if (!data_planes[i])
            ERROR("failed to allocate memory!");
    }

    return av_audio_fifo_read(afifo, *output, nb_samples);
}

static int write_samples_to_audio_fifo(AVAudioFifo* afifo, const TestStruct *test_sample,
                                       int nb_samples, int offset)
{
    int offset_size, i;
    void *data_planes[MAX_CHANNELS];

    if(nb_samples > test_sample->nb_samples_pch - offset){
        return 0;
    }
    if(offset >= test_sample->nb_samples_pch){
        return 0;
    }
    offset_size  = offset * afifo->sample_size;

    for (i = 0; i < afifo->nb_buffers ; ++i){
        data_planes[i] = (uint8_t*)test_sample->data_planes[i] + offset_size;
    }

    return av_audio_fifo_write(afifo, data_planes, nb_samples);
}

static void test_function(const TestStruct *test_sample)
{
    int ret, i;
    void **output_data  = NULL;
    AVAudioFifo *afifo  = av_audio_fifo_alloc(test_sample->format, test_sample->nb_ch,
                                            test_sample->nb_samples_pch);
    if (!afifo) {
        ERROR("ERROR: av_audio_fifo_alloc returned NULL!");
    }
    ret = write_samples_to_audio_fifo(afifo, test_sample, test_sample->nb_samples_pch, 0);
    if (ret < 0){
        ERROR("ERROR: av_audio_fifo_write failed!");
    }
    printf("written: %d\n", ret);

    ret = write_samples_to_audio_fifo(afifo, test_sample, test_sample->nb_samples_pch, 0);
    if (ret < 0){
        ERROR("ERROR: av_audio_fifo_write failed!");
    }
    printf("written: %d\n", ret);
    printf("remaining samples in audio_fifo: %d\n\n", av_audio_fifo_size(afifo));

    ret = read_samples_from_audio_fifo(afifo, &output_data, test_sample->nb_samples_pch);
    if (ret < 0){
        ERROR("ERROR: av_audio_fifo_read failed!");
    }
    printf("read: %d\n", ret);
    print_audio_bytes(test_sample, output_data, ret);
    printf("remaining samples in audio_fifo: %d\n\n", av_audio_fifo_size(afifo));

    /* test av_audio_fifo_peek */
    ret = av_audio_fifo_peek(afifo, output_data, afifo->nb_samples);
    if (ret < 0){
        ERROR("ERROR: av_audio_fifo_peek failed!");
    }
    printf("peek:\n");
    print_audio_bytes(test_sample, output_data, ret);
    printf("\n");

    /* test av_audio_fifo_peek_at */
    printf("peek_at:\n");
    for (i = 0; i < afifo->nb_samples; ++i){
        ret = av_audio_fifo_peek_at(afifo, output_data, 1, i);
        if (ret < 0){
            ERROR("ERROR: av_audio_fifo_peek_at failed!");
        }
        printf("%d:\n", i);
        print_audio_bytes(test_sample, output_data, ret);
    }
    printf("\n");

    /* test av_audio_fifo_drain */
    ret = av_audio_fifo_drain(afifo, afifo->nb_samples);
    if (ret < 0){
        ERROR("ERROR: av_audio_fifo_drain failed!");
    }
    if (afifo->nb_samples){
        ERROR("drain failed to flush all samples in audio_fifo!");
    }

    /* deallocate */
    free_data_planes(afifo, output_data);
    av_audio_fifo_free(afifo);
}

int main(void)
{
    int t, tests = sizeof(test_struct)/sizeof(test_struct[0]);

    for (t = 0; t < tests; ++t){
        printf("\nTEST: %d\n\n", t+1);
        test_function(&test_struct[t]);
    }
    return 0;
}


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

/*
 * AN_scalar_8_16_s_inv.cpp
 *
 *  Created on: 07.01.2018
 *      Author: Till Kolditz - Till.Kolditz@gmail.com
 */

#include <AN/AN_scalar.hpp>

namespace coding_benchmark {

    template
    struct AN_scalar_8_16_s_inv<1> ;
    template
    struct AN_scalar_8_16_s_inv<2> ;
    template
    struct AN_scalar_8_16_s_inv<4> ;
    template
    struct AN_scalar_8_16_s_inv<8> ;
    template
    struct AN_scalar_8_16_s_inv<16> ;
    template
    struct AN_scalar_8_16_s_inv<32> ;
    template
    struct AN_scalar_8_16_s_inv<64> ;
    template
    struct AN_scalar_8_16_s_inv<128> ;
    template
    struct AN_scalar_8_16_s_inv<256> ;
    template
    struct AN_scalar_8_16_s_inv<512> ;
    template
    struct AN_scalar_8_16_s_inv<1024> ;

}


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.ElasticLoadBalancing.Model
{
    /// <summary>
    /// Container for the parameters to the DeregisterInstancesFromLoadBalancer operation.
    /// <para> Deregisters instances from the LoadBalancer. Once the instance is deregistered, it will stop receiving traffic from the LoadBalancer.
    /// </para> <para> In order to successfully call this API, the same account credentials as those used to create the LoadBalancer must be
    /// provided. </para>
    /// </summary>
    /// <seealso cref="Amazon.ElasticLoadBalancing.AmazonElasticLoadBalancing.DeregisterInstancesFromLoadBalancer"/>
    public class DeregisterInstancesFromLoadBalancerRequest : AmazonWebServiceRequest
    {
        private string loadBalancerName;
        private List<Instance> instances = new List<Instance>();
        /// <summary>
        /// Default constructor for a new DeregisterInstancesFromLoadBalancerRequest object.  Callers should use the
        /// properties or fluent setter (With...) methods to initialize this object after creating it.
        /// </summary>
        public DeregisterInstancesFromLoadBalancerRequest() {}

        /// <summary>
        /// Constructs a new DeregisterInstancesFromLoadBalancerRequest object.
        /// Callers should use the properties or fluent setter (With...) methods to
        /// initialize any additional object members.
        /// </summary>
        ///
        /// <param name="loadBalancerName"> The name associated with the LoadBalancer. The name must be unique within the client AWS account. </param>
        /// <param name="instances"> A list of EC2 instance IDs consisting of all instances to be deregistered. </param>
        public DeregisterInstancesFromLoadBalancerRequest(string loadBalancerName, List<Instance> instances)
        {
            this.loadBalancerName = loadBalancerName;
            this.instances = instances;
        }

        /// <summary>
        /// The name associated with the LoadBalancer. The name must be unique within the client AWS account.
        ///
        /// </summary>
        public string LoadBalancerName
        {
            get { return this.loadBalancerName; }
            set { this.loadBalancerName = value; }
        }

        /// <summary>
        /// Sets the LoadBalancerName property
        /// </summary>
        /// <param name="loadBalancerName">The value to set for the LoadBalancerName property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public DeregisterInstancesFromLoadBalancerRequest WithLoadBalancerName(string loadBalancerName)
        {
            this.loadBalancerName = loadBalancerName;
            return this;
        }

        // Check to see if LoadBalancerName property is set
        internal bool IsSetLoadBalancerName()
        {
            return this.loadBalancerName != null;
        }

        /// <summary>
        /// A list of EC2 instance IDs consisting of all instances to be deregistered.
        ///
        /// </summary>
        public List<Instance> Instances
        {
            get { return this.instances; }
            set { this.instances = value; }
        }
        /// <summary>
        /// Adds elements to the Instances collection
        /// </summary>
        /// <param name="instances">The values to add to the Instances collection </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public DeregisterInstancesFromLoadBalancerRequest WithInstances(params Instance[] instances)
        {
            foreach (Instance element in instances)
            {
                this.instances.Add(element);
            }

            return this;
        }

        /// <summary>
        /// Adds elements to the Instances collection
        /// </summary>
        /// <param name="instances">The values to add to the Instances collection </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public DeregisterInstancesFromLoadBalancerRequest WithInstances(IEnumerable<Instance> instances)
        {
            foreach (Instance element in instances)
            {
                this.instances.Add(element);
            }

            return this;
        }

        // Check to see if Instances property is set
        internal bool IsSetInstances()
        {
            return this.instances.Count > 0;
        }
    }
}


text:
from .base import Setting

class ConfigFile(Setting):
    """
    Location of the config file to use.
    """

    name = "config_file"
    cli = ["-f", "--config_file"]

class Debug(Setting):
    """
    Turn on debugging
    """

    name = "debug"
    section = "Debugging"
    cli = ["-d", "--debug"]
    action = "store_true"
    default = False


text:
/*

Darko Bunic
http://www.redips.net/
Apr, 2011.

*/

body {
	font-family: arial;
	margin: 0px;
}

/* make drag container visible */
#redips-drag {
	border: 2px dashed LightBlue;
	width: 580px;
	padding: 10px;
	margin: 0px auto;
}

/* set border-collapse */
div#redips-drag table {
/* 	border-collapse: collapse; */
	border-collapse: separate;
	border-spacing: 0px;
	width: 580px;
}
	/* define margin below first table */
	.tbl1 {
		margin-bottom: 17px;
	}

/* set table row height */
div#redips-drag table tr {
	height: 40px;
}

/*
	http://stackoverflow.com/questions/4096390/table-border-color-in-css-with-border-collapse

	if collapsing borders have the same style and width, but differ in color,
	then from most to least preferred: cell, row, row group, column, column group, table.

	if ... come from same type of element, such as two rows... then color is taken from
	borders that are the topmost and the leftmost.

	wider border wins over narrower ones / double wins over solid, then dashed, dotted, ridge, outset, groove, inset
*/
div#redips-drag td {
	border: 2px groove white;
}

/* table titles */
div#redips-drag th {
	font-size: 14pt;
}

/* drag object (DIV inside table cell) */
.redips-drag {
	margin: auto;
	margin-bottom: 1px;
	margin-top: 1px;
	text-align: center;
	font-size: 10pt;
	width: 70px;
	height: 20px;
	line-height: 20px;
	border-width: 2px;
	border-style: solid;
	background-color: white;
	/* round corners */
	border-radius: 4px; /* Opera, Chrome */
	-moz-border-radius: 4px; /* FF */
}

/* blue DIV elements */
.blue {
	border-color: SteelBlue;
}

/* orange DIV elements */
.orange {
	border-color: #FF8A58;
}

/* DIV row handlers (blue left column) */
.redips-row {
	width: 20px;
	margin: 2px;
	border-color: SteelBlue;
	background-color: SteelBlue;
	/* round corners */
	border-radius: 14px; /* Opera, Chrome */
	-moz-border-radius: 14px; /* FF */
}

/* row handler TD background color */
.redips-rowhandler {
	background-color: #76ACDA;
}

/* marked cells (forbidden access for header and message line) */
.redips-mark {
	color: white;
	background-color: #aaa;
	text-align: center;
}

/* row dark */
.rd {
	background-color: #ddd;
}

/* row light */
.rl {
	background-color: #eee;
}

/* cell dark */
.cdark {
	background-color: #C6C8CB;
}


text:
<title>Zend Framework API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link>

API Documentation

Acl/Role/Registry.php

Global

                      Classes

\Zend_Acl_Role_Registry

Zend Framework

LICENSE

This source file is subject to the new BSD license that is bundled
with this package in the file LICENSE.txt.
It is also available through the world-wide-web at this URL:
http://framework.zend.com/license/new-bsd
If you did not receive a copy of the license and are unable to
obtain it through the world-wide-web, please send an email
to license@zend.com so we can send you a copy immediately.

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Acl

version

$Id: Registry.php 23775 2011-03-01 17:25:24Z ralph $

\Zend_Acl_Role_Registry
jump to top

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Acl

Properties

array
                 $_roles= 'array'

Internal Role registry data storage

Default valuearrayDetails

Type

array

Methods

add(
          \Zend_Acl_Role_Interface $role, \Zend_Acl_Role_Interface|string|array $parents
              =
              null
          )

        :
          \Zend_Acl_Role_Registry

Adds a Role having an identifier unique to the registry

The $parents parameter may be a reference to, or the string identifier for,
a Role existing in the registry, or $parents may be passed as an array of
these - mixing string identifiers and objects is ok - to indicate the Roles
from which the newly added Role will directly inherit.

In order to resolve potential ambiguities with conflicting rules inherited
from different parents, the most recently added parent takes precedence over
parents that were previously added. In other words, the first parent added
will have the least priority, and the last parent added will have the
highest priority.

Parameters

Name
Type
Description

$role
\Zend_Acl_Role_Interface

$parents

\Zend_Acl_Role_Interface|string|array

Returns

Type
Description

\Zend_Acl_Role_Registry
Provides a fluent interface

Throws

Exception
Description

\Zend_Acl_Role_Registry_Exception

get(
          \Zend_Acl_Role_Interface|string $role
          )

        :
          \Zend_Acl_Role_Interface

Returns the identified Role

The $role parameter can either be a Role or a Role identifier.

Parameters

Name
Type
Description

$role

\Zend_Acl_Role_Interface|string

Returns

Type
Description

\Zend_Acl_Role_Interface

Throws

Exception
Description

\Zend_Acl_Role_Registry_Exception

getParents(
          \Zend_Acl_Role_Interface|string $role
          )

        :
          array

Returns an array of an existing Role's parents

The array keys are the identifiers of the parent Roles, and the values are
the parent Role instances. The parent Roles are ordered in this array by
ascending priority. The highest priority parent Role, last in the array,
corresponds with the parent Role most recently added.

If the Role does not have any parents, then an empty array is returned.

Parameters

Name
Type
Description

$role

\Zend_Acl_Role_Interface|string

Returns

Type
Description

array

Details

uses

\Zend_Acl_Role_Registry::get()

getRoles(

          )

        :
          void

has(
          \Zend_Acl_Role_Interface|string $role
          )

        :
          boolean

Returns true if and only if the Role exists in the registry

The $role parameter can either be a Role or a Role identifier.

Parameters

Name
Type
Description

$role

\Zend_Acl_Role_Interface|string

Returns

Type
Description

boolean

inherits(
          \Zend_Acl_Role_Interface|string $role, \Zend_Acl_Role_Interface|string $inherit, boolean $onlyParents
              =
              false
          )

        :
          boolean

Returns true if and only if $role inherits from $inherit

Both parameters may be either a Role or a Role identifier. If
$onlyParents is true, then $role must inherit directly from
$inherit in order to return true. By default, this method looks
through the entire inheritance DAG to determine whether $role
inherits from $inherit through its ancestor Roles.

Parameters

Name
Type
Description

$role

\Zend_Acl_Role_Interface|string

$inherit

\Zend_Acl_Role_Interface|string

$onlyParents
boolean

Returns

Type
Description

boolean

Throws

Exception
Description

\Zend_Acl_Role_Registry_Exception

remove(
          \Zend_Acl_Role_Interface|string $role
          )

        :
          \Zend_Acl_Role_Registry

Removes the Role from the registry

The $role parameter can either be a Role or a Role identifier.

Parameters

Name
Type
Description

$role

\Zend_Acl_Role_Interface|string

Returns

Type
Description

\Zend_Acl_Role_Registry
Provides a fluent interface

Throws

Exception
Description

\Zend_Acl_Role_Registry_Exception

removeAll(

          )

        :
          \Zend_Acl_Role_Registry

Removes all Roles from the registry

Returns

Type
Description

\Zend_Acl_Role_Registry
Provides a fluent interface

Documentation was generated by DocBlox 0.13.3.


text:
package uk.ac.york.mhe504.dblm.enhancedmodel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.io.FileUtils;

/**
 * Merges two sets of table data CSV files
 *
 * args[0] tables.csv
 * args[1] folder containing the access data files
 * args[2] folder containing the database table dump files
 * args[3] folder to save the output
 */
public class DumpMerger {

	public static void main (String[] args)
	{

		try {
			List<String> tablelist = FileUtils.readLines(new File(args[0]));
			ExecutorService executor = Executors.newFixedThreadPool(32);
			for (String tableName : tablelist)
			{
				tableName = tableName.split(",")[0];
				Merger m = new Merger(tableName, args);
				executor.execute(m);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

class Merger implements Runnable{

	 String tableName;
	 String[] args;
	 public Merger(String tname, String[] a)
	 {
		 tableName = tname;
		 args = a;
	 }
	 public void run() {
			try {
				List<String> accessFile = FileUtils.readLines(new File(args[1] + java.io.File.separator +tableName));
				List<String> dumpFile = FileUtils.readLines(new File(args[2] + java.io.File.separator +tableName));

				PrintWriter pw = new PrintWriter(args[3] + java.io.File.separator +tableName);
				for (String dline : dumpFile)
				{
					boolean w = false;
					for (String aline: accessFile)
					{
						if (aline.split("\t")[0].equals(dline))
						{
							w = true;
							pw.println(aline);
						}
					}
					if (w==false)
						pw.println(dline + "\t 0");
				}
				pw.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

	 }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Box Move Example</title>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. Soc. mycol. Fr. 23: 222 (1907)

#### Original name
Syncephalastrum cinereum Bainier, 1907

### Remarks
null


text:
//
// Library: KaosCollections
// File:    ValueEnumerator.cs
//
// Copyright © 2009-2020 Kasey Osborn (github.com/kaosborn)
// MIT License - Use and redistribute freely
//

using System;

namespace Kaos.Collections
{
    public abstract partial class Btree<T>
    {
        /// <exclude />
        private protected class ValueEnumerator<V> : BaseEnumerator
        {
            public V CurrentValue { get; private set; }

            public V CurrentValueOrDefault => NotActive ? default : CurrentValue;

            public ValueEnumerator (Btree<T> owner, bool isReverse=false) : base (owner, isReverse)
            { }

            public ValueEnumerator (Btree<T> owner, int count) : base (owner, count)
            { }

            public ValueEnumerator (Btree<T> owner, Func<V,bool> condition) : base (owner)
             => Bypass2 (condition, (leaf,ix) => ((PairLeaf<V>) leaf).GetValue (ix));

            public ValueEnumerator (Btree<T> owner, Func<V,int,bool> condition) : base (owner)
             => Bypass3 (condition, (leaf,ix) => ((PairLeaf<V>) leaf).GetValue (ix));

            public void Initialize()
            {
                Init();
                CurrentValue = default;
            }

            public bool Advance()
            {
                if (AdvanceBase())
                  { CurrentValue = ((PairLeaf<V>) leaf).GetValue (leafIndex); return true; }
                else
                  { CurrentValue = default; return false; }
            }

            public void BypassValue (Func<V,bool> condition)
             => Bypass2 (condition, (leaf,ix) => ((PairLeaf<V>) leaf).GetValue (ix));

            public void BypassValue (Func<V,int,bool> condition)
             => Bypass3 (condition, (leaf,ix) => ((PairLeaf<V>) leaf).GetValue (ix));
        }
    }
}


text:
using namespace System;
using namespace NETGeographicLib;

int main(array<System::String ^> ^/*args*/)
{
    try {
        GeodesicExact^ geod = gcnew GeodesicExact( Constants::WGS84::MajorRadius,
                                                   Constants::WGS84::Flattening );
        // Alternatively: GeodesicExact^ geod = gcnew GeodesicExact();
        {
            // Sample direct calculation, travelling about NE from JFK
            double lat1 = 40.6, lon1 = -73.8, s12 = 5.5e6, azi1 = 51;
            double lat2, lon2;
            geod->Direct(lat1, lon1, azi1, s12, lat2, lon2);
            Console::WriteLine(String::Format("Latitude: {0} Longitude: {1}", lat2, lon2));
        }
        {
            // Sample inverse calculation, JFK to LHR
            double
            lat1 = 40.6, lon1 = -73.8, // JFK Airport
            lat2 = 51.6, lon2 = -0.5;  // LHR Airport
            double s12;
            geod->Inverse(lat1, lon1, lat2, lon2, s12);
            Console::WriteLine(s12);
        }
    }
    catch (GeographicErr^ e) {
        Console::WriteLine(String::Format("Caught exception: {0}", e->Message));
        return -1;
    }
    return 0;
}


text:
package org.apache.commons.imaging.formats.jpeg.iptc;

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

public final class IptcTypeLookup {

    private static final Map<Integer, IptcType> IPTC_TYPE_MAP = new HashMap<>();
    static {
        for (final IptcType iptcType : IptcTypes.values()) {
            IPTC_TYPE_MAP.put(iptcType.getType(), iptcType);
        }
    }

    private IptcTypeLookup() {
    }

    public static IptcType getIptcType(final int type) {
        if (!IPTC_TYPE_MAP.containsKey(type)) {
            return IptcTypes.getUnknown(type);
        }
        return IPTC_TYPE_MAP.get(type);
    }
}


text:
class Kss_Emu : private Kss_Cpu, public Classic_Emu {
	typedef Kss_Cpu cpu;
public:
	// KSS file header
	enum { header_size = 0x10 };
	struct header_t
	{
		byte tag [4];
		byte load_addr [2];
		byte load_size [2];
		byte init_addr [2];
		byte play_addr [2];
		byte first_bank;
		byte bank_mode;
		byte extra_header;
		byte device_flags;
	};

	enum { ext_header_size = 0x10 };
	struct ext_header_t
	{
		byte data_size [4];
		byte unused [4];
		byte first_track [2];
		byte last_tack [2];
		byte psg_vol;
		byte scc_vol;
		byte msx_music_vol;
		byte msx_audio_vol;
	};

	struct composite_header_t : header_t, ext_header_t { };

	// Header for currently loaded file
	composite_header_t const& header() const { return header_; }

	static gme_type_t static_type() { return gme_kss_type; }
public:
	Kss_Emu();
	~Kss_Emu();
protected:
	blargg_err_t track_info_( track_info_t*, int track ) const;
	blargg_err_t load_( Data_Reader& );
	blargg_err_t start_track_( int );
	blargg_err_t run_clocks( blip_time_t&, int );
	void set_tempo_( double );
	void set_voice( int, Blip_Buffer*, Blip_Buffer*, Blip_Buffer* );
	void update_eq( blip_eq_t const& );
	void unload();
private:
	Rom_Data<page_size> rom;
	composite_header_t header_;

	bool scc_accessed;
	bool gain_updated;
	void update_gain();

	unsigned scc_enabled; // 0 or 0xC000
	byte const* bank_data;
	int bank_count;
	void set_bank( int logical, int physical );
	blargg_long bank_size() const { return (16 * 1024L) >> (header_.bank_mode >> 7 & 1); }

	blip_time_t play_period;
	blip_time_t next_play;
	int ay_latch;

	friend void kss_cpu_out( class Kss_Cpu*, cpu_time_t, unsigned addr, int data );
	friend int  kss_cpu_in( class Kss_Cpu*, cpu_time_t, unsigned addr );
	void cpu_write( unsigned addr, int data );
	friend void kss_cpu_write( class Kss_Cpu*, unsigned addr, int data );

	// large items
	enum { mem_size = 0x10000 };
	byte ram [mem_size + cpu_padding];

	Ay_Apu ay;
	Scc_Apu scc;
	Sms_Apu* sn;
	byte unmapped_read  [0x100];
	byte unmapped_write [page_size];
};

#endif


text:
Purchases
=========

[![Build Status](https://travis-ci.org/clippings/purchases.png?branch=master)](https://travis-ci.org/clippings/purchases)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/clippings/purchases/badges/quality-score.png)](https://scrutinizer-ci.com/g/clippings/purchases/)
[![Code Coverage](https://scrutinizer-ci.com/g/clippings/purchases/badges/coverage.png)](https://scrutinizer-ci.com/g/clippings/purchases/)
[![Latest Stable Version](https://poser.pugx.org/clippings/purchases/v/stable.png)](https://packagist.org/packages/clippings/purchases)

This is a Kohana module that gives you out of the box functionality for multi-store purchases (each purchase may have Items from different sellers, each handling their portion of products independently)

It utilizes omnipay package

Usage
-----

The provided models work out of the box. You'll also have "Product" and "Store" models that you should use and extend.

```php
// Initialize some products and stores.
$store1 = new Store(['name' => 'My First Store']);
$product1 = new Product(['name' => 'My First Product', 'currency' => 'GBP', 'value' => 2000]);
$product2 = new Product(['name' => 'My Second Product', 'currency' => 'EUR', 'value' => 1000]);

$store1->getProducts()
    ->add($product1)
    ->add($product2);

$store2 = new Store(['name' => 'My Second Store']);
$product3 = new Product(['name' => 'My Third Product', 'currency' => 'GBP', 'value' => 5000]);

$store2->getProducts()
    ->add($product3);

Store::saveArray([$store1, $store2]);

// Now we can purchase something
$purchase = new Purchase();
$purchase
    ->addProduct($product1)
    ->addProduct($product2)
    ->addProduct($product3, 2);

// Freeze all the values of the order,
// so that it remains "frozen", even if prices of products change
$purchase->freeze();

// Initialize omnipay getway - here you will have Paypal, Stripe etc.
$gateway = Omnipay::getFactory()->create('Dummy');

$parameters = [
    'card' => [
        'number' => '4242424242424242',
        'expiryMonth' => 7,
        'expiryYear' => 2014,
        'cvv' => 123,
    ],
    'clientIp' => '192.168.0.1',
];

$response = $purchase->purchase($gateway, $parameters);

echo $response->isSuccessful();
```

A diagram of the models
-----------------------

```
┌─────────┐   ┌──────────┐    ┌───────┐
│ Address ├──→│ Purchase │    │ Store │
└─────────┘   └─┬─────┬──┘    └─┬─────┘
                │     ↓         ↓
                │ ┌───────────────┐
                │ │ StorePurchase │
                │ └───────┬───────┘
                │         ↓
                │     ┌──────────────┐
                └────→│ PurchaseItem │
┌─────────┐           ├──────────────┤
│ Product ├──────────→│ ProductItem  │
└─────────┘           └──────────────┘
```

Purchase is comprised of "PurchaseItems", a model which holds all the items that the user purchases.ProductItem exteds PurchaseItem so that they share the same table, using IheritedTrait.

Each PurchaseItem however, also belongs to a "StorePurchase" model, that represents the purchase for a specific store. This relation is managed automatically when you add products via the "addProduct" method or addPurchaseItem

Adding items to a purchase
-----------------------------

```php
$purchase = new Purchase();

// Adding a product
$purchase->addProduct($product);

// Adding multiple products
$purchase->addProduct($product, 5);

```

As the product already belongs to a specific store, this will create a specific StorePurchase for that store, if none exists. otherwise it will add the item to the existing StorePurchase. If this product already is present in the form of ProductItem, then it will increment the quantity.

```php
$purchase = new Purchase();

// Adding a purchaseItem
$purchase->addPurchaseItem($store, $purchaseItem);
```

If you need to add some other type of purchase item, that does not have an intrinsic relationship with a store, you can use the addPurchaseItem method. It will add any type of PurchaseItem.

Freezing assets
---------------

Since purchases use [harp-orm/transfers](https://github.com/clippings/transfers) package, it has the ability to "freeze" the values of purchase items when a purchase is actually completed.

```php
$purchase = new Purchase();
$product = new Product(['price' => 100]);

$purchase->addProduct($product, 3);

$productItem = $purchase->getItems()->getFirst();

// This will return the value of the product * quantity
// In this case 300
echo $productItem->getValue();

// Perform a freeze:
$purchase->freeze();

$product->price = 4000;

// Will still be 300
echo $productItem->getValue();
```

Freezing works by setting an "isFrozen" flag explicitly, so that later calls on ``freeze()`` will not recalculate values. You can take advantage of this by explicitly setting this flag to false for specific items and calling ``freeze()`` againg, to "refreeze" those values.

If you freeze a Purchase all the related PurchaseItems and StorePurchases will be frozen alongside it.

Currency Calculatens
--------------------

Purchases have a "currency" value that all the purchase items use. Any products with different currency will be converted using [harp-orm/money](https://github.com/harp-orm/money). That's why purchase items will not function properly, until they are attached to a purchase, which holds the currency for them.

```php
$purchase = new Purchase(['currency' => 'GBP']);
$product = new Product(['price' => 100, 'currency' => 'EUR']);

$purchase->addProduct($product, 3);

$productItem = $purchase->getItems()->getFirst();

// This will not 300, but convert it to GBP (around 240)
echo $productItem->getValue();
```

Refunding
---------

You can refund individual store purchases in full or with a partial amount.

```
$purchase = Purchase::find(1);
$storePurchase = $purchase->getStorePurchases()->getFirst();

$refund = new Refund();

// This will
$refund->setValue($storePurchase->getValue());

$storePurchase->getRefunds()->add($refund);

// Initialize omnipay getway - here you will have Paypal, Stripe etc.
$gateway = Omnipay::getFactory()->create('Dummy');

$refund->refund($gateway);
```

The refund object has a validation for its value, so that you do not refund more than the remaining amount for the store purchase, taking into account previous refunds.

## License

Copyright (c) 2014, Clippings Ltd. Developed by Ivan Kerin

Under BSD-3-Clause license, read LICENSE file.


text:
<resources>

    <style name="AppBaseTheme" parent="android:Theme.Light" />

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme" />

</resources>


text:
namespace Cassette.BundleProcessing
{
    public class ConcatenateAssets : IBundleProcessor<Bundle>
    {
        public void Process(Bundle bundle)
        {
            bundle.ConcatenateAssets(Separator);
        }

        public string Separator { get; set; }
    }
}


text:
<?php
/**
 * @ignore
 */

namespace silverstripe\test;

class ClassD extends subtest\ClassC {  }