text
stringlengths 2
100k
| meta
dict |
---|---|
#ifndef Py_LIMITED_API
#ifndef Py_LONGINTREPR_H
#define Py_LONGINTREPR_H
#ifdef __cplusplus
extern "C" {
#endif
/* This is published for the benefit of "friends" marshal.c and _decimal.c. */
/* Parameters of the integer representation. There are two different
sets of parameters: one set for 30-bit digits, stored in an unsigned 32-bit
integer type, and one set for 15-bit digits with each digit stored in an
unsigned short. The value of PYLONG_BITS_IN_DIGIT, defined either at
configure time or in pyport.h, is used to decide which digit size to use.
Type 'digit' should be able to hold 2*PyLong_BASE-1, and type 'twodigits'
should be an unsigned integer type able to hold all integers up to
PyLong_BASE*PyLong_BASE-1. x_sub assumes that 'digit' is an unsigned type,
and that overflow is handled by taking the result modulo 2**N for some N >
PyLong_SHIFT. The majority of the code doesn't care about the precise
value of PyLong_SHIFT, but there are some notable exceptions:
- long_pow() requires that PyLong_SHIFT be divisible by 5
- PyLong_{As,From}ByteArray require that PyLong_SHIFT be at least 8
- long_hash() requires that PyLong_SHIFT is *strictly* less than the number
of bits in an unsigned long, as do the PyLong <-> long (or unsigned long)
conversion functions
- the Python int <-> size_t/Py_ssize_t conversion functions expect that
PyLong_SHIFT is strictly less than the number of bits in a size_t
- the marshal code currently expects that PyLong_SHIFT is a multiple of 15
- NSMALLNEGINTS and NSMALLPOSINTS should be small enough to fit in a single
digit; with the current values this forces PyLong_SHIFT >= 9
The values 15 and 30 should fit all of the above requirements, on any
platform.
*/
#if PYLONG_BITS_IN_DIGIT == 30
typedef uint32_t digit;
typedef int32_t sdigit; /* signed variant of digit */
typedef uint64_t twodigits;
typedef int64_t stwodigits; /* signed variant of twodigits */
#define PyLong_SHIFT 30
#define _PyLong_DECIMAL_SHIFT 9 /* max(e such that 10**e fits in a digit) */
#define _PyLong_DECIMAL_BASE ((digit)1000000000) /* 10 ** DECIMAL_SHIFT */
#elif PYLONG_BITS_IN_DIGIT == 15
typedef unsigned short digit;
typedef short sdigit; /* signed variant of digit */
typedef unsigned long twodigits;
typedef long stwodigits; /* signed variant of twodigits */
#define PyLong_SHIFT 15
#define _PyLong_DECIMAL_SHIFT 4 /* max(e such that 10**e fits in a digit) */
#define _PyLong_DECIMAL_BASE ((digit)10000) /* 10 ** DECIMAL_SHIFT */
#else
#error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
#endif
#define PyLong_BASE ((digit)1 << PyLong_SHIFT)
#define PyLong_MASK ((digit)(PyLong_BASE - 1))
#if PyLong_SHIFT % 5 != 0
#error "longobject.c requires that PyLong_SHIFT be divisible by 5"
#endif
/* Long integer representation.
The absolute value of a number is equal to
SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
Negative numbers are represented with ob_size < 0;
zero is represented by ob_size == 0.
In a normalized number, ob_digit[abs(ob_size)-1] (the most significant
digit) is never zero. Also, in all cases, for all valid i,
0 <= ob_digit[i] <= MASK.
The allocation function takes care of allocating extra memory
so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available.
CAUTION: Generic code manipulating subtypes of PyVarObject has to
aware that ints abuse ob_size's sign bit.
*/
struct _longobject {
PyObject_VAR_HEAD
digit ob_digit[1];
};
PyAPI_FUNC(PyLongObject *) _PyLong_New(Py_ssize_t);
/* Return a copy of src. */
PyAPI_FUNC(PyObject *) _PyLong_Copy(PyLongObject *src);
#ifdef __cplusplus
}
#endif
#endif /* !Py_LONGINTREPR_H */
#endif /* Py_LIMITED_API */
| {
"pile_set_name": "Github"
} |
{
"author": {
"name": "Isaac Z. Schlueter",
"email": "[email protected]",
"url": "http://blog.izs.me"
},
"name": "minimatch",
"description": "a glob matcher in javascript",
"version": "0.3.0",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/minimatch.git"
},
"main": "minimatch.js",
"scripts": {
"test": "tap test/*.js"
},
"engines": {
"node": "*"
},
"dependencies": {
"lru-cache": "2",
"sigmund": "~1.0.0"
},
"devDependencies": {
"tap": ""
},
"license": {
"type": "MIT",
"url": "http://github.com/isaacs/minimatch/raw/master/LICENSE"
},
"bugs": {
"url": "https://github.com/isaacs/minimatch/issues"
},
"homepage": "https://github.com/isaacs/minimatch",
"_id": "[email protected]",
"_shasum": "275d8edaac4f1bb3326472089e7949c8394699dd",
"_from": "[email protected]",
"_npmVersion": "1.4.10",
"_npmUser": {
"name": "isaacs",
"email": "[email protected]"
},
"maintainers": [
{
"name": "isaacs",
"email": "[email protected]"
}
],
"dist": {
"shasum": "275d8edaac4f1bb3326472089e7949c8394699dd",
"tarball": "http://registry.npmjs.org/minimatch/-/minimatch-0.3.0.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-0.3.0.tgz",
"readme": "ERROR: No README data found!"
}
| {
"pile_set_name": "Github"
} |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"introduction\"></a>\n",
"## Introduction to Dask\n",
"#### By Paul Hendricks\n",
"-------\n",
"\n",
"In this notebook, we will show how to get started with Dask using basic Python primitives like integers and strings.\n",
"\n",
"**Table of Contents**\n",
"\n",
"* [Introduction to Dask](#introduction)\n",
"* [Setup](#setup)\n",
"* [Introduction to Dask](#dask)\n",
"* [Conclusion](#conclusion)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"setup\"></a>\n",
"## Setup\n",
"\n",
"This notebook was tested using the following Docker containers:\n",
"\n",
"* `rapidsai/rapidsai-dev-nightly:0.10-cuda10.0-devel-ubuntu18.04-py3.7` container from [DockerHub](https://hub.docker.com/r/rapidsai/rapidsai-nightly)\n",
"\n",
"This notebook was run on the NVIDIA GV100 GPU. Please be aware that your system may be different and you may need to modify the code or install packages to run the below examples. \n",
"\n",
"If you think you have found a bug or an error, please file an issue here: https://github.com/rapidsai/notebooks-contrib/issues\n",
"\n",
"Before we begin, let's check out our hardware setup by running the `nvidia-smi` command."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!nvidia-smi"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, let's see what CUDA version we have:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!nvcc --version"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Install graphviz\n",
"The visualizations in this notebook require graphviz. Your environment may not have it installed, but don't worry! If you don't, we're going to install it now. This can take a little while, so sit tight."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"try:\n",
" import graphviz\n",
"except ModuleNotFoundError:\n",
" os.system('conda install -c conda-forge graphviz -y')\n",
" os.system('conda install -c conda-forge python-graphviz -y')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"dask\"></a>\n",
"## Introduction to Dask\n",
"\n",
"Dask is a library the allows for parallelized computing. Written in Python, it allows one to compose complex workflows using large data structures like those found in NumPy, Pandas, and cuDF. In the following examples and notebooks, we'll show how to use Dask with cuDF to accelerate common ETL tasks as well as build and train machine learning models like Linear Regression and XGBoost.\n",
"\n",
"To learn more about Dask, check out the documentation here: http://docs.dask.org/en/latest/\n",
"\n",
"#### Client/Workers\n",
"\n",
"Dask operates by creating a cluster composed of a \"client\" and multiple \"workers\". The client is responsible for scheduling work; the workers are responsible for actually executing that work. \n",
"\n",
"Typically, we set the number of workers to be equal to the number of computing resources we have available to us. For CPU based workflows, this might be the number of cores or threads on that particlular machine. For example, we might set `n_workers = 8` if we have 8 CPU cores or threads on our machine that can each operate in parallel. This allows us to take advantage of all of our computing resources and enjoy the most benefits from parallelization.\n",
"\n",
"On a system with one or more GPUs, we usually set the number of workers equal to the number of GPUs available to us. Dask is a first class citizen in the world of General Purpose GPU computing and the RAPIDS ecosystem makes it very easy to use Dask with cuDF and XGBoost. \n",
"\n",
"Before we get started with Dask, we need to setup a Local Cluster of workers to execute our work and a Client to coordinate and schedule work for that cluster. As we see below, we can inititate a `cluster` and `client` using only few lines of code."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import dask; print('Dask Version:', dask.__version__)\n",
"from dask.distributed import Client, LocalCluster\n",
"\n",
"\n",
"# create a local cluster with 4 workers\n",
"n_workers = 4\n",
"cluster = LocalCluster(n_workers=n_workers)\n",
"client = Client(cluster)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's inspect the `client` object to view our current Dask status. We should see the IP Address for our Scheduler as well as the the number of workers in our Cluster. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# show current Dask status\n",
"client"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also see the status and more information at the Dashboard, found at `http://<ip_address>/status`. You can ignore this for now, we'll dive into this in subsequent tutorials.\n",
"\n",
"With our client and workers setup, it's time to execute our first program in parallel. We'll define a function called `add_5_to_x` that takes some value `x` and adds 5 to it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def add_5_to_x(x):\n",
" return x + 5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we'll iterate through our `n_workers` and create an execution graph, where each worker is responsible for taking its ID and passing it to the function `add_5_to_x`. For example, the worker with ID 2 will take its ID and pass it to the function `add_5_to_x`, resulting in the value 7."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from dask import delayed\n",
"\n",
"\n",
"addition_operations = [delayed(add_5_to_x)(i) for i in range(n_workers)]\n",
"addition_operations"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The above output shows a list of several `Delayed` objects. An important thing to note is that the workers aren't actually executing these results - we're just defining the execution graph for our client to execute later. The `delayed` function wraps our function `add_5_to_x` and returns a `Delayed` object. This ensures that this computation is in fact \"delayed\" - or lazily evaluated - and not executed on the spot i.e. when we define it.\n",
"\n",
"Next, let's sum each one of these intermediate results. We can accomplish this by wrapping Python's built-in `sum` function using our `delayed` function and storing this in a variable called `total`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"total = delayed(sum)(addition_operations)\n",
"total"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using the `graphviz` library, we can use the `visualize` method of a `Delayed` object to visualize our current graph."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"total.visualize()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As we mentioned before, none of these results - intermediate or final - have actually been compute. We can compute them using the `compute` method of our `client`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from dask.distributed import wait\n",
"import time\n",
"\n",
"\n",
"addition_futures = client.compute(addition_operations, optimize_graph=False, fifo_timeout=\"0ms\")\n",
"total_future = client.compute(total, optimize_graph=False, fifo_timeout=\"0ms\")\n",
"wait(total_future) # this will give Dask time to execute the work"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's inspect the output of each call to `client.compute`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"addition_futures"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can see from the above output that our `addition_futures` variable is a list of `Future` objects - not the \"actual results\" of adding 5 to each of `[0, 1, 2, 3]`. These `Future` objects are a promise that at one point a computation will take place and we will be left with a result. Dask is responsible for fulfilling that promise by delegating that task to the appropriate Dask worker and collecting the result.\n",
"\n",
"Let's take a look at our `total_future` object:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(total_future)\n",
"print(type(total_future))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Again, we see that this is an object of type `Future` as well as metadata about the status of the request (i.e. whether it has finished or not), the type of the result, and a key associated with that operation. To collect and print the result of each of these `Future` objects, we can call the `result()` method."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"addition_results = [future.result() for future in addition_futures]\n",
"print('Addition Results:', addition_results)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we see the results that we want from our addition operations. We can also use the simpler syntax of the `client.gather` method to collect our results."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"addition_results = client.gather(addition_futures)\n",
"total_result = client.gather(total_future)\n",
"print('Addition Results:', addition_results)\n",
"print('Total Result:', total_result)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Awesome! We just wrote our first distributed workflow.\n",
"\n",
"To confirm that Dask is truly executing in parallel, let's define a function that sleeps for 1 second and returns the string \"Success!\". In serial, this function should take our 4 workers around 4 seconds to execute."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def sleep_1():\n",
" time.sleep(1)\n",
" return 'Success!'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%time\n",
"\n",
"for _ in range(n_workers):\n",
" sleep_1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As expected, our process takes about 4 seconds to run. Now let's execute this same workflow in parallel using Dask."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%time\n",
"\n",
"# define delayed execution graph\n",
"sleep_operations = [delayed(sleep_1)() for _ in range(n_workers)]\n",
"\n",
"# use client to perform computations using execution graph\n",
"sleep_futures = client.compute(sleep_operations, optimize_graph=False, fifo_timeout=\"0ms\")\n",
"\n",
"# collect and print results\n",
"sleep_results = client.gather(sleep_futures)\n",
"print(sleep_results)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using Dask, we see that this whole process takes a little over a second - each worker is executing in parallel!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"conclusion\"></a>\n",
"## Conclusion\n",
"\n",
"In this tutorial, we learned how to use Dask with basic Python primitives like integers and strings.\n",
"\n",
"To learn more about RAPIDS, be sure to check out: \n",
"\n",
"* [Open Source Website](http://rapids.ai)\n",
"* [GitHub](https://github.com/rapidsai/)\n",
"* [Press Release](https://nvidianews.nvidia.com/news/nvidia-introduces-rapids-open-source-gpu-acceleration-platform-for-large-scale-data-analytics-and-machine-learning)\n",
"* [NVIDIA Blog](https://blogs.nvidia.com/blog/2018/10/10/rapids-data-science-open-source-community/)\n",
"* [Developer Blog](https://devblogs.nvidia.com/gpu-accelerated-analytics-rapids/)\n",
"* [NVIDIA Data Science Webpage](https://www.nvidia.com/en-us/deep-learning-ai/solutions/data-science/)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
| {
"pile_set_name": "Github"
} |
#include <jni.h>
#include <string>
extern "C"
JNIEXPORT jstring
JNICALL
Java_com_dogcamera_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
| {
"pile_set_name": "Github"
} |
complete -c dlocate -s S -x -d 'List records that match filenames'
complete -c dlocate -s L -d 'List all files in the package' -xa '(__fish_print_packages)'
complete -c dlocate -o ls -d 'ls -ldF all files in the package' -xa '(__fish_print_packages)'
complete -c dlocate -o du -d 'du -sck all files in the package' -xa '(__fish_print_packages)'
| {
"pile_set_name": "Github"
} |
package node
type Node struct {
Id int
}
type NodeOrderedSet []Node
| {
"pile_set_name": "Github"
} |
class Check {
int x, y; // The x- and y-coordinates
int size; // Dimension (width and height)
color baseGray; // Default gray value
boolean checked = false; // True when the check box is selected
Check(int xp, int yp, int s, color b) {
x = xp;
y = yp;
size = s;
baseGray = b;
}
// Updates the boolean variable checked
void press(float mx, float my) {
if ((mx >= x) && (mx <= x+size) && (my >= y) && (my <= y+size)) {
checked = !checked; // Toggle the check box on and off
}
}
// Draws the box and an X inside if the checked variable is true
void display() {
stroke(255);
fill(baseGray);
rect(x, y, size, size);
if (checked == true) {
line(x, y, x+size, y+size);
line(x+size, y, x, y+size);
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2013 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs <[email protected]>
*/
#include "ctxgf100.h"
/*******************************************************************************
* PGRAPH context register lists
******************************************************************************/
static const struct gf100_gr_init
gk110_grctx_init_icmd_0[] = {
{ 0x001000, 1, 0x01, 0x00000004 },
{ 0x000039, 3, 0x01, 0x00000000 },
{ 0x0000a9, 1, 0x01, 0x0000ffff },
{ 0x000038, 1, 0x01, 0x0fac6881 },
{ 0x00003d, 1, 0x01, 0x00000001 },
{ 0x0000e8, 8, 0x01, 0x00000400 },
{ 0x000078, 8, 0x01, 0x00000300 },
{ 0x000050, 1, 0x01, 0x00000011 },
{ 0x000058, 8, 0x01, 0x00000008 },
{ 0x000208, 8, 0x01, 0x00000001 },
{ 0x000081, 1, 0x01, 0x00000001 },
{ 0x000085, 1, 0x01, 0x00000004 },
{ 0x000088, 1, 0x01, 0x00000400 },
{ 0x000090, 1, 0x01, 0x00000300 },
{ 0x000098, 1, 0x01, 0x00001001 },
{ 0x0000e3, 1, 0x01, 0x00000001 },
{ 0x0000da, 1, 0x01, 0x00000001 },
{ 0x0000f8, 1, 0x01, 0x00000003 },
{ 0x0000fa, 1, 0x01, 0x00000001 },
{ 0x00009f, 4, 0x01, 0x0000ffff },
{ 0x0000b1, 1, 0x01, 0x00000001 },
{ 0x0000ad, 1, 0x01, 0x0000013e },
{ 0x0000e1, 1, 0x01, 0x00000010 },
{ 0x000290, 16, 0x01, 0x00000000 },
{ 0x0003b0, 16, 0x01, 0x00000000 },
{ 0x0002a0, 16, 0x01, 0x00000000 },
{ 0x000420, 16, 0x01, 0x00000000 },
{ 0x0002b0, 16, 0x01, 0x00000000 },
{ 0x000430, 16, 0x01, 0x00000000 },
{ 0x0002c0, 16, 0x01, 0x00000000 },
{ 0x0004d0, 16, 0x01, 0x00000000 },
{ 0x000720, 16, 0x01, 0x00000000 },
{ 0x0008c0, 16, 0x01, 0x00000000 },
{ 0x000890, 16, 0x01, 0x00000000 },
{ 0x0008e0, 16, 0x01, 0x00000000 },
{ 0x0008a0, 16, 0x01, 0x00000000 },
{ 0x0008f0, 16, 0x01, 0x00000000 },
{ 0x00094c, 1, 0x01, 0x000000ff },
{ 0x00094d, 1, 0x01, 0xffffffff },
{ 0x00094e, 1, 0x01, 0x00000002 },
{ 0x0002ec, 1, 0x01, 0x00000001 },
{ 0x0002f2, 2, 0x01, 0x00000001 },
{ 0x0002f5, 1, 0x01, 0x00000001 },
{ 0x0002f7, 1, 0x01, 0x00000001 },
{ 0x000303, 1, 0x01, 0x00000001 },
{ 0x0002e6, 1, 0x01, 0x00000001 },
{ 0x000466, 1, 0x01, 0x00000052 },
{ 0x000301, 1, 0x01, 0x3f800000 },
{ 0x000304, 1, 0x01, 0x30201000 },
{ 0x000305, 1, 0x01, 0x70605040 },
{ 0x000306, 1, 0x01, 0xb8a89888 },
{ 0x000307, 1, 0x01, 0xf8e8d8c8 },
{ 0x00030a, 1, 0x01, 0x00ffff00 },
{ 0x00030b, 1, 0x01, 0x0000001a },
{ 0x00030c, 1, 0x01, 0x00000001 },
{ 0x000318, 1, 0x01, 0x00000001 },
{ 0x000340, 1, 0x01, 0x00000000 },
{ 0x000375, 1, 0x01, 0x00000001 },
{ 0x00037d, 1, 0x01, 0x00000006 },
{ 0x0003a0, 1, 0x01, 0x00000002 },
{ 0x0003aa, 1, 0x01, 0x00000001 },
{ 0x0003a9, 1, 0x01, 0x00000001 },
{ 0x000380, 1, 0x01, 0x00000001 },
{ 0x000383, 1, 0x01, 0x00000011 },
{ 0x000360, 1, 0x01, 0x00000040 },
{ 0x000366, 2, 0x01, 0x00000000 },
{ 0x000368, 1, 0x01, 0x00000fff },
{ 0x000370, 2, 0x01, 0x00000000 },
{ 0x000372, 1, 0x01, 0x000fffff },
{ 0x00037a, 1, 0x01, 0x00000012 },
{ 0x000619, 1, 0x01, 0x00000003 },
{ 0x000811, 1, 0x01, 0x00000003 },
{ 0x000812, 1, 0x01, 0x00000004 },
{ 0x000813, 1, 0x01, 0x00000006 },
{ 0x000814, 1, 0x01, 0x00000008 },
{ 0x000815, 1, 0x01, 0x0000000b },
{ 0x000800, 6, 0x01, 0x00000001 },
{ 0x000632, 1, 0x01, 0x00000001 },
{ 0x000633, 1, 0x01, 0x00000002 },
{ 0x000634, 1, 0x01, 0x00000003 },
{ 0x000635, 1, 0x01, 0x00000004 },
{ 0x000654, 1, 0x01, 0x3f800000 },
{ 0x000657, 1, 0x01, 0x3f800000 },
{ 0x000655, 2, 0x01, 0x3f800000 },
{ 0x0006cd, 1, 0x01, 0x3f800000 },
{ 0x0007f5, 1, 0x01, 0x3f800000 },
{ 0x0007dc, 1, 0x01, 0x39291909 },
{ 0x0007dd, 1, 0x01, 0x79695949 },
{ 0x0007de, 1, 0x01, 0xb9a99989 },
{ 0x0007df, 1, 0x01, 0xf9e9d9c9 },
{ 0x0007e8, 1, 0x01, 0x00003210 },
{ 0x0007e9, 1, 0x01, 0x00007654 },
{ 0x0007ea, 1, 0x01, 0x00000098 },
{ 0x0007ec, 1, 0x01, 0x39291909 },
{ 0x0007ed, 1, 0x01, 0x79695949 },
{ 0x0007ee, 1, 0x01, 0xb9a99989 },
{ 0x0007ef, 1, 0x01, 0xf9e9d9c9 },
{ 0x0007f0, 1, 0x01, 0x00003210 },
{ 0x0007f1, 1, 0x01, 0x00007654 },
{ 0x0007f2, 1, 0x01, 0x00000098 },
{ 0x0005a5, 1, 0x01, 0x00000001 },
{ 0x000980, 128, 0x01, 0x00000000 },
{ 0x000468, 1, 0x01, 0x00000004 },
{ 0x00046c, 1, 0x01, 0x00000001 },
{ 0x000470, 96, 0x01, 0x00000000 },
{ 0x000510, 16, 0x01, 0x3f800000 },
{ 0x000520, 1, 0x01, 0x000002b6 },
{ 0x000529, 1, 0x01, 0x00000001 },
{ 0x000530, 16, 0x01, 0xffff0000 },
{ 0x000585, 1, 0x01, 0x0000003f },
{ 0x000576, 1, 0x01, 0x00000003 },
{ 0x00057b, 1, 0x01, 0x00000059 },
{ 0x000586, 1, 0x01, 0x00000040 },
{ 0x000582, 2, 0x01, 0x00000080 },
{ 0x0005c2, 1, 0x01, 0x00000001 },
{ 0x000638, 2, 0x01, 0x00000001 },
{ 0x00063a, 1, 0x01, 0x00000002 },
{ 0x00063b, 2, 0x01, 0x00000001 },
{ 0x00063d, 1, 0x01, 0x00000002 },
{ 0x00063e, 1, 0x01, 0x00000001 },
{ 0x0008b8, 8, 0x01, 0x00000001 },
{ 0x000900, 8, 0x01, 0x00000001 },
{ 0x000908, 8, 0x01, 0x00000002 },
{ 0x000910, 16, 0x01, 0x00000001 },
{ 0x000920, 8, 0x01, 0x00000002 },
{ 0x000928, 8, 0x01, 0x00000001 },
{ 0x000662, 1, 0x01, 0x00000001 },
{ 0x000648, 9, 0x01, 0x00000001 },
{ 0x000658, 1, 0x01, 0x0000000f },
{ 0x0007ff, 1, 0x01, 0x0000000a },
{ 0x00066a, 1, 0x01, 0x40000000 },
{ 0x00066b, 1, 0x01, 0x10000000 },
{ 0x00066c, 2, 0x01, 0xffff0000 },
{ 0x0007af, 2, 0x01, 0x00000008 },
{ 0x0007f6, 1, 0x01, 0x00000001 },
{ 0x00080b, 1, 0x01, 0x00000002 },
{ 0x0006b2, 1, 0x01, 0x00000055 },
{ 0x0007ad, 1, 0x01, 0x00000003 },
{ 0x000937, 1, 0x01, 0x00000001 },
{ 0x000971, 1, 0x01, 0x00000008 },
{ 0x000972, 1, 0x01, 0x00000040 },
{ 0x000973, 1, 0x01, 0x0000012c },
{ 0x00097c, 1, 0x01, 0x00000040 },
{ 0x000979, 1, 0x01, 0x00000003 },
{ 0x000975, 1, 0x01, 0x00000020 },
{ 0x000976, 1, 0x01, 0x00000001 },
{ 0x000977, 1, 0x01, 0x00000020 },
{ 0x000978, 1, 0x01, 0x00000001 },
{ 0x000957, 1, 0x01, 0x00000003 },
{ 0x00095e, 1, 0x01, 0x20164010 },
{ 0x00095f, 1, 0x01, 0x00000020 },
{ 0x000a0d, 1, 0x01, 0x00000006 },
{ 0x00097d, 1, 0x01, 0x00000020 },
{ 0x000683, 1, 0x01, 0x00000006 },
{ 0x000685, 1, 0x01, 0x003fffff },
{ 0x000687, 1, 0x01, 0x003fffff },
{ 0x0006a0, 1, 0x01, 0x00000005 },
{ 0x000840, 1, 0x01, 0x00400008 },
{ 0x000841, 1, 0x01, 0x08000080 },
{ 0x000842, 1, 0x01, 0x00400008 },
{ 0x000843, 1, 0x01, 0x08000080 },
{ 0x0006aa, 1, 0x01, 0x00000001 },
{ 0x0006ab, 1, 0x01, 0x00000002 },
{ 0x0006ac, 1, 0x01, 0x00000080 },
{ 0x0006ad, 2, 0x01, 0x00000100 },
{ 0x0006b1, 1, 0x01, 0x00000011 },
{ 0x0006bb, 1, 0x01, 0x000000cf },
{ 0x0006ce, 1, 0x01, 0x2a712488 },
{ 0x000739, 1, 0x01, 0x4085c000 },
{ 0x00073a, 1, 0x01, 0x00000080 },
{ 0x000786, 1, 0x01, 0x80000100 },
{ 0x00073c, 1, 0x01, 0x00010100 },
{ 0x00073d, 1, 0x01, 0x02800000 },
{ 0x000787, 1, 0x01, 0x000000cf },
{ 0x00078c, 1, 0x01, 0x00000008 },
{ 0x000792, 1, 0x01, 0x00000001 },
{ 0x000794, 3, 0x01, 0x00000001 },
{ 0x000797, 1, 0x01, 0x000000cf },
{ 0x000836, 1, 0x01, 0x00000001 },
{ 0x00079a, 1, 0x01, 0x00000002 },
{ 0x000833, 1, 0x01, 0x04444480 },
{ 0x0007a1, 1, 0x01, 0x00000001 },
{ 0x0007a3, 3, 0x01, 0x00000001 },
{ 0x000831, 1, 0x01, 0x00000004 },
{ 0x000b07, 1, 0x01, 0x00000002 },
{ 0x000b08, 2, 0x01, 0x00000100 },
{ 0x000b0a, 1, 0x01, 0x00000001 },
{ 0x000a04, 1, 0x01, 0x000000ff },
{ 0x000a0b, 1, 0x01, 0x00000040 },
{ 0x00097f, 1, 0x01, 0x00000100 },
{ 0x000a02, 1, 0x01, 0x00000001 },
{ 0x000809, 1, 0x01, 0x00000007 },
{ 0x00c221, 1, 0x01, 0x00000040 },
{ 0x00c1b0, 8, 0x01, 0x0000000f },
{ 0x00c1b8, 1, 0x01, 0x0fac6881 },
{ 0x00c1b9, 1, 0x01, 0x00fac688 },
{ 0x00c401, 1, 0x01, 0x00000001 },
{ 0x00c402, 1, 0x01, 0x00010001 },
{ 0x00c403, 2, 0x01, 0x00000001 },
{ 0x00c40e, 1, 0x01, 0x00000020 },
{ 0x00c500, 1, 0x01, 0x00000003 },
{ 0x01e100, 1, 0x01, 0x00000001 },
{ 0x001000, 1, 0x01, 0x00000002 },
{ 0x0006aa, 1, 0x01, 0x00000001 },
{ 0x0006ad, 2, 0x01, 0x00000100 },
{ 0x0006b1, 1, 0x01, 0x00000011 },
{ 0x00078c, 1, 0x01, 0x00000008 },
{ 0x000792, 1, 0x01, 0x00000001 },
{ 0x000794, 3, 0x01, 0x00000001 },
{ 0x000797, 1, 0x01, 0x000000cf },
{ 0x00079a, 1, 0x01, 0x00000002 },
{ 0x000833, 1, 0x01, 0x04444480 },
{ 0x0007a1, 1, 0x01, 0x00000001 },
{ 0x0007a3, 3, 0x01, 0x00000001 },
{ 0x000831, 1, 0x01, 0x00000004 },
{ 0x01e100, 1, 0x01, 0x00000001 },
{ 0x001000, 1, 0x01, 0x00000008 },
{ 0x000039, 3, 0x01, 0x00000000 },
{ 0x000380, 1, 0x01, 0x00000001 },
{ 0x000366, 2, 0x01, 0x00000000 },
{ 0x000368, 1, 0x01, 0x00000fff },
{ 0x000370, 2, 0x01, 0x00000000 },
{ 0x000372, 1, 0x01, 0x000fffff },
{ 0x000813, 1, 0x01, 0x00000006 },
{ 0x000814, 1, 0x01, 0x00000008 },
{ 0x000957, 1, 0x01, 0x00000003 },
{ 0x000b07, 1, 0x01, 0x00000002 },
{ 0x000b08, 2, 0x01, 0x00000100 },
{ 0x000b0a, 1, 0x01, 0x00000001 },
{ 0x000a04, 1, 0x01, 0x000000ff },
{ 0x000a0b, 1, 0x01, 0x00000040 },
{ 0x00097f, 1, 0x01, 0x00000100 },
{ 0x000a02, 1, 0x01, 0x00000001 },
{ 0x000809, 1, 0x01, 0x00000007 },
{ 0x00c221, 1, 0x01, 0x00000040 },
{ 0x00c401, 1, 0x01, 0x00000001 },
{ 0x00c402, 1, 0x01, 0x00010001 },
{ 0x00c403, 2, 0x01, 0x00000001 },
{ 0x00c40e, 1, 0x01, 0x00000020 },
{ 0x00c500, 1, 0x01, 0x00000003 },
{ 0x01e100, 1, 0x01, 0x00000001 },
{ 0x001000, 1, 0x01, 0x00000001 },
{ 0x000b07, 1, 0x01, 0x00000002 },
{ 0x000b08, 2, 0x01, 0x00000100 },
{ 0x000b0a, 1, 0x01, 0x00000001 },
{ 0x01e100, 1, 0x01, 0x00000001 },
{}
};
const struct gf100_gr_pack
gk110_grctx_pack_icmd[] = {
{ gk110_grctx_init_icmd_0 },
{}
};
static const struct gf100_gr_init
gk110_grctx_init_a197_0[] = {
{ 0x000800, 8, 0x40, 0x00000000 },
{ 0x000804, 8, 0x40, 0x00000000 },
{ 0x000808, 8, 0x40, 0x00000400 },
{ 0x00080c, 8, 0x40, 0x00000300 },
{ 0x000810, 1, 0x04, 0x000000cf },
{ 0x000850, 7, 0x40, 0x00000000 },
{ 0x000814, 8, 0x40, 0x00000040 },
{ 0x000818, 8, 0x40, 0x00000001 },
{ 0x00081c, 8, 0x40, 0x00000000 },
{ 0x000820, 8, 0x40, 0x00000000 },
{ 0x001c00, 16, 0x10, 0x00000000 },
{ 0x001c04, 16, 0x10, 0x00000000 },
{ 0x001c08, 16, 0x10, 0x00000000 },
{ 0x001c0c, 16, 0x10, 0x00000000 },
{ 0x001d00, 16, 0x10, 0x00000000 },
{ 0x001d04, 16, 0x10, 0x00000000 },
{ 0x001d08, 16, 0x10, 0x00000000 },
{ 0x001d0c, 16, 0x10, 0x00000000 },
{ 0x001f00, 16, 0x08, 0x00000000 },
{ 0x001f04, 16, 0x08, 0x00000000 },
{ 0x001f80, 16, 0x08, 0x00000000 },
{ 0x001f84, 16, 0x08, 0x00000000 },
{ 0x002000, 1, 0x04, 0x00000000 },
{ 0x002040, 1, 0x04, 0x00000011 },
{ 0x002080, 1, 0x04, 0x00000020 },
{ 0x0020c0, 1, 0x04, 0x00000030 },
{ 0x002100, 1, 0x04, 0x00000040 },
{ 0x002140, 1, 0x04, 0x00000051 },
{ 0x00200c, 6, 0x40, 0x00000001 },
{ 0x002010, 1, 0x04, 0x00000000 },
{ 0x002050, 1, 0x04, 0x00000000 },
{ 0x002090, 1, 0x04, 0x00000001 },
{ 0x0020d0, 1, 0x04, 0x00000002 },
{ 0x002110, 1, 0x04, 0x00000003 },
{ 0x002150, 1, 0x04, 0x00000004 },
{ 0x000380, 4, 0x20, 0x00000000 },
{ 0x000384, 4, 0x20, 0x00000000 },
{ 0x000388, 4, 0x20, 0x00000000 },
{ 0x00038c, 4, 0x20, 0x00000000 },
{ 0x000700, 4, 0x10, 0x00000000 },
{ 0x000704, 4, 0x10, 0x00000000 },
{ 0x000708, 4, 0x10, 0x00000000 },
{ 0x002800, 128, 0x04, 0x00000000 },
{ 0x000a00, 16, 0x20, 0x00000000 },
{ 0x000a04, 16, 0x20, 0x00000000 },
{ 0x000a08, 16, 0x20, 0x00000000 },
{ 0x000a0c, 16, 0x20, 0x00000000 },
{ 0x000a10, 16, 0x20, 0x00000000 },
{ 0x000a14, 16, 0x20, 0x00000000 },
{ 0x000c00, 16, 0x10, 0x00000000 },
{ 0x000c04, 16, 0x10, 0x00000000 },
{ 0x000c08, 16, 0x10, 0x00000000 },
{ 0x000c0c, 16, 0x10, 0x3f800000 },
{ 0x000d00, 8, 0x08, 0xffff0000 },
{ 0x000d04, 8, 0x08, 0xffff0000 },
{ 0x000e00, 16, 0x10, 0x00000000 },
{ 0x000e04, 16, 0x10, 0xffff0000 },
{ 0x000e08, 16, 0x10, 0xffff0000 },
{ 0x000d40, 4, 0x08, 0x00000000 },
{ 0x000d44, 4, 0x08, 0x00000000 },
{ 0x001e00, 8, 0x20, 0x00000001 },
{ 0x001e04, 8, 0x20, 0x00000001 },
{ 0x001e08, 8, 0x20, 0x00000002 },
{ 0x001e0c, 8, 0x20, 0x00000001 },
{ 0x001e10, 8, 0x20, 0x00000001 },
{ 0x001e14, 8, 0x20, 0x00000002 },
{ 0x001e18, 8, 0x20, 0x00000001 },
{ 0x003400, 128, 0x04, 0x00000000 },
{ 0x00030c, 1, 0x04, 0x00000001 },
{ 0x001944, 1, 0x04, 0x00000000 },
{ 0x001514, 1, 0x04, 0x00000000 },
{ 0x000d68, 1, 0x04, 0x0000ffff },
{ 0x00121c, 1, 0x04, 0x0fac6881 },
{ 0x000fac, 1, 0x04, 0x00000001 },
{ 0x001538, 1, 0x04, 0x00000001 },
{ 0x000fe0, 2, 0x04, 0x00000000 },
{ 0x000fe8, 1, 0x04, 0x00000014 },
{ 0x000fec, 1, 0x04, 0x00000040 },
{ 0x000ff0, 1, 0x04, 0x00000000 },
{ 0x00179c, 1, 0x04, 0x00000000 },
{ 0x001228, 1, 0x04, 0x00000400 },
{ 0x00122c, 1, 0x04, 0x00000300 },
{ 0x001230, 1, 0x04, 0x00010001 },
{ 0x0007f8, 1, 0x04, 0x00000000 },
{ 0x0015b4, 1, 0x04, 0x00000001 },
{ 0x0015cc, 1, 0x04, 0x00000000 },
{ 0x001534, 1, 0x04, 0x00000000 },
{ 0x000fb0, 1, 0x04, 0x00000000 },
{ 0x0015d0, 1, 0x04, 0x00000000 },
{ 0x00153c, 1, 0x04, 0x00000000 },
{ 0x0016b4, 1, 0x04, 0x00000003 },
{ 0x000fbc, 4, 0x04, 0x0000ffff },
{ 0x000df8, 2, 0x04, 0x00000000 },
{ 0x001948, 1, 0x04, 0x00000000 },
{ 0x001970, 1, 0x04, 0x00000001 },
{ 0x00161c, 1, 0x04, 0x000009f0 },
{ 0x000dcc, 1, 0x04, 0x00000010 },
{ 0x00163c, 1, 0x04, 0x00000000 },
{ 0x0015e4, 1, 0x04, 0x00000000 },
{ 0x001160, 32, 0x04, 0x25e00040 },
{ 0x001880, 32, 0x04, 0x00000000 },
{ 0x000f84, 2, 0x04, 0x00000000 },
{ 0x0017c8, 2, 0x04, 0x00000000 },
{ 0x0017d0, 1, 0x04, 0x000000ff },
{ 0x0017d4, 1, 0x04, 0xffffffff },
{ 0x0017d8, 1, 0x04, 0x00000002 },
{ 0x0017dc, 1, 0x04, 0x00000000 },
{ 0x0015f4, 2, 0x04, 0x00000000 },
{ 0x001434, 2, 0x04, 0x00000000 },
{ 0x000d74, 1, 0x04, 0x00000000 },
{ 0x000dec, 1, 0x04, 0x00000001 },
{ 0x0013a4, 1, 0x04, 0x00000000 },
{ 0x001318, 1, 0x04, 0x00000001 },
{ 0x001644, 1, 0x04, 0x00000000 },
{ 0x000748, 1, 0x04, 0x00000000 },
{ 0x000de8, 1, 0x04, 0x00000000 },
{ 0x001648, 1, 0x04, 0x00000000 },
{ 0x0012a4, 1, 0x04, 0x00000000 },
{ 0x001120, 4, 0x04, 0x00000000 },
{ 0x001118, 1, 0x04, 0x00000000 },
{ 0x00164c, 1, 0x04, 0x00000000 },
{ 0x001658, 1, 0x04, 0x00000000 },
{ 0x001910, 1, 0x04, 0x00000290 },
{ 0x001518, 1, 0x04, 0x00000000 },
{ 0x00165c, 1, 0x04, 0x00000001 },
{ 0x001520, 1, 0x04, 0x00000000 },
{ 0x001604, 1, 0x04, 0x00000000 },
{ 0x001570, 1, 0x04, 0x00000000 },
{ 0x0013b0, 2, 0x04, 0x3f800000 },
{ 0x00020c, 1, 0x04, 0x00000000 },
{ 0x001670, 1, 0x04, 0x30201000 },
{ 0x001674, 1, 0x04, 0x70605040 },
{ 0x001678, 1, 0x04, 0xb8a89888 },
{ 0x00167c, 1, 0x04, 0xf8e8d8c8 },
{ 0x00166c, 1, 0x04, 0x00000000 },
{ 0x001680, 1, 0x04, 0x00ffff00 },
{ 0x0012d0, 1, 0x04, 0x00000003 },
{ 0x0012d4, 1, 0x04, 0x00000002 },
{ 0x001684, 2, 0x04, 0x00000000 },
{ 0x000dac, 2, 0x04, 0x00001b02 },
{ 0x000db4, 1, 0x04, 0x00000000 },
{ 0x00168c, 1, 0x04, 0x00000000 },
{ 0x0015bc, 1, 0x04, 0x00000000 },
{ 0x00156c, 1, 0x04, 0x00000000 },
{ 0x00187c, 1, 0x04, 0x00000000 },
{ 0x001110, 1, 0x04, 0x00000001 },
{ 0x000dc0, 3, 0x04, 0x00000000 },
{ 0x001234, 1, 0x04, 0x00000000 },
{ 0x001690, 1, 0x04, 0x00000000 },
{ 0x0012ac, 1, 0x04, 0x00000001 },
{ 0x0002c4, 1, 0x04, 0x00000000 },
{ 0x000790, 5, 0x04, 0x00000000 },
{ 0x00077c, 1, 0x04, 0x00000000 },
{ 0x001000, 1, 0x04, 0x00000010 },
{ 0x0010fc, 1, 0x04, 0x00000000 },
{ 0x001290, 1, 0x04, 0x00000000 },
{ 0x000218, 1, 0x04, 0x00000010 },
{ 0x0012d8, 1, 0x04, 0x00000000 },
{ 0x0012dc, 1, 0x04, 0x00000010 },
{ 0x000d94, 1, 0x04, 0x00000001 },
{ 0x00155c, 2, 0x04, 0x00000000 },
{ 0x001564, 1, 0x04, 0x00000fff },
{ 0x001574, 2, 0x04, 0x00000000 },
{ 0x00157c, 1, 0x04, 0x000fffff },
{ 0x001354, 1, 0x04, 0x00000000 },
{ 0x001610, 1, 0x04, 0x00000012 },
{ 0x001608, 2, 0x04, 0x00000000 },
{ 0x00260c, 1, 0x04, 0x00000000 },
{ 0x0007ac, 1, 0x04, 0x00000000 },
{ 0x00162c, 1, 0x04, 0x00000003 },
{ 0x000210, 1, 0x04, 0x00000000 },
{ 0x000320, 1, 0x04, 0x00000000 },
{ 0x000324, 6, 0x04, 0x3f800000 },
{ 0x000750, 1, 0x04, 0x00000000 },
{ 0x000760, 1, 0x04, 0x39291909 },
{ 0x000764, 1, 0x04, 0x79695949 },
{ 0x000768, 1, 0x04, 0xb9a99989 },
{ 0x00076c, 1, 0x04, 0xf9e9d9c9 },
{ 0x000770, 1, 0x04, 0x30201000 },
{ 0x000774, 1, 0x04, 0x70605040 },
{ 0x000778, 1, 0x04, 0x00009080 },
{ 0x000780, 1, 0x04, 0x39291909 },
{ 0x000784, 1, 0x04, 0x79695949 },
{ 0x000788, 1, 0x04, 0xb9a99989 },
{ 0x00078c, 1, 0x04, 0xf9e9d9c9 },
{ 0x0007d0, 1, 0x04, 0x30201000 },
{ 0x0007d4, 1, 0x04, 0x70605040 },
{ 0x0007d8, 1, 0x04, 0x00009080 },
{ 0x00037c, 1, 0x04, 0x00000001 },
{ 0x000740, 2, 0x04, 0x00000000 },
{ 0x002600, 1, 0x04, 0x00000000 },
{ 0x001918, 1, 0x04, 0x00000000 },
{ 0x00191c, 1, 0x04, 0x00000900 },
{ 0x001920, 1, 0x04, 0x00000405 },
{ 0x001308, 1, 0x04, 0x00000001 },
{ 0x001924, 1, 0x04, 0x00000000 },
{ 0x0013ac, 1, 0x04, 0x00000000 },
{ 0x00192c, 1, 0x04, 0x00000001 },
{ 0x00193c, 1, 0x04, 0x00002c1c },
{ 0x000d7c, 1, 0x04, 0x00000000 },
{ 0x000f8c, 1, 0x04, 0x00000000 },
{ 0x0002c0, 1, 0x04, 0x00000001 },
{ 0x001510, 1, 0x04, 0x00000000 },
{ 0x001940, 1, 0x04, 0x00000000 },
{ 0x000ff4, 2, 0x04, 0x00000000 },
{ 0x00194c, 2, 0x04, 0x00000000 },
{ 0x001968, 1, 0x04, 0x00000000 },
{ 0x001590, 1, 0x04, 0x0000003f },
{ 0x0007e8, 4, 0x04, 0x00000000 },
{ 0x00196c, 1, 0x04, 0x00000011 },
{ 0x0002e4, 1, 0x04, 0x0000b001 },
{ 0x00036c, 2, 0x04, 0x00000000 },
{ 0x00197c, 1, 0x04, 0x00000000 },
{ 0x000fcc, 2, 0x04, 0x00000000 },
{ 0x0002d8, 1, 0x04, 0x00000040 },
{ 0x001980, 1, 0x04, 0x00000080 },
{ 0x001504, 1, 0x04, 0x00000080 },
{ 0x001984, 1, 0x04, 0x00000000 },
{ 0x000300, 1, 0x04, 0x00000001 },
{ 0x0013a8, 1, 0x04, 0x00000000 },
{ 0x0012ec, 1, 0x04, 0x00000000 },
{ 0x001310, 1, 0x04, 0x00000000 },
{ 0x001314, 1, 0x04, 0x00000001 },
{ 0x001380, 1, 0x04, 0x00000000 },
{ 0x001384, 4, 0x04, 0x00000001 },
{ 0x001394, 1, 0x04, 0x00000000 },
{ 0x00139c, 1, 0x04, 0x00000000 },
{ 0x001398, 1, 0x04, 0x00000000 },
{ 0x001594, 1, 0x04, 0x00000000 },
{ 0x001598, 4, 0x04, 0x00000001 },
{ 0x000f54, 3, 0x04, 0x00000000 },
{ 0x0019bc, 1, 0x04, 0x00000000 },
{ 0x000f9c, 2, 0x04, 0x00000000 },
{ 0x0012cc, 1, 0x04, 0x00000000 },
{ 0x0012e8, 1, 0x04, 0x00000000 },
{ 0x00130c, 1, 0x04, 0x00000001 },
{ 0x001360, 8, 0x04, 0x00000000 },
{ 0x00133c, 2, 0x04, 0x00000001 },
{ 0x001344, 1, 0x04, 0x00000002 },
{ 0x001348, 2, 0x04, 0x00000001 },
{ 0x001350, 1, 0x04, 0x00000002 },
{ 0x001358, 1, 0x04, 0x00000001 },
{ 0x0012e4, 1, 0x04, 0x00000000 },
{ 0x00131c, 4, 0x04, 0x00000000 },
{ 0x0019c0, 1, 0x04, 0x00000000 },
{ 0x001140, 1, 0x04, 0x00000000 },
{ 0x0019c4, 1, 0x04, 0x00000000 },
{ 0x0019c8, 1, 0x04, 0x00001500 },
{ 0x00135c, 1, 0x04, 0x00000000 },
{ 0x000f90, 1, 0x04, 0x00000000 },
{ 0x0019e0, 8, 0x04, 0x00000001 },
{ 0x0019cc, 1, 0x04, 0x00000001 },
{ 0x0015b8, 1, 0x04, 0x00000000 },
{ 0x001a00, 1, 0x04, 0x00001111 },
{ 0x001a04, 7, 0x04, 0x00000000 },
{ 0x000d6c, 2, 0x04, 0xffff0000 },
{ 0x0010f8, 1, 0x04, 0x00001010 },
{ 0x000d80, 5, 0x04, 0x00000000 },
{ 0x000da0, 1, 0x04, 0x00000000 },
{ 0x0007a4, 2, 0x04, 0x00000000 },
{ 0x001508, 1, 0x04, 0x80000000 },
{ 0x00150c, 1, 0x04, 0x40000000 },
{ 0x001668, 1, 0x04, 0x00000000 },
{ 0x000318, 2, 0x04, 0x00000008 },
{ 0x000d9c, 1, 0x04, 0x00000001 },
{ 0x000ddc, 1, 0x04, 0x00000002 },
{ 0x000374, 1, 0x04, 0x00000000 },
{ 0x000378, 1, 0x04, 0x00000020 },
{ 0x0007dc, 1, 0x04, 0x00000000 },
{ 0x00074c, 1, 0x04, 0x00000055 },
{ 0x001420, 1, 0x04, 0x00000003 },
{ 0x0017bc, 2, 0x04, 0x00000000 },
{ 0x0017c4, 1, 0x04, 0x00000001 },
{ 0x001008, 1, 0x04, 0x00000008 },
{ 0x00100c, 1, 0x04, 0x00000040 },
{ 0x001010, 1, 0x04, 0x0000012c },
{ 0x000d60, 1, 0x04, 0x00000040 },
{ 0x00075c, 1, 0x04, 0x00000003 },
{ 0x001018, 1, 0x04, 0x00000020 },
{ 0x00101c, 1, 0x04, 0x00000001 },
{ 0x001020, 1, 0x04, 0x00000020 },
{ 0x001024, 1, 0x04, 0x00000001 },
{ 0x001444, 3, 0x04, 0x00000000 },
{ 0x000360, 1, 0x04, 0x20164010 },
{ 0x000364, 1, 0x04, 0x00000020 },
{ 0x000368, 1, 0x04, 0x00000000 },
{ 0x000de4, 1, 0x04, 0x00000000 },
{ 0x000204, 1, 0x04, 0x00000006 },
{ 0x000208, 1, 0x04, 0x00000000 },
{ 0x0002cc, 2, 0x04, 0x003fffff },
{ 0x001220, 1, 0x04, 0x00000005 },
{ 0x000fdc, 1, 0x04, 0x00000000 },
{ 0x000f98, 1, 0x04, 0x00400008 },
{ 0x001284, 1, 0x04, 0x08000080 },
{ 0x001450, 1, 0x04, 0x00400008 },
{ 0x001454, 1, 0x04, 0x08000080 },
{ 0x000214, 1, 0x04, 0x00000000 },
{}
};
const struct gf100_gr_pack
gk110_grctx_pack_mthd[] = {
{ gk110_grctx_init_a197_0, 0xa197 },
{ gf100_grctx_init_902d_0, 0x902d },
{}
};
static const struct gf100_gr_init
gk110_grctx_init_fe_0[] = {
{ 0x404004, 8, 0x04, 0x00000000 },
{ 0x404024, 1, 0x04, 0x0000e000 },
{ 0x404028, 8, 0x04, 0x00000000 },
{ 0x4040a8, 8, 0x04, 0x00000000 },
{ 0x4040c8, 1, 0x04, 0xf800008f },
{ 0x4040d0, 6, 0x04, 0x00000000 },
{ 0x4040e8, 1, 0x04, 0x00001000 },
{ 0x4040f8, 1, 0x04, 0x00000000 },
{ 0x404100, 10, 0x04, 0x00000000 },
{ 0x404130, 2, 0x04, 0x00000000 },
{ 0x404138, 1, 0x04, 0x20000040 },
{ 0x404150, 1, 0x04, 0x0000002e },
{ 0x404154, 1, 0x04, 0x00000400 },
{ 0x404158, 1, 0x04, 0x00000200 },
{ 0x404164, 1, 0x04, 0x00000055 },
{ 0x40417c, 2, 0x04, 0x00000000 },
{ 0x4041a0, 4, 0x04, 0x00000000 },
{ 0x404200, 1, 0x04, 0x0000a197 },
{ 0x404204, 1, 0x04, 0x0000a1c0 },
{ 0x404208, 1, 0x04, 0x0000a140 },
{ 0x40420c, 1, 0x04, 0x0000902d },
{}
};
const struct gf100_gr_init
gk110_grctx_init_pri_0[] = {
{ 0x404404, 12, 0x04, 0x00000000 },
{ 0x404438, 1, 0x04, 0x00000000 },
{ 0x404460, 2, 0x04, 0x00000000 },
{ 0x404468, 1, 0x04, 0x00ffffff },
{ 0x40446c, 1, 0x04, 0x00000000 },
{ 0x404480, 1, 0x04, 0x00000001 },
{ 0x404498, 1, 0x04, 0x00000001 },
{}
};
const struct gf100_gr_init
gk110_grctx_init_cwd_0[] = {
{ 0x405b00, 1, 0x04, 0x00000000 },
{ 0x405b10, 1, 0x04, 0x00001000 },
{ 0x405b20, 1, 0x04, 0x04000000 },
{}
};
static const struct gf100_gr_init
gk110_grctx_init_pd_0[] = {
{ 0x406020, 1, 0x04, 0x034103c1 },
{ 0x406028, 4, 0x04, 0x00000001 },
{ 0x4064a8, 1, 0x04, 0x00000000 },
{ 0x4064ac, 1, 0x04, 0x00003fff },
{ 0x4064b0, 3, 0x04, 0x00000000 },
{ 0x4064c0, 1, 0x04, 0x802000f0 },
{ 0x4064c4, 1, 0x04, 0x0192ffff },
{ 0x4064c8, 1, 0x04, 0x018007c0 },
{ 0x4064cc, 9, 0x04, 0x00000000 },
{ 0x4064fc, 1, 0x04, 0x0000022a },
{}
};
static const struct gf100_gr_init
gk110_grctx_init_be_0[] = {
{ 0x408800, 1, 0x04, 0x12802a3c },
{ 0x408804, 1, 0x04, 0x00000040 },
{ 0x408808, 1, 0x04, 0x1003e005 },
{ 0x408840, 1, 0x04, 0x0000000b },
{ 0x408900, 1, 0x04, 0x3080b801 },
{ 0x408904, 1, 0x04, 0x62000001 },
{ 0x408908, 1, 0x04, 0x00c8102f },
{ 0x408980, 1, 0x04, 0x0000011d },
{}
};
const struct gf100_gr_pack
gk110_grctx_pack_hub[] = {
{ gf100_grctx_init_main_0 },
{ gk110_grctx_init_fe_0 },
{ gk110_grctx_init_pri_0 },
{ gk104_grctx_init_memfmt_0 },
{ gk104_grctx_init_ds_0 },
{ gk110_grctx_init_cwd_0 },
{ gk110_grctx_init_pd_0 },
{ gf100_grctx_init_rstr2d_0 },
{ gk104_grctx_init_scc_0 },
{ gk110_grctx_init_be_0 },
{}
};
static const struct gf100_gr_init
gk110_grctx_init_setup_0[] = {
{ 0x418800, 1, 0x04, 0x7006860a },
{ 0x418808, 1, 0x04, 0x00000000 },
{ 0x41880c, 1, 0x04, 0x00000030 },
{ 0x418810, 1, 0x04, 0x00000000 },
{ 0x418828, 1, 0x04, 0x00000044 },
{ 0x418830, 1, 0x04, 0x10000001 },
{ 0x4188d8, 1, 0x04, 0x00000008 },
{ 0x4188e0, 1, 0x04, 0x01000000 },
{ 0x4188e8, 5, 0x04, 0x00000000 },
{ 0x4188fc, 1, 0x04, 0x20100018 },
{}
};
const struct gf100_gr_init
gk110_grctx_init_gpc_unk_2[] = {
{ 0x418d24, 1, 0x04, 0x00000000 },
{}
};
const struct gf100_gr_pack
gk110_grctx_pack_gpc[] = {
{ gf100_grctx_init_gpc_unk_0 },
{ gf119_grctx_init_prop_0 },
{ gf119_grctx_init_gpc_unk_1 },
{ gk110_grctx_init_setup_0 },
{ gf100_grctx_init_zcull_0 },
{ gf119_grctx_init_crstr_0 },
{ gk104_grctx_init_gpm_0 },
{ gk110_grctx_init_gpc_unk_2 },
{ gf100_grctx_init_gcc_0 },
{}
};
const struct gf100_gr_init
gk110_grctx_init_tex_0[] = {
{ 0x419a00, 1, 0x04, 0x000000f0 },
{ 0x419a04, 1, 0x04, 0x00000001 },
{ 0x419a08, 1, 0x04, 0x00000021 },
{ 0x419a0c, 1, 0x04, 0x00020000 },
{ 0x419a10, 1, 0x04, 0x00000000 },
{ 0x419a14, 1, 0x04, 0x00000200 },
{ 0x419a1c, 1, 0x04, 0x0000c000 },
{ 0x419a20, 1, 0x04, 0x00020800 },
{ 0x419a30, 1, 0x04, 0x00000001 },
{ 0x419ac4, 1, 0x04, 0x0037f440 },
{}
};
const struct gf100_gr_init
gk110_grctx_init_mpc_0[] = {
{ 0x419c00, 1, 0x04, 0x0000001a },
{ 0x419c04, 1, 0x04, 0x80000006 },
{ 0x419c08, 1, 0x04, 0x00000002 },
{ 0x419c20, 1, 0x04, 0x00000000 },
{ 0x419c24, 1, 0x04, 0x00084210 },
{ 0x419c28, 1, 0x04, 0x3efbefbe },
{}
};
const struct gf100_gr_init
gk110_grctx_init_l1c_0[] = {
{ 0x419ce8, 1, 0x04, 0x00000000 },
{ 0x419cf4, 1, 0x04, 0x00000203 },
{}
};
static const struct gf100_gr_init
gk110_grctx_init_sm_0[] = {
{ 0x419e04, 1, 0x04, 0x00000000 },
{ 0x419e08, 1, 0x04, 0x0000001d },
{ 0x419e0c, 1, 0x04, 0x00000000 },
{ 0x419e10, 1, 0x04, 0x00001c02 },
{ 0x419e44, 1, 0x04, 0x0013eff2 },
{ 0x419e48, 1, 0x04, 0x00000000 },
{ 0x419e4c, 1, 0x04, 0x0000007f },
{ 0x419e50, 2, 0x04, 0x00000000 },
{ 0x419e58, 1, 0x04, 0x00000001 },
{ 0x419e5c, 3, 0x04, 0x00000000 },
{ 0x419e68, 1, 0x04, 0x00000002 },
{ 0x419e6c, 12, 0x04, 0x00000000 },
{ 0x419eac, 1, 0x04, 0x00001f8f },
{ 0x419eb0, 1, 0x04, 0x0db00d2f },
{ 0x419eb8, 1, 0x04, 0x00000000 },
{ 0x419ec8, 1, 0x04, 0x0001304f },
{ 0x419f30, 4, 0x04, 0x00000000 },
{ 0x419f40, 1, 0x04, 0x00000018 },
{ 0x419f44, 3, 0x04, 0x00000000 },
{ 0x419f58, 1, 0x04, 0x00000000 },
{ 0x419f70, 1, 0x04, 0x00007300 },
{ 0x419f78, 1, 0x04, 0x000000eb },
{ 0x419f7c, 1, 0x04, 0x00000404 },
{}
};
static const struct gf100_gr_pack
gk110_grctx_pack_tpc[] = {
{ gf117_grctx_init_pe_0 },
{ gk110_grctx_init_tex_0 },
{ gk110_grctx_init_mpc_0 },
{ gk110_grctx_init_l1c_0 },
{ gk110_grctx_init_sm_0 },
{}
};
static const struct gf100_gr_init
gk110_grctx_init_cbm_0[] = {
{ 0x41bec0, 1, 0x04, 0x10000000 },
{ 0x41bec4, 1, 0x04, 0x00037f7f },
{ 0x41bee4, 1, 0x04, 0x00000000 },
{}
};
const struct gf100_gr_pack
gk110_grctx_pack_ppc[] = {
{ gk104_grctx_init_pes_0 },
{ gk110_grctx_init_cbm_0 },
{ gf117_grctx_init_wwdx_0 },
{}
};
/*******************************************************************************
* PGRAPH context implementation
******************************************************************************/
const struct gf100_grctx_func
gk110_grctx = {
.main = gk104_grctx_generate_main,
.unkn = gk104_grctx_generate_unkn,
.hub = gk110_grctx_pack_hub,
.gpc = gk110_grctx_pack_gpc,
.zcull = gf100_grctx_pack_zcull,
.tpc = gk110_grctx_pack_tpc,
.ppc = gk110_grctx_pack_ppc,
.icmd = gk110_grctx_pack_icmd,
.mthd = gk110_grctx_pack_mthd,
.bundle = gk104_grctx_generate_bundle,
.bundle_size = 0x3000,
.bundle_min_gpm_fifo_depth = 0x180,
.bundle_token_limit = 0x7c0,
.pagepool = gk104_grctx_generate_pagepool,
.pagepool_size = 0x8000,
.attrib = gf117_grctx_generate_attrib,
.attrib_nr_max = 0x324,
.attrib_nr = 0x218,
.alpha_nr_max = 0x7ff,
.alpha_nr = 0x648,
};
| {
"pile_set_name": "Github"
} |
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- weixuan
labels:
- live
- service
- service/live/xroom
options:
no_parent_owners: true
| {
"pile_set_name": "Github"
} |
//
// Paragraphs.swift
// SavannaKit
//
// Created by Louis D'hauwe on 17/02/2018.
// Copyright © 2018 Silver Fox. All rights reserved.
//
import Foundation
#if os(macOS)
import AppKit
#else
import UIKit
#endif
extension TextView {
func paragraphRectForRange(range: NSRange) -> CGRect {
var nsRange = range
let layoutManager: NSLayoutManager
let textContainer: NSTextContainer
#if os(macOS)
layoutManager = self.layoutManager!
textContainer = self.textContainer!
#else
layoutManager = self.layoutManager
textContainer = self.textContainer
#endif
nsRange = layoutManager.glyphRange(forCharacterRange: nsRange, actualCharacterRange: nil)
var sectionRect = layoutManager.boundingRect(forGlyphRange: nsRange, in: textContainer)
// FIXME: don't use this hack
// This gets triggered for the final paragraph in a textview if the next line is empty (so the last paragraph ends with a newline)
if sectionRect.origin.x == 0 {
sectionRect.size.height -= 22
}
sectionRect.origin.x = 0
return sectionRect
}
}
func generateParagraphs(for textView: InnerTextView, flipRects: Bool = false) -> [Paragraph] {
let range = NSRange(location: 0, length: (textView.text as NSString).length)
var paragraphs = [Paragraph]()
var i = 0
(textView.text as NSString).enumerateSubstrings(in: range, options: [.byParagraphs]) { (paragraphContent, paragraphRange, enclosingRange, stop) in
i += 1
let rect = textView.paragraphRectForRange(range: paragraphRange)
let paragraph = Paragraph(rect: rect, number: i)
paragraphs.append(paragraph)
}
if textView.text.isEmpty || textView.text.hasSuffix("\n") {
var rect: CGRect
#if os(macOS)
let gutterWidth = textView.textContainerInset.width
#else
let gutterWidth = textView.textContainerInset.left
#endif
let lineHeight: CGFloat = 18
if let last = paragraphs.last {
// FIXME: don't use hardcoded "2" as line spacing
rect = CGRect(x: 0, y: last.rect.origin.y + last.rect.height + 2, width: gutterWidth, height: last.rect.height)
} else {
rect = CGRect(x: 0, y: 0, width: gutterWidth, height: lineHeight)
}
i += 1
let endParagraph = Paragraph(rect: rect, number: i)
paragraphs.append(endParagraph)
}
if flipRects {
paragraphs = paragraphs.map { (p) -> Paragraph in
var p = p
p.rect.origin.y = textView.bounds.height - p.rect.height - p.rect.origin.y
return p
}
}
return paragraphs
}
func offsetParagraphs(_ paragraphs: [Paragraph], for textView: InnerTextView, yOffset: CGFloat = 0) -> [Paragraph] {
var paragraphs = paragraphs
#if os(macOS)
if let yOffset = textView.enclosingScrollView?.contentView.bounds.origin.y {
paragraphs = paragraphs.map { (p) -> Paragraph in
var p = p
p.rect.origin.y += yOffset
return p
}
}
#endif
paragraphs = paragraphs.map { (p) -> Paragraph in
var p = p
p.rect.origin.y += yOffset
return p
}
return paragraphs
}
func drawLineNumbers(_ paragraphs: [Paragraph], in rect: CGRect, for textView: InnerTextView) {
guard let style = textView.theme?.lineNumbersStyle else {
return
}
for paragraph in paragraphs {
guard paragraph.rect.intersects(rect) else {
continue
}
let attr = paragraph.attributedString(for: style)
var drawRect = paragraph.rect
let gutterWidth = textView.gutterWidth
let drawSize = attr.size()
drawRect.origin.x = gutterWidth - drawSize.width - 4
#if os(macOS)
// drawRect.origin.y += (drawRect.height - drawSize.height) / 2.0
#else
// drawRect.origin.y += 22 - drawSize.height
#endif
drawRect.size.width = drawSize.width
drawRect.size.height = drawSize.height
// Color.red.withAlphaComponent(0.4).setFill()
// paragraph.rect.fill()
attr.draw(in: drawRect)
}
}
| {
"pile_set_name": "Github"
} |
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"jsx": "react",
"esModuleInterop": true,
"sourceMap": true,
"baseUrl": ".",
"strict": true,
"paths": {
"@/*": ["src/*"],
"@tmp/*": ["src/pages/.umi/*"]
},
"allowSyntheticDefaultImports": true
}
}
| {
"pile_set_name": "Github"
} |
/**
* This file is part of logisim-evolution.
*
* Logisim-evolution is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Logisim-evolution 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 General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with logisim-evolution. If not, see <http://www.gnu.org/licenses/>.
*
* Original code by Carl Burch (http://www.cburch.com), 2011.
* Subsequent modifications by:
* + College of the Holy Cross
* http://www.holycross.edu
* + Haute École Spécialisée Bernoise/Berner Fachhochschule
* http://www.bfh.ch
* + Haute École du paysage, d'ingénierie et d'architecture de Genève
* http://hepia.hesge.ch/
* + Haute École d'Ingénierie et de Gestion du Canton de Vaud
* http://www.heig-vd.ch/
*/
package com.cburch.draw.canvas;
import com.cburch.draw.model.CanvasObject;
import java.util.Collection;
import java.util.EventObject;
public class SelectionEvent extends EventObject {
private static final long serialVersionUID = 1L;
public static final int ACTION_ADDED = 0;
public static final int ACTION_REMOVED = 1;
public static final int ACTION_HANDLE = 2;
private int action;
private Collection<CanvasObject> affected;
public SelectionEvent(Selection source, int action, Collection<CanvasObject> affected) {
super(source);
this.action = action;
this.affected = affected;
}
public int getAction() {
return action;
}
public Collection<CanvasObject> getAffected() {
return affected;
}
public Selection getSelection() {
return (Selection) getSource();
}
}
| {
"pile_set_name": "Github"
} |
package systemtests
import . "gopkg.in/check.v1"
func (s *systemtestSuite) TestBasicStarted(c *C) {
c.Assert(s.vagrant.GetNode("mon0").RunCommand("pgrep -c apiserver"), IsNil)
c.Assert(s.vagrant.SSHExecAllNodes("pgrep -c volplugin"), IsNil)
}
func (s *systemtestSuite) TestBasicSSH(c *C) {
c.Assert(s.vagrant.SSHExecAllNodes("/bin/echo"), IsNil)
}
| {
"pile_set_name": "Github"
} |
<!--
Description: feed copyright contains onresize
Expect: not bozo and feed['copyright'] == u'<img src="http://www.ragingplatypus.com/i/cam-full.jpg" />'
-->
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<copyright type="text/html" mode="escaped"><img src="http://www.ragingplatypus.com/i/cam-full.jpg" onresize="location.href='http://www.ragingplatypus.com/';" /></copyright>
</feed> | {
"pile_set_name": "Github"
} |
/* GCC Quad-Precision Math Library
Copyright (C) 2010, 2011 Free Software Foundation, Inc.
Written by Francois-Xavier Coudert <[email protected]>
This file is part of the libquadmath library.
Libquadmath is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
Libquadmath 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with libquadmath; see the file COPYING.LIB. If
not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
Boston, MA 02110-1301, USA. */
#ifndef QUADMATH_H
#define QUADMATH_H
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Define the complex type corresponding to __float128
("_Complex __float128" is not allowed) */
#if (!defined(_ARCH_PPC)) || defined(__LONG_DOUBLE_IEEE128__)
typedef _Complex float __attribute__((mode(TC))) __complex128;
#else
typedef _Complex float __attribute__((mode(KC))) __complex128;
#endif
#ifdef __cplusplus
# define __quadmath_throw throw ()
# define __quadmath_nth(fct) fct throw ()
#else
# define __quadmath_throw __attribute__((__nothrow__))
# define __quadmath_nth(fct) __attribute__((__nothrow__)) fct
#endif
/* Prototypes for real functions */
extern __float128 acosq (__float128) __quadmath_throw;
extern __float128 acoshq (__float128) __quadmath_throw;
extern __float128 asinq (__float128) __quadmath_throw;
extern __float128 asinhq (__float128) __quadmath_throw;
extern __float128 atanq (__float128) __quadmath_throw;
extern __float128 atanhq (__float128) __quadmath_throw;
extern __float128 atan2q (__float128, __float128) __quadmath_throw;
extern __float128 cbrtq (__float128) __quadmath_throw;
extern __float128 ceilq (__float128) __quadmath_throw;
extern __float128 copysignq (__float128, __float128) __quadmath_throw;
extern __float128 coshq (__float128) __quadmath_throw;
extern __float128 cosq (__float128) __quadmath_throw;
extern __float128 erfq (__float128) __quadmath_throw;
extern __float128 erfcq (__float128) __quadmath_throw;
extern __float128 expq (__float128) __quadmath_throw;
extern __float128 expm1q (__float128) __quadmath_throw;
extern __float128 fabsq (__float128) __quadmath_throw;
extern __float128 fdimq (__float128, __float128) __quadmath_throw;
extern int finiteq (__float128) __quadmath_throw;
extern __float128 floorq (__float128) __quadmath_throw;
extern __float128 fmaq (__float128, __float128, __float128) __quadmath_throw;
extern __float128 fmaxq (__float128, __float128) __quadmath_throw;
extern __float128 fminq (__float128, __float128) __quadmath_throw;
extern __float128 fmodq (__float128, __float128) __quadmath_throw;
extern __float128 frexpq (__float128, int *) __quadmath_throw;
extern __float128 hypotq (__float128, __float128) __quadmath_throw;
extern int isinfq (__float128) __quadmath_throw;
extern int ilogbq (__float128) __quadmath_throw;
extern int isnanq (__float128) __quadmath_throw;
extern __float128 j0q (__float128) __quadmath_throw;
extern __float128 j1q (__float128) __quadmath_throw;
extern __float128 jnq (int, __float128) __quadmath_throw;
extern __float128 ldexpq (__float128, int) __quadmath_throw;
extern __float128 lgammaq (__float128) __quadmath_throw;
extern long long int llrintq (__float128) __quadmath_throw;
extern long long int llroundq (__float128) __quadmath_throw;
extern __float128 logbq (__float128) __quadmath_throw;
extern __float128 logq (__float128) __quadmath_throw;
extern __float128 log10q (__float128) __quadmath_throw;
extern __float128 log2q (__float128) __quadmath_throw;
extern __float128 log1pq (__float128) __quadmath_throw;
extern long int lrintq (__float128) __quadmath_throw;
extern long int lroundq (__float128) __quadmath_throw;
extern __float128 modfq (__float128, __float128 *) __quadmath_throw;
extern __float128 nanq (const char *) __quadmath_throw;
extern __float128 nearbyintq (__float128) __quadmath_throw;
extern __float128 nextafterq (__float128, __float128) __quadmath_throw;
extern __float128 powq (__float128, __float128) __quadmath_throw;
extern __float128 remainderq (__float128, __float128) __quadmath_throw;
extern __float128 remquoq (__float128, __float128, int *) __quadmath_throw;
extern __float128 rintq (__float128) __quadmath_throw;
extern __float128 roundq (__float128) __quadmath_throw;
extern __float128 scalblnq (__float128, long int) __quadmath_throw;
extern __float128 scalbnq (__float128, int) __quadmath_throw;
extern int signbitq (__float128) __quadmath_throw;
extern void sincosq (__float128, __float128 *, __float128 *) __quadmath_throw;
extern __float128 sinhq (__float128) __quadmath_throw;
extern __float128 sinq (__float128) __quadmath_throw;
extern __float128 sqrtq (__float128) __quadmath_throw;
extern __float128 tanq (__float128) __quadmath_throw;
extern __float128 tanhq (__float128) __quadmath_throw;
extern __float128 tgammaq (__float128) __quadmath_throw;
extern __float128 truncq (__float128) __quadmath_throw;
extern __float128 y0q (__float128) __quadmath_throw;
extern __float128 y1q (__float128) __quadmath_throw;
extern __float128 ynq (int, __float128) __quadmath_throw;
/* Prototypes for complex functions */
extern __float128 cabsq (__complex128) __quadmath_throw;
extern __float128 cargq (__complex128) __quadmath_throw;
extern __float128 cimagq (__complex128) __quadmath_throw;
extern __float128 crealq (__complex128) __quadmath_throw;
extern __complex128 cacosq (__complex128) __quadmath_throw;
extern __complex128 cacoshq (__complex128) __quadmath_throw;
extern __complex128 casinq (__complex128) __quadmath_throw;
extern __complex128 casinhq (__complex128) __quadmath_throw;
extern __complex128 catanq (__complex128) __quadmath_throw;
extern __complex128 catanhq (__complex128) __quadmath_throw;
extern __complex128 ccosq (__complex128) __quadmath_throw;
extern __complex128 ccoshq (__complex128) __quadmath_throw;
extern __complex128 cexpq (__complex128) __quadmath_throw;
extern __complex128 cexpiq (__float128) __quadmath_throw;
extern __complex128 clogq (__complex128) __quadmath_throw;
extern __complex128 clog10q (__complex128) __quadmath_throw;
extern __complex128 conjq (__complex128) __quadmath_throw;
extern __complex128 cpowq (__complex128, __complex128) __quadmath_throw;
extern __complex128 cprojq (__complex128) __quadmath_throw;
extern __complex128 csinq (__complex128) __quadmath_throw;
extern __complex128 csinhq (__complex128) __quadmath_throw;
extern __complex128 csqrtq (__complex128) __quadmath_throw;
extern __complex128 ctanq (__complex128) __quadmath_throw;
extern __complex128 ctanhq (__complex128) __quadmath_throw;
/* Prototypes for string <-> __float128 conversion functions */
extern __float128 strtoflt128 (const char *, char **) __quadmath_throw;
extern int quadmath_snprintf (char *str, size_t size,
const char *format, ...) __quadmath_throw;
/* Macros */
#define FLT128_MAX 1.18973149535723176508575932662800702e4932Q
#define FLT128_MIN 3.36210314311209350626267781732175260e-4932Q
#define FLT128_EPSILON 1.92592994438723585305597794258492732e-34Q
#define FLT128_DENORM_MIN 6.475175119438025110924438958227646552e-4966Q
#define FLT128_MANT_DIG 113
#define FLT128_MIN_EXP (-16381)
#define FLT128_MAX_EXP 16384
#define FLT128_DIG 33
#define FLT128_MIN_10_EXP (-4931)
#define FLT128_MAX_10_EXP 4932
#define HUGE_VALQ __builtin_huge_valq()
/* The following alternative is valid, but brings the warning:
(floating constant exceeds range of ‘__float128’) */
/* #define HUGE_VALQ (__extension__ 0x1.0p32767Q) */
#define M_Eq 2.7182818284590452353602874713526625Q /* e */
#define M_LOG2Eq 1.4426950408889634073599246810018921Q /* log_2 e */
#define M_LOG10Eq 0.4342944819032518276511289189166051Q /* log_10 e */
#define M_LN2q 0.6931471805599453094172321214581766Q /* log_e 2 */
#define M_LN10q 2.3025850929940456840179914546843642Q /* log_e 10 */
#define M_PIq 3.1415926535897932384626433832795029Q /* pi */
#define M_PI_2q 1.5707963267948966192313216916397514Q /* pi/2 */
#define M_PI_4q 0.7853981633974483096156608458198757Q /* pi/4 */
#define M_1_PIq 0.3183098861837906715377675267450287Q /* 1/pi */
#define M_2_PIq 0.6366197723675813430755350534900574Q /* 2/pi */
#define M_2_SQRTPIq 1.1283791670955125738961589031215452Q /* 2/sqrt(pi) */
#define M_SQRT2q 1.4142135623730950488016887242096981Q /* sqrt(2) */
#define M_SQRT1_2q 0.7071067811865475244008443621048490Q /* 1/sqrt(2) */
#define __quadmath_extern_inline \
extern inline __attribute__ ((__gnu_inline__))
__quadmath_extern_inline __float128
__quadmath_nth (cimagq (__complex128 __z))
{
return __imag__ __z;
}
__quadmath_extern_inline __float128
__quadmath_nth (crealq (__complex128 __z))
{
return __real__ __z;
}
__quadmath_extern_inline __complex128
__quadmath_nth (conjq (__complex128 __z))
{
return __extension__ ~__z;
}
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
function* g(){ x ? yield : y }
| {
"pile_set_name": "Github"
} |
//
// Custom Heap Memory Allocators
//
#include <stdlib.h>
#include <new>
#include "porting_inline.hpp"
#include "system.h"
#include "heaplayers.h"
using namespace HL;
volatile int anyThreadCreatedInHL = 1;
//
// Fixed Heap
//
// class definition
class TheFixedHeapType :
public LockedHeap<SpinLockType,FreelistHeap<ZoneHeap<MallocHeap,0> > > {};
// initialize & finalize
UINTPTR
hl_register_fixed_heap (int chunk_size)
{
TheFixedHeapType *th = new TheFixedHeapType;
if (th)
{
th->reset (chunk_size);
return (UINTPTR) th;
}
return 0;
}
void
hl_unregister_fixed_heap (UINTPTR heap_id)
{
TheFixedHeapType *th = (TheFixedHeapType *) heap_id;
if (th)
{
delete th;
}
}
// alloc & free
void *
hl_fixed_alloc (UINTPTR heap_id, size_t sz)
{
TheFixedHeapType *th = (TheFixedHeapType *) heap_id;
if (th)
{
return th->malloc (sz);
}
return NULL;
}
void
hl_fixed_free (UINTPTR heap_id, void *ptr)
{
TheFixedHeapType *th = (TheFixedHeapType *) heap_id;
if (th)
{
th->free (ptr);
}
}
//
// Obstack Heap
//
// class definition
class TheObstackHeapType :
public SizeHeap<ObstackHeap<0,MallocHeap> > {};
// initialize & finalize
UINTPTR
hl_register_ostk_heap (int chunk_size)
{
TheObstackHeapType *th = new TheObstackHeapType;
if (th)
{
th->reset (chunk_size);
return (UINTPTR) th;
}
return 0;
}
void
hl_unregister_ostk_heap (UINTPTR heap_id)
{
TheObstackHeapType *th = (TheObstackHeapType *) heap_id;
if (th)
{
delete th;
}
}
// alloc & free
void *
hl_ostk_alloc (UINTPTR heap_id, size_t sz)
{
TheObstackHeapType *th = (TheObstackHeapType *) heap_id;
if (th)
{
return th->malloc (sz);
}
return NULL;
}
void
hl_ostk_free (UINTPTR heap_id, void *ptr)
{
TheObstackHeapType *th = (TheObstackHeapType *) heap_id;
if (th)
{
th->free (ptr);
}
}
| {
"pile_set_name": "Github"
} |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.stdext
import org.rust.cargo.project.model.CargoProjectsService
import java.lang.annotation.Inherited
/**
* Like [org.rust.MockEdition], but makes the test run 2 times with both edition
*
* @see CargoProjectsService.setEdition
*/
@Inherited
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class BothEditions
| {
"pile_set_name": "Github"
} |
import {css} from '@emotion/core';
const textStyles = () => css`
/* stylelint-disable no-descending-specificity */
h1,
h2,
h3,
h4,
h5,
h6,
p,
ul,
ol,
table,
dl,
blockquote,
form,
pre,
.auto-select-text,
.section,
[class^='highlight-'] {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
h1,
h2,
h3,
h4,
h5,
h6 {
line-height: 1.2;
}
p,
ul,
ol,
blockquote {
line-height: 1.5;
}
h1 {
font-size: 3.2rem;
}
h2 {
font-size: 2.8rem;
}
h3 {
font-size: 2.4rem;
}
h4 {
font-size: 2rem;
}
h5 {
font-size: 1.6rem;
}
h6 {
font-size: 1.4rem;
}
pre {
word-break: break-all;
white-space: pre-wrap;
}
/* stylelint-enable */
`;
export default textStyles;
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Tests\Twig;
use App\Configuration\ThemeConfiguration;
use App\Entity\Configuration;
use App\Tests\Configuration\TestConfigLoader;
use App\Twig\TitleExtension;
use PHPUnit\Framework\TestCase;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\TwigFunction;
/**
* @covers \App\Twig\TitleExtension
*/
class TitleExtensionTest extends TestCase
{
protected function getSut(string $title = null): TitleExtension
{
$translator = $this->getMockBuilder(TranslatorInterface::class)->getMock();
$translator->method('trans')->willReturn('foo');
$configs = [
(new Configuration())->setName('theme.branding.title')->setValue($title)
];
$loader = new TestConfigLoader($configs);
$configuration = new ThemeConfiguration($loader, ['branding' => ['title' => null]]);
return new TitleExtension($translator, $configuration);
}
public function testGetFunctions()
{
$functions = ['get_title'];
$sut = $this->getSut();
$twigFunctions = $sut->getFunctions();
$this->assertCount(\count($functions), $twigFunctions);
$i = 0;
/** @var TwigFunction $function */
foreach ($twigFunctions as $function) {
$this->assertInstanceOf(TwigFunction::class, $function);
$this->assertEquals($functions[$i++], $function->getName());
}
}
public function testGetTitle()
{
$sut = $this->getSut();
$this->assertEquals('Kimai – foo', $sut->generateTitle());
$this->assertEquals('sdfsdf | Kimai – foo', $sut->generateTitle('sdfsdf | '));
$this->assertEquals('<b>Kimai</b> ... foo', $sut->generateTitle('<b>', '</b> ... '));
$this->assertEquals('Kimai | foo', $sut->generateTitle(null, ' | '));
}
public function testGetBrandedTitle()
{
$sut = $this->getSut('MyCompany');
$this->assertEquals('MyCompany – foo', $sut->generateTitle());
$this->assertEquals('sdfsdf | MyCompany – foo', $sut->generateTitle('sdfsdf | '));
$this->assertEquals('<b>MyCompany</b> ... foo', $sut->generateTitle('<b>', '</b> ... '));
$this->assertEquals('MyCompany | foo', $sut->generateTitle(null, ' | '));
}
}
| {
"pile_set_name": "Github"
} |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class Question(object):
QUESTION_XML_TEMPLATE = """<Question><QuestionIdentifier>%s</QuestionIdentifier>%s<IsRequired>%s</IsRequired>%s%s</Question>"""
DISPLAY_NAME_XML_TEMPLATE = """<DisplayName>%s</DisplayName>"""
def __init__(self, identifier, content, answer_spec, is_required=False, display_name=None): #amount=0.0, currency_code='USD'):
self.identifier = identifier
self.content = content
self.answer_spec = answer_spec
self.is_required = is_required
self.display_name = display_name
def get_as_params(self, label='Question', identifier=None):
if identifier is None:
raise ValueError("identifier (QuestionIdentifier) is required per MTurk spec.")
return { label : self.get_as_xml() }
def get_as_xml(self):
# add the display name if required
display_name_xml = ''
if self.display_name:
display_name_xml = self.DISPLAY_NAME_XML_TEMPLATE %(self.display_name)
ret = Question.QUESTION_XML_TEMPLATE % (self.identifier,
display_name_xml,
str(self.is_required).lower(),
self.content.get_as_xml(),
self.answer_spec.get_as_xml())
return ret
class ExternalQuestion(object):
EXTERNAL_QUESTIONFORM_SCHEMA_LOCATION = "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd"
EXTERNAL_QUESTION_XML_TEMPLATE = """<ExternalQuestion xmlns="%s"><ExternalURL>%s</ExternalURL><FrameHeight>%s</FrameHeight></ExternalQuestion>"""
def __init__(self, external_url, frame_height):
self.external_url = external_url
self.frame_height = frame_height
def get_as_params(self, label='ExternalQuestion'):
return { label : self.get_as_xml() }
def get_as_xml(self):
ret = ExternalQuestion.EXTERNAL_QUESTION_XML_TEMPLATE % (ExternalQuestion.EXTERNAL_QUESTIONFORM_SCHEMA_LOCATION,
self.external_url,
self.frame_height)
return ret
class OrderedContent(object):
def __init__(self):
self.items = []
def append(self, field, value):
"Expects field type and value"
self.items.append((field, value))
def get_binary_xml(self, field, value):
return """
<Binary>
<MimeType>
<Type>%s</Type>
<SubType>%s</SubType>
</MimeType>
<DataURL>%s</DataURL>
<AltText>%s</AltText>
</Binary>""" % (value['binary_type'],
value['binary_subtype'],
value['binary'],
value['binary_alttext'])
def get_application_xml(self, field, value):
raise NotImplementedError("Application question content is not yet supported.")
def get_as_xml(self):
default_handler = lambda f,v: '<%s>%s</%s>' % (f,v,f)
bulleted_list_handler = lambda _,list: '<List>%s</List>' % ''.join([('<ListItem>%s</ListItem>' % item) for item in list])
formatted_content_handler = lambda _,content: "<FormattedContent><![CDATA[%s]]></FormattedContent>" % content
application_handler = self.get_application_xml
binary_handler = self.get_binary_xml
children = ''
for (field,value) in self.items:
handler = default_handler
if field == 'List':
handler = bulleted_list_handler
elif field == 'Application':
handler = application_handler
elif field == 'Binary':
handler = binary_handler
elif field == 'FormattedContent':
handler = formatted_content_handler
children = children + handler(field, value)
return children
class Overview(object):
OVERVIEW_XML_TEMPLATE = """<Overview>%s</Overview>"""
def __init__(self):
self.ordered_content = OrderedContent()
def append(self, field, value):
self.ordered_content.append(field,value)
def get_as_params(self, label='Overview'):
return { label : self.get_as_xml() }
def get_as_xml(self):
ret = Overview.OVERVIEW_XML_TEMPLATE % (self.ordered_content.get_as_xml())
return ret
class QuestionForm(object):
QUESTIONFORM_SCHEMA_LOCATION = "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd"
QUESTIONFORM_XML_TEMPLATE = """<QuestionForm xmlns="%s">%s</QuestionForm>""" # % (ns, questions_xml)
def __init__(self, questions=None, overview=None):
if questions is None or type(questions) is not list:
raise ValueError("Must pass a list of Question instances to QuestionForm constructor")
else:
self.questions = questions
self.overview = overview
def get_as_xml(self):
if self.overview:
overview_xml = self.overview.get_as_xml()
questions_xml = "".join([q.get_as_xml() for q in self.questions])
qf_xml = overview_xml + questions_xml
return QuestionForm.QUESTIONFORM_XML_TEMPLATE % (QuestionForm.QUESTIONFORM_SCHEMA_LOCATION, qf_xml)
#def startElement(self, name, attrs, connection):
# return None
#
#def endElement(self, name, value, connection):
#
# #if name == 'Amount':
# # self.amount = float(value)
# #elif name == 'CurrencyCode':
# # self.currency_code = value
# #elif name == 'FormattedPrice':
# # self.formatted_price = value
#
# pass # What's this method for? I don't get it.
class QuestionContent(object):
QUESTIONCONTENT_XML_TEMPLATE = """<QuestionContent>%s</QuestionContent>"""
def __init__(self):
self.ordered_content = OrderedContent()
def append(self, field, value):
self.ordered_content.append(field,value)
def get_as_xml(self):
ret = QuestionContent.QUESTIONCONTENT_XML_TEMPLATE % (self.ordered_content.get_as_xml())
return ret
class AnswerSpecification(object):
ANSWERSPECIFICATION_XML_TEMPLATE = """<AnswerSpecification>%s</AnswerSpecification>"""
def __init__(self, spec):
self.spec = spec
def get_as_xml(self):
values = () # TODO
return AnswerSpecification.ANSWERSPECIFICATION_XML_TEMPLATE % self.spec.get_as_xml()
class FreeTextAnswer(object):
FREETEXTANSWER_XML_TEMPLATE = """<FreeTextAnswer>%s%s</FreeTextAnswer>""" # (constraints, default)
FREETEXTANSWER_CONSTRAINTS_XML_TEMPLATE = """<Constraints>%s%s%s</Constraints>""" # (is_numeric_xml, length_xml, regex_xml)
FREETEXTANSWER_LENGTH_XML_TEMPLATE = """<Length %s %s />""" # (min_length_attr, max_length_attr)
FREETEXTANSWER_ISNUMERIC_XML_TEMPLATE = """<IsNumeric %s %s />""" # (min_value_attr, max_value_attr)
FREETEXTANSWER_DEFAULTTEXT_XML_TEMPLATE = """<DefaultText>%s</DefaultText>""" # (default)
def __init__(self, default=None, min_length=None, max_length=None, is_numeric=False, min_value=None, max_value=None, format_regex=None):
self.default = default
self.min_length = min_length
self.max_length = max_length
self.is_numeric = is_numeric
self.min_value = min_value
self.max_value = max_value
self.format_regex = format_regex
def get_as_xml(self):
is_numeric_xml = ""
if self.is_numeric:
min_value_attr = ""
max_value_attr = ""
if self.min_value:
min_value_attr = """minValue="%d" """ % self.min_value
if self.max_value:
max_value_attr = """maxValue="%d" """ % self.max_value
is_numeric_xml = FreeTextAnswer.FREETEXTANSWER_ISNUMERIC_XML_TEMPLATE % (min_value_attr, max_value_attr)
length_xml = ""
if self.min_length or self.max_length:
min_length_attr = ""
max_length_attr = ""
if self.min_length:
min_length_attr = """minLength="%d" """
if self.max_length:
max_length_attr = """maxLength="%d" """
length_xml = FreeTextAnswer.FREETEXTANSWER_LENGTH_XML_TEMPLATE % (min_length_attr, max_length_attr)
regex_xml = ""
if self.format_regex:
format_regex_attribs = '''regex="%s"''' %self.format_regex['regex']
error_text = self.format_regex.get('error_text', None)
if error_text:
format_regex_attribs += ' errorText="%s"' %error_text
flags = self.format_regex.get('flags', None)
if flags:
format_regex_attribs += ' flags="%s"' %flags
regex_xml = """<AnswerFormatRegex %s/>""" %format_regex_attribs
constraints_xml = ""
if is_numeric_xml or length_xml or regex_xml:
constraints_xml = FreeTextAnswer.FREETEXTANSWER_CONSTRAINTS_XML_TEMPLATE % (is_numeric_xml, length_xml, regex_xml)
default_xml = ""
if self.default is not None:
default_xml = FreeTextAnswer.FREETEXTANSWER_DEFAULTTEXT_XML_TEMPLATE % self.default
return FreeTextAnswer.FREETEXTANSWER_XML_TEMPLATE % (constraints_xml, default_xml)
class FileUploadAnswer(object):
FILEUPLOADANSWER_XML_TEMLPATE = """<FileUploadAnswer><MinFileSizeInBytes>%d</MinFileSizeInBytes><MaxFileSizeInBytes>%d</MaxFileSizeInBytes></FileUploadAnswer>""" # (min, max)
DEFAULT_MIN_SIZE = 1024 # 1K (completely arbitrary!)
DEFAULT_MAX_SIZE = 5 * 1024 * 1024 # 5MB (completely arbitrary!)
def __init__(self, min=None, max=None):
self.min = min
self.max = max
if self.min is None:
self.min = FileUploadAnswer.DEFAULT_MIN_SIZE
if self.max is None:
self.max = FileUploadAnswer.DEFAULT_MAX_SIZE
def get_as_xml(self):
return FileUploadAnswer.FILEUPLOADANSWER_XML_TEMLPATE % (self.min, self.max)
class SelectionAnswer(object):
"""
A class to generate SelectionAnswer XML data structures.
Does not yet implement Binary selection options.
"""
SELECTIONANSWER_XML_TEMPLATE = """<SelectionAnswer>%s%s<Selections>%s</Selections></SelectionAnswer>""" # % (count_xml, style_xml, selections_xml)
SELECTION_XML_TEMPLATE = """<Selection><SelectionIdentifier>%s</SelectionIdentifier>%s</Selection>""" # (identifier, value_xml)
SELECTION_VALUE_XML_TEMPLATE = """<%s>%s</%s>""" # (type, value, type)
STYLE_XML_TEMPLATE = """<StyleSuggestion>%s</StyleSuggestion>""" # (style)
MIN_SELECTION_COUNT_XML_TEMPLATE = """<MinSelectionCount>%s</MinSelectionCount>""" # count
MAX_SELECTION_COUNT_XML_TEMPLATE = """<MaxSelectionCount>%s</MaxSelectionCount>""" # count
ACCEPTED_STYLES = ['radiobutton', 'dropdown', 'checkbox', 'list', 'combobox', 'multichooser']
OTHER_SELECTION_ELEMENT_NAME = 'OtherSelection'
def __init__(self, min=1, max=1, style=None, selections=None, type='text', other=False):
if style is not None:
if style in SelectionAnswer.ACCEPTED_STYLES:
self.style_suggestion = style
else:
raise ValueError("style '%s' not recognized; should be one of %s" % (style, ', '.join(SelectionAnswer.ACCEPTED_STYLES)))
else:
self.style_suggestion = None
if selections is None:
raise ValueError("SelectionAnswer.__init__(): selections must be a non-empty list of (content, identifier) tuples")
else:
self.selections = selections
self.min_selections = min
self.max_selections = max
assert len(selections) >= self.min_selections, "# of selections is less than minimum of %d" % self.min_selections
#assert len(selections) <= self.max_selections, "# of selections exceeds maximum of %d" % self.max_selections
self.type = type
self.other = other
def get_as_xml(self):
xml = ""
if self.type == 'text':
TYPE_TAG = "Text"
elif self.type == 'binary':
TYPE_TAG = "Binary"
else:
raise ValueError("illegal type: %s; must be either 'text' or 'binary'" % str(self.type))
# build list of <Selection> elements
selections_xml = ""
for tpl in self.selections:
value_xml = SelectionAnswer.SELECTION_VALUE_XML_TEMPLATE % (TYPE_TAG, tpl[0], TYPE_TAG)
selection_xml = SelectionAnswer.SELECTION_XML_TEMPLATE % (tpl[1], value_xml)
selections_xml += selection_xml
if self.other:
# add OtherSelection element as xml if available
if hasattr(self.other, 'get_as_xml'):
assert type(self.other) == FreeTextAnswer, 'OtherSelection can only be a FreeTextAnswer'
selections_xml += self.other.get_as_xml().replace('FreeTextAnswer', 'OtherSelection')
else:
selections_xml += "<OtherSelection />"
if self.style_suggestion is not None:
style_xml = SelectionAnswer.STYLE_XML_TEMPLATE % self.style_suggestion
else:
style_xml = ""
if self.style_suggestion != 'radiobutton':
count_xml = SelectionAnswer.MIN_SELECTION_COUNT_XML_TEMPLATE %self.min_selections
count_xml += SelectionAnswer.MAX_SELECTION_COUNT_XML_TEMPLATE %self.max_selections
else:
count_xml = ""
ret = SelectionAnswer.SELECTIONANSWER_XML_TEMPLATE % (count_xml, style_xml, selections_xml)
# return XML
return ret
| {
"pile_set_name": "Github"
} |
if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR})
message(FATAL_ERROR "Prevented in-tree built. Please create a build directory outside of the SDL source code and call cmake from there")
endif()
cmake_minimum_required(VERSION 2.8.11)
project(SDL2 C CXX)
# !!! FIXME: this should probably do "MACOSX_RPATH ON" as a target property
# !!! FIXME: for the SDL2 shared library (so you get an
# !!! FIXME: install_name ("soname") of "@rpath/libSDL-whatever.dylib"
# !!! FIXME: instead of "/usr/local/lib/libSDL-whatever.dylib"), but I'm
# !!! FIXME: punting for now and leaving the existing behavior. Until this
# !!! FIXME: properly resolved, this line silences a warning in CMake 3.0+.
# !!! FIXME: remove it and this comment entirely once the problem is
# !!! FIXME: properly resolved.
#cmake_policy(SET CMP0042 OLD)
include(CheckFunctionExists)
include(CheckLibraryExists)
include(CheckIncludeFiles)
include(CheckIncludeFile)
include(CheckSymbolExists)
include(CheckCSourceCompiles)
include(CheckCSourceRuns)
include(CheckCCompilerFlag)
include(CheckTypeSize)
include(CheckStructHasMember)
include(CMakeDependentOption)
include(FindPkgConfig)
include(GNUInstallDirs)
set(CMAKE_MODULE_PATH "${SDL2_SOURCE_DIR}/cmake")
include(${SDL2_SOURCE_DIR}/cmake/macros.cmake)
include(${SDL2_SOURCE_DIR}/cmake/sdlchecks.cmake)
# General settings
# Edit include/SDL_version.h and change the version, then:
# SDL_MICRO_VERSION += 1;
# SDL_INTERFACE_AGE += 1;
# SDL_BINARY_AGE += 1;
# if any functions have been added, set SDL_INTERFACE_AGE to 0.
# if backwards compatibility has been broken,
# set SDL_BINARY_AGE and SDL_INTERFACE_AGE to 0.
set(SDL_MAJOR_VERSION 2)
set(SDL_MINOR_VERSION 0)
set(SDL_MICRO_VERSION 10)
set(SDL_INTERFACE_AGE 0)
set(SDL_BINARY_AGE 10)
set(SDL_VERSION "${SDL_MAJOR_VERSION}.${SDL_MINOR_VERSION}.${SDL_MICRO_VERSION}")
# the following should match the versions in Xcode project file:
set(DYLIB_CURRENT_VERSION 10.0.0)
set(DYLIB_COMPATIBILITY_VERSION 1.0.0)
# Set defaults preventing destination file conflicts
set(SDL_CMAKE_DEBUG_POSTFIX "d"
CACHE STRING "Name suffix for debug builds")
mark_as_advanced(CMAKE_IMPORT_LIBRARY_SUFFIX SDL_CMAKE_DEBUG_POSTFIX)
# Calculate a libtool-like version number
math(EXPR LT_CURRENT "${SDL_MICRO_VERSION} - ${SDL_INTERFACE_AGE}")
math(EXPR LT_AGE "${SDL_BINARY_AGE} - ${SDL_INTERFACE_AGE}")
math(EXPR LT_MAJOR "${LT_CURRENT}- ${LT_AGE}")
set(LT_REVISION "${SDL_INTERFACE_AGE}")
set(LT_RELEASE "${SDL_MAJOR_VERSION}.${SDL_MINOR_VERSION}")
set(LT_VERSION "${LT_MAJOR}.${LT_AGE}.${LT_REVISION}")
#message(STATUS "${LT_VERSION} :: ${LT_AGE} :: ${LT_REVISION} :: ${LT_CURRENT} :: ${LT_RELEASE}")
# General settings & flags
set(LIBRARY_OUTPUT_DIRECTORY "build")
# Check for 64 or 32 bit
set(SIZEOF_VOIDP ${CMAKE_SIZEOF_VOID_P})
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(ARCH_64 TRUE)
set(PROCESSOR_ARCH "x64")
else()
set(ARCH_64 FALSE)
set(PROCESSOR_ARCH "x86")
endif()
set(LIBNAME SDL2)
if(NOT LIBTYPE)
set(LIBTYPE SHARED)
endif()
# Get the platform
if(WIN32)
if(NOT WINDOWS)
set(WINDOWS TRUE)
endif()
elseif(UNIX AND NOT APPLE)
if(CMAKE_SYSTEM_NAME MATCHES ".*Linux")
set(LINUX TRUE)
elseif(CMAKE_SYSTEM_NAME MATCHES "kFreeBSD.*")
set(FREEBSD TRUE)
elseif(CMAKE_SYSTEM_NAME MATCHES "kNetBSD.*|NetBSD.*")
set(NETBSD TRUE)
elseif(CMAKE_SYSTEM_NAME MATCHES "kOpenBSD.*|OpenBSD.*")
set(OPENBSD TRUE)
elseif(CMAKE_SYSTEM_NAME MATCHES ".*GNU.*")
set(GNU TRUE)
elseif(CMAKE_SYSTEM_NAME MATCHES ".*BSDI.*")
set(BSDI TRUE)
elseif(CMAKE_SYSTEM_NAME MATCHES "DragonFly.*|FreeBSD")
set(FREEBSD TRUE)
elseif(CMAKE_SYSTEM_NAME MATCHES "SYSV5.*")
set(SYSV5 TRUE)
elseif(CMAKE_SYSTEM_NAME MATCHES "Solaris.*")
set(SOLARIS TRUE)
elseif(CMAKE_SYSTEM_NAME MATCHES "HP-UX.*")
set(HPUX TRUE)
elseif(CMAKE_SYSTEM_NAME MATCHES "AIX.*")
set(AIX TRUE)
elseif(CMAKE_SYSTEM_NAME MATCHES "Minix.*")
set(MINIX TRUE)
endif()
elseif(APPLE)
if(CMAKE_SYSTEM_NAME MATCHES ".*Darwin.*")
set(DARWIN TRUE)
elseif(CMAKE_SYSTEM_NAME MATCHES ".*MacOS.*")
set(MACOSX TRUE)
endif()
# TODO: iOS?
elseif(CMAKE_SYSTEM_NAME MATCHES "BeOS.*")
message_error("BeOS support has been removed as of SDL 2.0.2.")
elseif(CMAKE_SYSTEM_NAME MATCHES "Haiku.*")
set(HAIKU TRUE)
endif()
# Don't mistake osx for unix
if(UNIX AND NOT APPLE)
set(UNIX_SYS ON)
else()
set(UNIX_SYS OFF)
endif()
if(UNIX OR APPLE)
set(UNIX_OR_MAC_SYS ON)
else()
set(UNIX_OR_MAC_SYS OFF)
endif()
if (UNIX_OR_MAC_SYS AND NOT EMSCRIPTEN) # JavaScript does not yet have threading support, so disable pthreads when building for Emscripten.
set(SDL_PTHREADS_ENABLED_BY_DEFAULT ON)
else()
set(SDL_PTHREADS_ENABLED_BY_DEFAULT OFF)
endif()
# Default option knobs
if(APPLE OR ARCH_64)
if(NOT "${CMAKE_OSX_ARCHITECTURES}" MATCHES "arm")
set(OPT_DEF_SSEMATH ON)
endif()
endif()
if(UNIX OR MINGW OR MSYS)
set(OPT_DEF_LIBC ON)
endif()
# The hidraw support doesn't catch Xbox, PS4 and Nintendo controllers,
# so we'll just use libusb when it's available. Except that libusb
# requires root permissions to open devices, so that's not generally
# useful, and we'll disable this by default on Unix. Windows and macOS
# can use it without root access, though, so enable by default there.
if(WINDOWS OR APPLE OR ANDROID)
set(HIDAPI_SKIP_LIBUSB TRUE)
else()
set(HIDAPI_SKIP_LIBUSB FALSE)
endif()
if (HIDAPI_SKIP_LIBUSB)
set(OPT_DEF_HIDAPI ON)
endif()
# Compiler info
if(CMAKE_COMPILER_IS_GNUCC)
set(USE_GCC TRUE)
set(OPT_DEF_ASM TRUE)
elseif(CMAKE_C_COMPILER_ID MATCHES "Clang")
set(USE_CLANG TRUE)
set(OPT_DEF_ASM TRUE)
elseif(MSVC_VERSION GREATER 1400) # VisualStudio 8.0+
set(OPT_DEF_ASM TRUE)
#set(CMAKE_C_FLAGS "/ZI /WX- /
else()
set(OPT_DEF_ASM FALSE)
endif()
if(USE_GCC OR USE_CLANG)
set(OPT_DEF_GCC_ATOMICS ON)
endif()
# Default flags, if not set otherwise
if("$ENV{CFLAGS}" STREQUAL "")
if(CMAKE_BUILD_TYPE STREQUAL "")
if(USE_GCC OR USE_CLANG)
set(CMAKE_C_FLAGS "-g -O3")
endif()
endif()
else()
set(CMAKE_C_FLAGS "$ENV{CFLAGS}")
list(APPEND EXTRA_CFLAGS "$ENV{CFLAGS}")
endif()
if(NOT ("$ENV{CFLAGS}" STREQUAL "")) # Hackish, but does the trick on Win32
list(APPEND EXTRA_LDFLAGS "$ENV{LDFLAGS}")
endif()
if(MSVC)
option(FORCE_STATIC_VCRT "Force /MT for static VC runtimes" OFF)
if(FORCE_STATIC_VCRT)
foreach(flag_var
CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE
CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO)
if(${flag_var} MATCHES "/MD")
string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
endif()
endforeach()
endif()
# Make sure /RTC1 is disabled, otherwise it will use functions from the CRT
foreach(flag_var
CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE
CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO)
string(REGEX REPLACE "/RTC(su|[1su])" "" ${flag_var} "${${flag_var}}")
endforeach(flag_var)
endif()
# Those are used for pkg-config and friends, so that the SDL2.pc, sdl2-config,
# etc. are created correctly.
set(SDL_LIBS "-lSDL2")
set(SDL_CFLAGS "")
# When building shared lib for Windows with MinGW,
# avoid the DLL having a "lib" prefix
if(WINDOWS)
set(CMAKE_SHARED_LIBRARY_PREFIX "")
endif()
# Emscripten toolchain has a nonempty default value for this, and the checks
# in this file need to change that, so remember the original value, and
# restore back to that afterwards. For check_function_exists() to work in
# Emscripten, this value must be at its default value.
set(ORIG_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
if(CYGWIN)
# We build SDL on cygwin without the UNIX emulation layer
include_directories("-I/usr/include/mingw")
set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -mno-cygwin")
check_c_source_compiles("int main(int argc, char **argv) {}"
HAVE_GCC_NO_CYGWIN)
set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
if(HAVE_GCC_NO_CYGWIN)
list(APPEND EXTRA_LDFLAGS "-mno-cygwin")
list(APPEND SDL_LIBS "-mno-cygwin")
endif()
set(SDL_CFLAGS "${SDL_CFLAGS} -I/usr/include/mingw")
endif()
add_definitions(-DUSING_GENERATED_CONFIG_H)
# General includes
include_directories(${SDL2_BINARY_DIR}/include ${SDL2_SOURCE_DIR}/include)
if(USE_GCC OR USE_CLANG)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -idirafter ${SDL2_SOURCE_DIR}/src/video/khronos")
else()
include_directories(${SDL2_SOURCE_DIR}/src/video/khronos)
endif()
# All these ENABLED_BY_DEFAULT vars will default to ON if not specified, so
# you only need to have a platform override them if they are disabling.
set(OPT_DEF_ASM TRUE)
if(EMSCRIPTEN)
# Set up default values for the currently supported set of subsystems:
# Emscripten/Javascript does not have assembly support, a dynamic library
# loading architecture, low-level CPU inspection or multithreading.
set(OPT_DEF_ASM FALSE)
set(SDL_SHARED_ENABLED_BY_DEFAULT OFF)
set(SDL_ATOMIC_ENABLED_BY_DEFAULT OFF)
set(SDL_THREADS_ENABLED_BY_DEFAULT OFF)
set(SDL_LOADSO_ENABLED_BY_DEFAULT OFF)
set(SDL_CPUINFO_ENABLED_BY_DEFAULT OFF)
set(SDL_DLOPEN_ENABLED_BY_DEFAULT OFF)
endif()
# When defined, respect CMake's BUILD_SHARED_LIBS setting:
set(SDL_STATIC_ENABLED_BY_DEFAULT ON)
if (NOT DEFINED SDL_SHARED_ENABLED_BY_DEFAULT)
# ...unless decided already (as for EMSCRIPTEN)
set(SDL_SHARED_ENABLED_BY_DEFAULT OFF)
if (NOT DEFINED BUILD_SHARED_LIBS)
# No preference? Build both, just like the AC/AM configure
set(SDL_SHARED_ENABLED_BY_DEFAULT ON)
elseif (BUILD_SHARED_LIBS)
# In this case, we assume the user wants a shared lib and don't build
# the static one
set(SDL_SHARED_ENABLED_BY_DEFAULT ON)
set(SDL_STATIC_ENABLED_BY_DEFAULT OFF)
endif()
endif()
set(SDL_SUBSYSTEMS
Atomic Audio Video Render Events Joystick Haptic Power Threads Timers
File Loadso CPUinfo Filesystem Dlopen Sensor)
foreach(_SUB ${SDL_SUBSYSTEMS})
string(TOUPPER ${_SUB} _OPT)
if (NOT DEFINED SDL_${_OPT}_ENABLED_BY_DEFAULT)
set(SDL_${_OPT}_ENABLED_BY_DEFAULT ON)
endif()
option(SDL_${_OPT} "Enable the ${_SUB} subsystem" ${SDL_${_OPT}_ENABLED_BY_DEFAULT})
endforeach()
option_string(ASSERTIONS "Enable internal sanity checks (auto/disabled/release/enabled/paranoid)" "auto")
#set_option(DEPENDENCY_TRACKING "Use gcc -MMD -MT dependency tracking" ON)
set_option(LIBC "Use the system C library" ${OPT_DEF_LIBC})
set_option(GCC_ATOMICS "Use gcc builtin atomics" ${OPT_DEF_GCC_ATOMICS})
set_option(ASSEMBLY "Enable assembly routines" ${OPT_DEF_ASM})
set_option(SSEMATH "Allow GCC to use SSE floating point math" ${OPT_DEF_SSEMATH})
set_option(MMX "Use MMX assembly routines" ${OPT_DEF_ASM})
set_option(3DNOW "Use 3Dnow! MMX assembly routines" ${OPT_DEF_ASM})
set_option(SSE "Use SSE assembly routines" ${OPT_DEF_ASM})
set_option(SSE2 "Use SSE2 assembly routines" ${OPT_DEF_SSEMATH})
set_option(SSE3 "Use SSE3 assembly routines" ${OPT_DEF_SSEMATH})
set_option(ALTIVEC "Use Altivec assembly routines" ${OPT_DEF_ASM})
set_option(DISKAUDIO "Support the disk writer audio driver" ON)
set_option(DUMMYAUDIO "Support the dummy audio driver" ON)
set_option(VIDEO_DIRECTFB "Use DirectFB video driver" OFF)
dep_option(DIRECTFB_SHARED "Dynamically load directfb support" ON "VIDEO_DIRECTFB" OFF)
set_option(VIDEO_DUMMY "Use dummy video driver" ON)
set_option(VIDEO_OPENGL "Include OpenGL support" ON)
set_option(VIDEO_OPENGLES "Include OpenGL ES support" ON)
set_option(PTHREADS "Use POSIX threads for multi-threading" ${SDL_PTHREADS_ENABLED_BY_DEFAULT})
dep_option(PTHREADS_SEM "Use pthread semaphores" ON "PTHREADS" OFF)
set_option(SDL_DLOPEN "Use dlopen for shared object loading" ${SDL_DLOPEN_ENABLED_BY_DEFAULT})
set_option(OSS "Support the OSS audio API" ${UNIX_SYS})
set_option(ALSA "Support the ALSA audio API" ${UNIX_SYS})
dep_option(ALSA_SHARED "Dynamically load ALSA audio support" ON "ALSA" OFF)
set_option(JACK "Support the JACK audio API" ${UNIX_SYS})
dep_option(JACK_SHARED "Dynamically load JACK audio support" ON "JACK" OFF)
set_option(ESD "Support the Enlightened Sound Daemon" ${UNIX_SYS})
dep_option(ESD_SHARED "Dynamically load ESD audio support" ON "ESD" OFF)
set_option(PULSEAUDIO "Use PulseAudio" ${UNIX_SYS})
dep_option(PULSEAUDIO_SHARED "Dynamically load PulseAudio support" ON "PULSEAUDIO" OFF)
set_option(ARTS "Support the Analog Real Time Synthesizer" ${UNIX_SYS})
dep_option(ARTS_SHARED "Dynamically load aRts audio support" ON "ARTS" OFF)
set_option(NAS "Support the NAS audio API" ${UNIX_SYS})
set_option(NAS_SHARED "Dynamically load NAS audio API" ${UNIX_SYS})
set_option(SNDIO "Support the sndio audio API" ${UNIX_SYS})
set_option(FUSIONSOUND "Use FusionSound audio driver" OFF)
dep_option(FUSIONSOUND_SHARED "Dynamically load fusionsound audio support" ON "FUSIONSOUND" OFF)
set_option(LIBSAMPLERATE "Use libsamplerate for audio rate conversion" ${UNIX_SYS})
dep_option(LIBSAMPLERATE_SHARED "Dynamically load libsamplerate" ON "LIBSAMPLERATE" OFF)
set_option(RPATH "Use an rpath when linking SDL" ${UNIX_SYS})
set_option(CLOCK_GETTIME "Use clock_gettime() instead of gettimeofday()" OFF)
set_option(INPUT_TSLIB "Use the Touchscreen library for input" ${UNIX_SYS})
set_option(VIDEO_X11 "Use X11 video driver" ${UNIX_SYS})
set_option(VIDEO_WAYLAND "Use Wayland video driver" ${UNIX_SYS})
dep_option(WAYLAND_SHARED "Dynamically load Wayland support" ON "VIDEO_WAYLAND" OFF)
dep_option(VIDEO_WAYLAND_QT_TOUCH "QtWayland server support for Wayland video driver" ON "VIDEO_WAYLAND" OFF)
set_option(VIDEO_RPI "Use Raspberry Pi video driver" ${UNIX_SYS})
dep_option(X11_SHARED "Dynamically load X11 support" ON "VIDEO_X11" OFF)
set(SDL_X11_OPTIONS Xcursor Xinerama XInput Xrandr Xscrnsaver XShape Xvm)
foreach(_SUB ${SDL_X11_OPTIONS})
string(TOUPPER "VIDEO_X11_${_SUB}" _OPT)
dep_option(${_OPT} "Enable ${_SUB} support" ON "VIDEO_X11" OFF)
endforeach()
set_option(VIDEO_COCOA "Use Cocoa video driver" ${APPLE})
set_option(DIRECTX "Use DirectX for Windows audio/video" ${WINDOWS})
set_option(WASAPI "Use the Windows WASAPI audio driver" ${WINDOWS})
set_option(RENDER_D3D "Enable the Direct3D render driver" ${WINDOWS})
set_option(VIDEO_VIVANTE "Use Vivante EGL video driver" ${UNIX_SYS})
dep_option(VIDEO_VULKAN "Enable Vulkan support" ON "ANDROID OR APPLE OR LINUX OR WINDOWS" OFF)
set_option(VIDEO_KMSDRM "Use KMS DRM video driver" ${UNIX_SYS})
dep_option(KMSDRM_SHARED "Dynamically load KMS DRM support" ON "VIDEO_KMSDRM" OFF)
option_string(BACKGROUNDING_SIGNAL "number to use for magic backgrounding signal or 'OFF'" "OFF")
option_string(FOREGROUNDING_SIGNAL "number to use for magic foregrounding signal or 'OFF'" "OFF")
set_option(HIDAPI "Use HIDAPI for low level joystick drivers" ${OPT_DEF_HIDAPI})
set(SDL_SHARED ${SDL_SHARED_ENABLED_BY_DEFAULT} CACHE BOOL "Build a shared version of the library")
set(SDL_STATIC ${SDL_STATIC_ENABLED_BY_DEFAULT} CACHE BOOL "Build a static version of the library")
dep_option(SDL_STATIC_PIC "Static version of the library should be built with Position Independent Code" OFF "SDL_STATIC" OFF)
set_option(SDL_TEST "Build the test directory" OFF)
# General source files
file(GLOB SOURCE_FILES
${SDL2_SOURCE_DIR}/src/*.c
${SDL2_SOURCE_DIR}/src/atomic/*.c
${SDL2_SOURCE_DIR}/src/audio/*.c
${SDL2_SOURCE_DIR}/src/cpuinfo/*.c
${SDL2_SOURCE_DIR}/src/dynapi/*.c
${SDL2_SOURCE_DIR}/src/events/*.c
${SDL2_SOURCE_DIR}/src/file/*.c
${SDL2_SOURCE_DIR}/src/libm/*.c
${SDL2_SOURCE_DIR}/src/render/*.c
${SDL2_SOURCE_DIR}/src/render/*/*.c
${SDL2_SOURCE_DIR}/src/stdlib/*.c
${SDL2_SOURCE_DIR}/src/thread/*.c
${SDL2_SOURCE_DIR}/src/timer/*.c
${SDL2_SOURCE_DIR}/src/video/*.c
${SDL2_SOURCE_DIR}/src/video/yuv2rgb/*.c)
if(ASSERTIONS STREQUAL "auto")
# Do nada - use optimization settings to determine the assertion level
elseif(ASSERTIONS STREQUAL "disabled")
set(SDL_DEFAULT_ASSERT_LEVEL 0)
elseif(ASSERTIONS STREQUAL "release")
set(SDL_DEFAULT_ASSERT_LEVEL 1)
elseif(ASSERTIONS STREQUAL "enabled")
set(SDL_DEFAULT_ASSERT_LEVEL 2)
elseif(ASSERTIONS STREQUAL "paranoid")
set(SDL_DEFAULT_ASSERT_LEVEL 3)
else()
message_error("unknown assertion level")
endif()
set(HAVE_ASSERTIONS ${ASSERTIONS})
if(NOT BACKGROUNDING_SIGNAL STREQUAL "OFF")
add_definitions("-DSDL_BACKGROUNDING_SIGNAL=${BACKGROUNDING_SIGNAL}")
endif()
if(NOT FOREGROUNDING_SIGNAL STREQUAL "OFF")
add_definitions("-DSDL_FOREGROUNDING_SIGNAL=${FOREGROUNDING_SIGNAL}")
endif()
# Compiler option evaluation
if(USE_GCC OR USE_CLANG)
# Check for -Wall first, so later things can override pieces of it.
check_c_compiler_flag(-Wall HAVE_GCC_WALL)
if(HAVE_GCC_WALL)
list(APPEND EXTRA_CFLAGS "-Wall")
if(HAIKU)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-multichar")
endif()
endif()
check_c_compiler_flag(-fno-strict-aliasing HAVE_GCC_NO_STRICT_ALIASING)
if(HAVE_GCC_NO_STRICT_ALIASING)
list(APPEND EXTRA_CFLAGS "-fno-strict-aliasing")
endif()
check_c_compiler_flag(-Wdeclaration-after-statement HAVE_GCC_WDECLARATION_AFTER_STATEMENT)
if(HAVE_GCC_WDECLARATION_AFTER_STATEMENT)
check_c_compiler_flag(-Werror=declaration-after-statement HAVE_GCC_WERROR_DECLARATION_AFTER_STATEMENT)
if(HAVE_GCC_WERROR_DECLARATION_AFTER_STATEMENT)
list(APPEND EXTRA_CFLAGS "-Werror=declaration-after-statement")
endif()
list(APPEND EXTRA_CFLAGS "-Wdeclaration-after-statement")
endif()
if(DEPENDENCY_TRACKING)
check_c_source_compiles("
#if !defined(__GNUC__) || __GNUC__ < 3
#error Dependency tracking requires GCC 3.0 or newer
#endif
int main(int argc, char **argv) { }" HAVE_DEPENDENCY_TRACKING)
endif()
if(GCC_ATOMICS)
check_c_source_compiles("int main(int argc, char **argv) {
int a;
void *x, *y, *z;
__sync_lock_test_and_set(&a, 4);
__sync_lock_test_and_set(&x, y);
__sync_fetch_and_add(&a, 1);
__sync_bool_compare_and_swap(&a, 5, 10);
__sync_bool_compare_and_swap(&x, y, z); }" HAVE_GCC_ATOMICS)
if(NOT HAVE_GCC_ATOMICS)
check_c_source_compiles("int main(int argc, char **argv) {
int a;
__sync_lock_test_and_set(&a, 1);
__sync_lock_release(&a); }" HAVE_GCC_SYNC_LOCK_TEST_AND_SET)
endif()
endif()
set(CMAKE_REQUIRED_FLAGS "-mpreferred-stack-boundary=2")
check_c_source_compiles("int x = 0; int main(int argc, char **argv) {}"
HAVE_GCC_PREFERRED_STACK_BOUNDARY)
set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
set(CMAKE_REQUIRED_FLAGS "-fvisibility=hidden -Werror")
check_c_source_compiles("
#if !defined(__GNUC__) || __GNUC__ < 4
#error SDL only uses visibility attributes in GCC 4 or newer
#endif
int main(int argc, char **argv) {}" HAVE_GCC_FVISIBILITY)
if(HAVE_GCC_FVISIBILITY)
list(APPEND EXTRA_CFLAGS "-fvisibility=hidden")
endif()
set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
check_c_compiler_flag(-Wshadow HAVE_GCC_WSHADOW)
if(HAVE_GCC_WSHADOW)
list(APPEND EXTRA_CFLAGS "-Wshadow")
endif()
if(APPLE)
list(APPEND EXTRA_LDFLAGS "-Wl,-undefined,error")
list(APPEND EXTRA_LDFLAGS "-Wl,-compatibility_version,${DYLIB_COMPATIBILITY_VERSION}")
list(APPEND EXTRA_LDFLAGS "-Wl,-current_version,${DYLIB_CURRENT_VERSION}")
else()
set(CMAKE_REQUIRED_FLAGS "-Wl,--no-undefined")
check_c_compiler_flag("" HAVE_NO_UNDEFINED)
set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
if(HAVE_NO_UNDEFINED)
list(APPEND EXTRA_LDFLAGS "-Wl,--no-undefined")
endif()
endif()
endif()
if(ASSEMBLY)
if(USE_GCC OR USE_CLANG)
set(SDL_ASSEMBLY_ROUTINES 1)
# TODO: Those all seem to be quite GCC specific - needs to be
# reworked for better compiler support
set(HAVE_ASSEMBLY TRUE)
if(MMX)
set(CMAKE_REQUIRED_FLAGS "-mmmx")
check_c_source_compiles("
#ifdef __MINGW32__
#include <_mingw.h>
#ifdef __MINGW64_VERSION_MAJOR
#include <intrin.h>
#else
#include <mmintrin.h>
#endif
#else
#include <mmintrin.h>
#endif
#ifndef __MMX__
#error Assembler CPP flag not enabled
#endif
int main(int argc, char **argv) { }" HAVE_MMX)
if(HAVE_MMX)
list(APPEND EXTRA_CFLAGS "-mmmx")
endif()
set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
endif()
if(3DNOW)
set(CMAKE_REQUIRED_FLAGS "-m3dnow")
check_c_source_compiles("
#include <mm3dnow.h>
#ifndef __3dNOW__
#error Assembler CPP flag not enabled
#endif
int main(int argc, char **argv) {
void *p = 0;
_m_prefetch(p);
}" HAVE_3DNOW)
if(HAVE_3DNOW)
list(APPEND EXTRA_CFLAGS "-m3dnow")
endif()
set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
endif()
if(SSE)
set(CMAKE_REQUIRED_FLAGS "-msse")
check_c_source_compiles("
#ifdef __MINGW32__
#include <_mingw.h>
#ifdef __MINGW64_VERSION_MAJOR
#include <intrin.h>
#else
#include <xmmintrin.h>
#endif
#else
#include <xmmintrin.h>
#endif
#ifndef __SSE__
#error Assembler CPP flag not enabled
#endif
int main(int argc, char **argv) { }" HAVE_SSE)
if(HAVE_SSE)
list(APPEND EXTRA_CFLAGS "-msse")
endif()
set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
endif()
if(SSE2)
set(CMAKE_REQUIRED_FLAGS "-msse2")
check_c_source_compiles("
#ifdef __MINGW32__
#include <_mingw.h>
#ifdef __MINGW64_VERSION_MAJOR
#include <intrin.h>
#else
#include <emmintrin.h>
#endif
#else
#include <emmintrin.h>
#endif
#ifndef __SSE2__
#error Assembler CPP flag not enabled
#endif
int main(int argc, char **argv) { }" HAVE_SSE2)
if(HAVE_SSE2)
list(APPEND EXTRA_CFLAGS "-msse2")
endif()
set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
endif()
if(SSE3)
set(CMAKE_REQUIRED_FLAGS "-msse3")
check_c_source_compiles("
#ifdef __MINGW32__
#include <_mingw.h>
#ifdef __MINGW64_VERSION_MAJOR
#include <intrin.h>
#else
#include <pmmintrin.h>
#endif
#else
#include <pmmintrin.h>
#endif
#ifndef __SSE3__
#error Assembler CPP flag not enabled
#endif
int main(int argc, char **argv) { }" HAVE_SSE3)
if(HAVE_SSE3)
list(APPEND EXTRA_CFLAGS "-msse3")
endif()
set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
endif()
if(NOT SSEMATH)
if(SSE OR SSE2 OR SSE3)
if(USE_GCC)
check_c_compiler_flag(-mfpmath=387 HAVE_FP_387)
if(HAVE_FP_387)
list(APPEND EXTRA_CFLAGS "-mfpmath=387")
endif()
endif()
set(HAVE_SSEMATH TRUE)
endif()
endif()
check_include_file("immintrin.h" HAVE_IMMINTRIN_H)
if(ALTIVEC)
set(CMAKE_REQUIRED_FLAGS "-maltivec")
check_c_source_compiles("
#include <altivec.h>
vector unsigned int vzero() {
return vec_splat_u32(0);
}
int main(int argc, char **argv) { }" HAVE_ALTIVEC_H_HDR)
check_c_source_compiles("
vector unsigned int vzero() {
return vec_splat_u32(0);
}
int main(int argc, char **argv) { }" HAVE_ALTIVEC)
set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
if(HAVE_ALTIVEC OR HAVE_ALTIVEC_H_HDR)
set(HAVE_ALTIVEC TRUE) # if only HAVE_ALTIVEC_H_HDR is set
list(APPEND EXTRA_CFLAGS "-maltivec")
set(SDL_ALTIVEC_BLITTERS 1)
if(HAVE_ALTIVEC_H_HDR)
set(HAVE_ALTIVEC_H 1)
endif()
endif()
endif()
elseif(MSVC_VERSION GREATER 1500)
# TODO: SDL_cpuinfo.h needs to support the user's configuration wish
# for MSVC - right now it is always activated
if(NOT ARCH_64)
set(HAVE_MMX TRUE)
set(HAVE_3DNOW TRUE)
endif()
set(HAVE_SSE TRUE)
set(HAVE_SSE2 TRUE)
set(HAVE_SSE3 TRUE)
set(SDL_ASSEMBLY_ROUTINES 1)
endif()
# TODO:
#else()
# if(USE_GCC OR USE_CLANG)
# list(APPEND EXTRA_CFLAGS "-mno-sse" "-mno-sse2" "-mno-sse3" "-mno-mmx")
# endif()
endif()
# TODO: Can't deactivate on FreeBSD? w/o LIBC, SDL_stdinc.h can't define
# anything.
if(LIBC)
if(WINDOWS AND NOT MINGW)
set(HAVE_LIBC TRUE)
foreach(_HEADER stdio.h string.h wchar.h ctype.h math.h limits.h)
string(TOUPPER "HAVE_${_HEADER}" _UPPER)
string(REPLACE "." "_" _HAVE_H ${_UPPER})
set(${_HAVE_H} 1)
endforeach()
set(HAVE_SIGNAL_H 1)
foreach(_FN
malloc calloc realloc free qsort abs memset memcpy memmove memcmp
wcslen wcscmp
strlen _strrev _strupr _strlwr strchr strrchr strstr itoa _ltoa
_ultoa strtol strtoul strtoll strtod atoi atof strcmp strncmp
_stricmp _strnicmp sscanf
acos acosf asin asinf atan atanf atan2 atan2f ceil ceilf
copysign copysignf cos cosf exp expf fabs fabsf floor floorf fmod fmodf
log logf log10 log10f pow powf scalbn scalbnf sin sinf sqrt sqrtf tan tanf)
string(TOUPPER ${_FN} _UPPER)
set(HAVE_${_UPPER} 1)
endforeach()
if(NOT CYGWIN AND NOT MINGW)
set(HAVE_ALLOCA 1)
endif()
set(HAVE_M_PI 1)
add_definitions(-D_USE_MATH_DEFINES) # needed for M_PI
set(STDC_HEADERS 1)
else()
set(HAVE_LIBC TRUE)
check_include_file(sys/types.h HAVE_SYS_TYPES_H)
foreach(_HEADER
stdio.h stdlib.h stddef.h stdarg.h malloc.h memory.h string.h limits.h
strings.h wchar.h inttypes.h stdint.h ctype.h math.h iconv.h signal.h libunwind.h)
string(TOUPPER "HAVE_${_HEADER}" _UPPER)
string(REPLACE "." "_" _HAVE_H ${_UPPER})
check_include_file("${_HEADER}" ${_HAVE_H})
endforeach()
check_include_files("dlfcn.h;stdint.h;stddef.h;inttypes.h;stdlib.h;strings.h;string.h;float.h" STDC_HEADERS)
check_type_size("size_t" SIZEOF_SIZE_T)
check_symbol_exists(M_PI math.h HAVE_M_PI)
# TODO: refine the mprotect check
check_c_source_compiles("#include <sys/types.h>
#include <sys/mman.h>
int main() { }" HAVE_MPROTECT)
foreach(_FN
strtod malloc calloc realloc free getenv setenv putenv unsetenv
qsort abs bcopy memset memcpy memmove memcmp strlen strlcpy strlcat
_strrev _strupr _strlwr strchr strrchr strstr itoa _ltoa
_uitoa _ultoa strtol strtoul _i64toa _ui64toa strtoll strtoull
atoi atof strcmp strncmp _stricmp strcasecmp _strnicmp strncasecmp
vsscanf vsnprintf fopen64 fseeko fseeko64 sigaction setjmp
nanosleep sysconf sysctlbyname getauxval poll _Exit
)
string(TOUPPER ${_FN} _UPPER)
set(_HAVEVAR "HAVE_${_UPPER}")
check_function_exists("${_FN}" ${_HAVEVAR})
endforeach()
check_library_exists(m pow "" HAVE_LIBM)
if(HAVE_LIBM)
set(CMAKE_REQUIRED_LIBRARIES m)
foreach(_FN
atan atan2 ceil copysign cos cosf fabs floor log pow scalbn sin
sinf sqrt sqrtf tan tanf acos asin)
string(TOUPPER ${_FN} _UPPER)
set(_HAVEVAR "HAVE_${_UPPER}")
check_function_exists("${_FN}" ${_HAVEVAR})
endforeach()
set(CMAKE_REQUIRED_LIBRARIES)
list(APPEND EXTRA_LIBS m)
endif()
check_library_exists(iconv iconv_open "" HAVE_LIBICONV)
if(HAVE_LIBICONV)
list(APPEND EXTRA_LIBS iconv)
set(HAVE_ICONV 1)
endif()
if(NOT APPLE)
check_include_file(alloca.h HAVE_ALLOCA_H)
check_function_exists(alloca HAVE_ALLOCA)
else()
set(HAVE_ALLOCA_H 1)
set(HAVE_ALLOCA 1)
endif()
check_struct_has_member("struct sigaction" "sa_sigaction" "signal.h" HAVE_SA_SIGACTION)
endif()
else()
if(WINDOWS)
set(HAVE_STDARG_H 1)
set(HAVE_STDDEF_H 1)
endif()
endif()
# Enable/disable various subsystems of the SDL library
foreach(_SUB ${SDL_SUBSYSTEMS})
string(TOUPPER ${_SUB} _OPT)
if(NOT SDL_${_OPT})
set(SDL_${_OPT}_DISABLED 1)
endif()
endforeach()
if(SDL_JOYSTICK)
file(GLOB JOYSTICK_SOURCES ${SDL2_SOURCE_DIR}/src/joystick/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${JOYSTICK_SOURCES})
endif()
if(SDL_HAPTIC)
if(NOT SDL_JOYSTICK)
# Haptic requires some private functions from the joystick subsystem.
message_error("SDL_HAPTIC requires SDL_JOYSTICK, which is not enabled")
endif()
file(GLOB HAPTIC_SOURCES ${SDL2_SOURCE_DIR}/src/haptic/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${HAPTIC_SOURCES})
endif()
if(SDL_SENSOR)
file(GLOB SENSOR_SOURCES ${SDL2_SOURCE_DIR}/src/sensor/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${SENSOR_SOURCES})
endif()
if(SDL_POWER)
file(GLOB POWER_SOURCES ${SDL2_SOURCE_DIR}/src/power/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${POWER_SOURCES})
endif()
# TODO: in configure.ac, the test for LOADSO and SDL_DLOPEN is a bit weird:
# if LOADSO is not wanted, SDL_LOADSO_DISABLED is set
# If however on Unix or APPLE dlopen() is detected via CheckDLOPEN(),
# SDL_LOADSO_DISABLED will not be set, regardless of the LOADSO settings
# General SDL subsystem options, valid for all platforms
if(SDL_AUDIO)
# CheckDummyAudio/CheckDiskAudio - valid for all platforms
if(DUMMYAUDIO)
set(SDL_AUDIO_DRIVER_DUMMY 1)
file(GLOB DUMMYAUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/dummy/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${DUMMYAUDIO_SOURCES})
set(HAVE_DUMMYAUDIO TRUE)
endif()
if(DISKAUDIO)
set(SDL_AUDIO_DRIVER_DISK 1)
file(GLOB DISKAUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/disk/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${DISKAUDIO_SOURCES})
set(HAVE_DISKAUDIO TRUE)
endif()
endif()
if(SDL_DLOPEN)
# Relevant for Unix/Darwin only
if(UNIX OR APPLE)
CheckDLOPEN()
endif()
endif()
if(SDL_VIDEO)
if(VIDEO_DUMMY)
set(SDL_VIDEO_DRIVER_DUMMY 1)
file(GLOB VIDEO_DUMMY_SOURCES ${SDL2_SOURCE_DIR}/src/video/dummy/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${VIDEO_DUMMY_SOURCES})
set(HAVE_VIDEO_DUMMY TRUE)
set(HAVE_SDL_VIDEO TRUE)
endif()
endif()
# Platform-specific options and settings
if(ANDROID)
file(GLOB ANDROID_CORE_SOURCES ${SDL2_SOURCE_DIR}/src/core/android/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_CORE_SOURCES})
# SDL_spinlock.c Needs to be compiled in ARM mode.
# There seems to be no better way currently to set the ARM mode.
# see: https://issuetracker.google.com/issues/62264618
# Another option would be to set ARM mode to all compiled files
check_c_compiler_flag(-marm HAVE_ARM_MODE)
if(HAVE_ARM_MODE)
set_source_files_properties(${SDL2_SOURCE_DIR}/src/atomic/SDL_spinlock.c PROPERTIES COMPILE_FLAGS -marm)
endif()
file(GLOB ANDROID_MAIN_SOURCES ${SDL2_SOURCE_DIR}/src/main/android/*.c)
set(SDLMAIN_SOURCES ${SDLMAIN_SOURCES} ${ANDROID_MAIN_SOURCES})
if(SDL_AUDIO)
set(SDL_AUDIO_DRIVER_ANDROID 1)
file(GLOB ANDROID_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/android/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_AUDIO_SOURCES})
set(HAVE_SDL_AUDIO TRUE)
endif()
if(SDL_FILESYSTEM)
set(SDL_FILESYSTEM_ANDROID 1)
file(GLOB ANDROID_FILESYSTEM_SOURCES ${SDL2_SOURCE_DIR}/src/filesystem/android/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_FILESYSTEM_SOURCES})
set(HAVE_SDL_FILESYSTEM TRUE)
endif()
if(SDL_HAPTIC)
set(SDL_HAPTIC_ANDROID 1)
file(GLOB ANDROID_HAPTIC_SOURCES ${SDL2_SOURCE_DIR}/src/haptic/android/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_HAPTIC_SOURCES})
set(HAVE_SDL_HAPTIC TRUE)
endif()
if(SDL_JOYSTICK)
CheckHIDAPI()
set(SDL_JOYSTICK_ANDROID 1)
file(GLOB ANDROID_JOYSTICK_SOURCES ${SDL2_SOURCE_DIR}/src/joystick/android/*.c ${SDL2_SOURCE_DIR}/src/joystick/steam/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_JOYSTICK_SOURCES})
set(HAVE_SDL_JOYSTICK TRUE)
endif()
if(SDL_LOADSO)
set(SDL_LOADSO_DLOPEN 1)
file(GLOB LOADSO_SOURCES ${SDL2_SOURCE_DIR}/src/loadso/dlopen/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${LOADSO_SOURCES})
set(HAVE_SDL_LOADSO TRUE)
endif()
if(SDL_POWER)
set(SDL_POWER_ANDROID 1)
file(GLOB ANDROID_POWER_SOURCES ${SDL2_SOURCE_DIR}/src/power/android/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_POWER_SOURCES})
set(HAVE_SDL_POWER TRUE)
endif()
if(SDL_TIMERS)
set(SDL_TIMER_UNIX 1)
file(GLOB TIMER_SOURCES ${SDL2_SOURCE_DIR}/src/timer/unix/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${TIMER_SOURCES})
set(HAVE_SDL_TIMERS TRUE)
endif()
if(SDL_SENSOR)
set(SDL_SENSOR_ANDROID 1)
set(HAVE_SDL_SENSORS TRUE)
file(GLOB ANDROID_SENSOR_SOURCES ${SDL2_SOURCE_DIR}/src/sensor/android/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_SENSOR_SOURCES})
endif()
if(SDL_VIDEO)
set(SDL_VIDEO_DRIVER_ANDROID 1)
file(GLOB ANDROID_VIDEO_SOURCES ${SDL2_SOURCE_DIR}/src/video/android/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_VIDEO_SOURCES})
set(HAVE_SDL_VIDEO TRUE)
# Core stuff
find_library(ANDROID_DL_LIBRARY dl)
find_library(ANDROID_LOG_LIBRARY log)
find_library(ANDROID_LIBRARY_LIBRARY android)
list(APPEND EXTRA_LIBS ${ANDROID_DL_LIBRARY} ${ANDROID_LOG_LIBRARY} ${ANDROID_LIBRARY_LIBRARY})
add_definitions(-DGL_GLEXT_PROTOTYPES)
#enable gles
if(VIDEO_OPENGLES)
set(SDL_VIDEO_OPENGL_EGL 1)
set(HAVE_VIDEO_OPENGLES TRUE)
set(SDL_VIDEO_OPENGL_ES 1)
set(SDL_VIDEO_RENDER_OGL_ES 1)
set(SDL_VIDEO_OPENGL_ES2 1)
set(SDL_VIDEO_RENDER_OGL_ES2 1)
find_library(OpenGLES1_LIBRARY GLESv1_CM)
find_library(OpenGLES2_LIBRARY GLESv2)
list(APPEND EXTRA_LIBS ${OpenGLES1_LIBRARY} ${OpenGLES2_LIBRARY})
endif()
CHECK_C_SOURCE_COMPILES("
#if defined(__ARM_ARCH) && __ARM_ARCH < 7
#error Vulkan doesn't work on this configuration
#endif
int main()
{
return 0;
}
" VULKAN_PASSED_ANDROID_CHECKS)
if(NOT VULKAN_PASSED_ANDROID_CHECKS)
set(VIDEO_VULKAN OFF)
message(STATUS "Vulkan doesn't work on this configuration")
endif()
endif()
CheckPTHREAD()
elseif(EMSCRIPTEN)
# Hide noisy warnings that intend to aid mostly during initial stages of porting a new
# project. Uncomment at will for verbose cross-compiling -I/../ path info.
add_definitions(-Wno-warn-absolute-paths)
if(SDL_AUDIO)
set(SDL_AUDIO_DRIVER_EMSCRIPTEN 1)
file(GLOB EM_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/emscripten/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${EM_AUDIO_SOURCES})
set(HAVE_SDL_AUDIO TRUE)
endif()
if(SDL_FILESYSTEM)
set(SDL_FILESYSTEM_EMSCRIPTEN 1)
file(GLOB EM_FILESYSTEM_SOURCES ${SDL2_SOURCE_DIR}/src/filesystem/emscripten/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${EM_FILESYSTEM_SOURCES})
set(HAVE_SDL_FILESYSTEM TRUE)
endif()
if(SDL_JOYSTICK)
set(SDL_JOYSTICK_EMSCRIPTEN 1)
file(GLOB EM_JOYSTICK_SOURCES ${SDL2_SOURCE_DIR}/src/joystick/emscripten/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${EM_JOYSTICK_SOURCES})
set(HAVE_SDL_JOYSTICK TRUE)
endif()
if(SDL_POWER)
set(SDL_POWER_EMSCRIPTEN 1)
file(GLOB EM_POWER_SOURCES ${SDL2_SOURCE_DIR}/src/power/emscripten/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${EM_POWER_SOURCES})
set(HAVE_SDL_POWER TRUE)
endif()
if(SDL_TIMERS)
set(SDL_TIMER_UNIX 1)
file(GLOB TIMER_SOURCES ${SDL2_SOURCE_DIR}/src/timer/unix/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${TIMER_SOURCES})
set(HAVE_SDL_TIMERS TRUE)
if(CLOCK_GETTIME)
set(HAVE_CLOCK_GETTIME 1)
endif()
endif()
if(SDL_VIDEO)
set(SDL_VIDEO_DRIVER_EMSCRIPTEN 1)
file(GLOB EM_VIDEO_SOURCES ${SDL2_SOURCE_DIR}/src/video/emscripten/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${EM_VIDEO_SOURCES})
set(HAVE_SDL_VIDEO TRUE)
#enable gles
if(VIDEO_OPENGLES)
set(SDL_VIDEO_OPENGL_EGL 1)
set(HAVE_VIDEO_OPENGLES TRUE)
set(SDL_VIDEO_OPENGL_ES2 1)
set(SDL_VIDEO_RENDER_OGL_ES2 1)
endif()
endif()
elseif(UNIX AND NOT APPLE AND NOT ANDROID)
if(SDL_AUDIO)
if(SYSV5 OR SOLARIS OR HPUX)
set(SDL_AUDIO_DRIVER_SUNAUDIO 1)
file(GLOB SUN_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/sun/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${SUN_AUDIO_SOURCES})
set(HAVE_SDL_AUDIO TRUE)
elseif(NETBSD)
set(SDL_AUDIO_DRIVER_NETBSD 1)
file(GLOB NETBSD_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/netbsd/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${NETBSD_AUDIO_SOURCES})
set(HAVE_SDL_AUDIO TRUE)
elseif(AIX)
set(SDL_AUDIO_DRIVER_PAUDIO 1)
file(GLOB AIX_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/paudio/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${AIX_AUDIO_SOURCES})
set(HAVE_SDL_AUDIO TRUE)
endif()
CheckOSS()
CheckALSA()
CheckJACK()
CheckPulseAudio()
CheckESD()
CheckARTS()
CheckNAS()
CheckSNDIO()
CheckFusionSound()
CheckLibSampleRate()
endif()
if(SDL_VIDEO)
# Need to check for Raspberry PI first and add platform specific compiler flags, otherwise the test for GLES fails!
CheckRPI()
CheckX11()
CheckDirectFB()
CheckOpenGLX11()
CheckOpenGLESX11()
CheckWayland()
CheckVivante()
CheckKMSDRM()
endif()
if(UNIX)
file(GLOB CORE_UNIX_SOURCES ${SDL2_SOURCE_DIR}/src/core/unix/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${CORE_UNIX_SOURCES})
endif()
if(LINUX)
check_c_source_compiles("
#include <linux/input.h>
#ifndef EVIOCGNAME
#error EVIOCGNAME() ioctl not available
#endif
int main(int argc, char** argv) {}" HAVE_INPUT_EVENTS)
check_c_source_compiles("
#include <linux/kd.h>
#include <linux/keyboard.h>
int main(int argc, char **argv)
{
struct kbentry kbe;
kbe.kb_table = KG_CTRL;
ioctl(0, KDGKBENT, &kbe);
}" HAVE_INPUT_KD)
file(GLOB CORE_LINUX_SOURCES ${SDL2_SOURCE_DIR}/src/core/linux/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${CORE_LINUX_SOURCES})
if(HAVE_INPUT_EVENTS)
set(SDL_INPUT_LINUXEV 1)
endif()
if(SDL_HAPTIC AND HAVE_INPUT_EVENTS)
set(SDL_HAPTIC_LINUX 1)
file(GLOB HAPTIC_SOURCES ${SDL2_SOURCE_DIR}/src/haptic/linux/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${HAPTIC_SOURCES})
set(HAVE_SDL_HAPTIC TRUE)
endif()
if(HAVE_INPUT_KD)
set(SDL_INPUT_LINUXKD 1)
endif()
check_include_file("libudev.h" HAVE_LIBUDEV_H)
if(PKG_CONFIG_FOUND)
pkg_search_module(DBUS dbus-1 dbus)
if(DBUS_FOUND)
set(HAVE_DBUS_DBUS_H TRUE)
include_directories(${DBUS_INCLUDE_DIRS})
list(APPEND EXTRA_LIBS ${DBUS_LIBRARIES})
endif()
pkg_search_module(IBUS ibus-1.0 ibus)
if(IBUS_FOUND)
set(HAVE_IBUS_IBUS_H TRUE)
include_directories(${IBUS_INCLUDE_DIRS})
list(APPEND EXTRA_LIBS ${IBUS_LIBRARIES})
endif()
if(HAVE_LIBUNWIND_H)
# We've already found the header, so REQUIRE the lib to be present
pkg_search_module(UNWIND REQUIRED libunwind)
pkg_search_module(UNWIND_GENERIC REQUIRED libunwind-generic)
list(APPEND EXTRA_LIBS ${UNWIND_LIBRARIES} ${UNWIND_GENERIC_LIBRARIES})
endif()
endif()
check_include_file("fcitx/frontend.h" HAVE_FCITX_FRONTEND_H)
endif()
if(INPUT_TSLIB)
check_c_source_compiles("
#include \"tslib.h\"
int main(int argc, char** argv) { }" HAVE_INPUT_TSLIB)
if(HAVE_INPUT_TSLIB)
set(SDL_INPUT_TSLIB 1)
list(APPEND EXTRA_LIBS ts)
endif()
endif()
if(SDL_JOYSTICK)
CheckUSBHID() # seems to be BSD specific - limit the test to BSD only?
CheckHIDAPI()
if(LINUX AND NOT ANDROID)
set(SDL_JOYSTICK_LINUX 1)
file(GLOB JOYSTICK_SOURCES ${SDL2_SOURCE_DIR}/src/joystick/linux/*.c ${SDL2_SOURCE_DIR}/src/joystick/steam/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${JOYSTICK_SOURCES})
set(HAVE_SDL_JOYSTICK TRUE)
endif()
endif()
CheckPTHREAD()
if(CLOCK_GETTIME)
check_library_exists(rt clock_gettime "" FOUND_CLOCK_GETTIME)
if(FOUND_CLOCK_GETTIME)
list(APPEND EXTRA_LIBS rt)
set(HAVE_CLOCK_GETTIME 1)
else()
check_library_exists(c clock_gettime "" FOUND_CLOCK_GETTIME)
if(FOUND_CLOCK_GETTIME)
set(HAVE_CLOCK_GETTIME 1)
endif()
endif()
endif()
check_include_file(linux/version.h HAVE_LINUX_VERSION_H)
if(HAVE_LINUX_VERSION_H)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DHAVE_LINUX_VERSION_H")
endif()
if(SDL_POWER)
if(LINUX)
set(SDL_POWER_LINUX 1)
file(GLOB POWER_SOURCES ${SDL2_SOURCE_DIR}/src/power/linux/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${POWER_SOURCES})
set(HAVE_SDL_POWER TRUE)
endif()
endif()
if(SDL_FILESYSTEM)
set(SDL_FILESYSTEM_UNIX 1)
file(GLOB FILESYSTEM_SOURCES ${SDL2_SOURCE_DIR}/src/filesystem/unix/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${FILESYSTEM_SOURCES})
set(HAVE_SDL_FILESYSTEM TRUE)
endif()
if(SDL_TIMERS)
set(SDL_TIMER_UNIX 1)
file(GLOB TIMER_SOURCES ${SDL2_SOURCE_DIR}/src/timer/unix/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${TIMER_SOURCES})
set(HAVE_SDL_TIMERS TRUE)
endif()
if(RPATH)
set(SDL_RLD_FLAGS "")
if(BSDI OR FREEBSD OR LINUX OR NETBSD)
set(CMAKE_REQUIRED_FLAGS "-Wl,--enable-new-dtags")
check_c_compiler_flag("" HAVE_ENABLE_NEW_DTAGS)
set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
if(HAVE_ENABLE_NEW_DTAGS)
set(SDL_RLD_FLAGS "-Wl,-rpath,\${libdir} -Wl,--enable-new-dtags")
else()
set(SDL_RLD_FLAGS "-Wl,-rpath,\${libdir}")
endif()
elseif(SOLARIS)
set(SDL_RLD_FLAGS "-R\${libdir}")
endif()
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(HAVE_RPATH TRUE)
endif()
elseif(WINDOWS)
find_program(WINDRES windres)
check_c_source_compiles("
#include <windows.h>
int main(int argc, char **argv) { }" HAVE_WIN32_CC)
file(GLOB CORE_SOURCES ${SDL2_SOURCE_DIR}/src/core/windows/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${CORE_SOURCES})
if(MSVC)
# Prevent codegen that would use the VC runtime libraries.
set_property(DIRECTORY . APPEND PROPERTY COMPILE_OPTIONS "/GS-")
if(NOT ARCH_64)
set_property(DIRECTORY . APPEND PROPERTY COMPILE_OPTIONS "/arch:SSE")
endif()
endif()
# Check for DirectX
if(DIRECTX)
if(DEFINED MSVC_VERSION AND NOT ${MSVC_VERSION} LESS 1700)
set(USE_WINSDK_DIRECTX TRUE)
endif()
if(NOT CMAKE_COMPILER_IS_MINGW AND NOT USE_WINSDK_DIRECTX)
if("$ENV{DXSDK_DIR}" STREQUAL "")
message_error("DIRECTX requires the \$DXSDK_DIR environment variable to be set")
endif()
set(CMAKE_REQUIRED_FLAGS "/I\"$ENV{DXSDK_DIR}\\Include\"")
endif()
if(HAVE_WIN32_CC)
# xinput.h may need windows.h, but doesn't include it itself.
check_c_source_compiles("
#include <windows.h>
#include <xinput.h>
int main(int argc, char **argv) { }" HAVE_XINPUT_H)
check_c_source_compiles("
#include <windows.h>
#include <xinput.h>
XINPUT_GAMEPAD_EX x1;
int main(int argc, char **argv) { }" HAVE_XINPUT_GAMEPAD_EX)
check_c_source_compiles("
#include <windows.h>
#include <xinput.h>
XINPUT_STATE_EX s1;
int main(int argc, char **argv) { }" HAVE_XINPUT_STATE_EX)
else()
check_include_file(xinput.h HAVE_XINPUT_H)
endif()
check_include_file(d3d9.h HAVE_D3D_H)
check_include_file(d3d11_1.h HAVE_D3D11_H)
check_include_file(ddraw.h HAVE_DDRAW_H)
check_include_file(dsound.h HAVE_DSOUND_H)
check_include_file(dinput.h HAVE_DINPUT_H)
check_include_file(dxgi.h HAVE_DXGI_H)
if(HAVE_D3D_H OR HAVE_D3D11_H OR HAVE_DDRAW_H OR HAVE_DSOUND_H OR HAVE_DINPUT_H)
set(HAVE_DIRECTX TRUE)
if(NOT CMAKE_COMPILER_IS_MINGW AND NOT USE_WINSDK_DIRECTX)
# TODO: change $ENV{DXSDL_DIR} to get the path from the include checks
link_directories($ENV{DXSDK_DIR}\\lib\\${PROCESSOR_ARCH})
include_directories($ENV{DXSDK_DIR}\\Include)
endif()
endif()
set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
endif()
# headers needed elsewhere ...
check_include_file(mmdeviceapi.h HAVE_MMDEVICEAPI_H)
check_include_file(audioclient.h HAVE_AUDIOCLIENT_H)
check_include_file(endpointvolume.h HAVE_ENDPOINTVOLUME_H)
if(SDL_AUDIO)
set(SDL_AUDIO_DRIVER_WINMM 1)
file(GLOB WINMM_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/winmm/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${WINMM_AUDIO_SOURCES})
set(HAVE_SDL_AUDIO TRUE)
if(HAVE_DSOUND_H)
set(SDL_AUDIO_DRIVER_DSOUND 1)
file(GLOB DSOUND_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/directsound/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${DSOUND_AUDIO_SOURCES})
endif()
if(WASAPI AND HAVE_AUDIOCLIENT_H AND HAVE_MMDEVICEAPI_H)
set(SDL_AUDIO_DRIVER_WASAPI 1)
file(GLOB WASAPI_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/wasapi/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${WASAPI_AUDIO_SOURCES})
endif()
endif()
if(SDL_VIDEO)
# requires SDL_LOADSO on Windows (IME, DX, etc.)
if(NOT SDL_LOADSO)
message_error("SDL_VIDEO requires SDL_LOADSO, which is not enabled")
endif()
set(SDL_VIDEO_DRIVER_WINDOWS 1)
file(GLOB WIN_VIDEO_SOURCES ${SDL2_SOURCE_DIR}/src/video/windows/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${WIN_VIDEO_SOURCES})
if(RENDER_D3D AND HAVE_D3D_H)
set(SDL_VIDEO_RENDER_D3D 1)
set(HAVE_RENDER_D3D TRUE)
endif()
if(RENDER_D3D AND HAVE_D3D11_H)
set(SDL_VIDEO_RENDER_D3D11 1)
set(HAVE_RENDER_D3D TRUE)
endif()
set(HAVE_SDL_VIDEO TRUE)
endif()
if(SDL_THREADS)
set(SDL_THREAD_WINDOWS 1)
set(SOURCE_FILES ${SOURCE_FILES}
${SDL2_SOURCE_DIR}/src/thread/windows/SDL_sysmutex.c
${SDL2_SOURCE_DIR}/src/thread/windows/SDL_syssem.c
${SDL2_SOURCE_DIR}/src/thread/windows/SDL_systhread.c
${SDL2_SOURCE_DIR}/src/thread/windows/SDL_systls.c
${SDL2_SOURCE_DIR}/src/thread/generic/SDL_syscond.c)
set(HAVE_SDL_THREADS TRUE)
endif()
if(SDL_POWER)
set(SDL_POWER_WINDOWS 1)
set(SOURCE_FILES ${SOURCE_FILES} ${SDL2_SOURCE_DIR}/src/power/windows/SDL_syspower.c)
set(HAVE_SDL_POWER TRUE)
endif()
if(SDL_FILESYSTEM)
set(SDL_FILESYSTEM_WINDOWS 1)
file(GLOB FILESYSTEM_SOURCES ${SDL2_SOURCE_DIR}/src/filesystem/windows/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${FILESYSTEM_SOURCES})
set(HAVE_SDL_FILESYSTEM TRUE)
endif()
# Libraries for Win32 native and MinGW
list(APPEND EXTRA_LIBS user32 gdi32 winmm imm32 ole32 oleaut32 version uuid advapi32 setupapi shell32)
# TODO: in configure.ac the check for timers is set on
# cygwin | mingw32* - does this include mingw32CE?
if(SDL_TIMERS)
set(SDL_TIMER_WINDOWS 1)
file(GLOB TIMER_SOURCES ${SDL2_SOURCE_DIR}/src/timer/windows/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${TIMER_SOURCES})
set(HAVE_SDL_TIMERS TRUE)
endif()
if(SDL_LOADSO)
set(SDL_LOADSO_WINDOWS 1)
file(GLOB LOADSO_SOURCES ${SDL2_SOURCE_DIR}/src/loadso/windows/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${LOADSO_SOURCES})
set(HAVE_SDL_LOADSO TRUE)
endif()
file(GLOB CORE_SOURCES ${SDL2_SOURCE_DIR}/src/core/windows/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${CORE_SOURCES})
if(SDL_VIDEO)
if(VIDEO_OPENGL)
set(SDL_VIDEO_OPENGL 1)
set(SDL_VIDEO_OPENGL_WGL 1)
set(SDL_VIDEO_RENDER_OGL 1)
set(HAVE_VIDEO_OPENGL TRUE)
endif()
if(VIDEO_OPENGLES)
set(SDL_VIDEO_OPENGL_EGL 1)
set(SDL_VIDEO_OPENGL_ES2 1)
set(SDL_VIDEO_RENDER_OGL_ES2 1)
set(HAVE_VIDEO_OPENGLES TRUE)
endif()
endif()
if(SDL_JOYSTICK)
CheckHIDAPI()
if(HAVE_HIDAPI)
set(SOURCE_FILES ${SOURCE_FILES} ${SDL2_SOURCE_DIR}/src/hidapi/windows/hid.c)
endif()
file(GLOB JOYSTICK_SOURCES ${SDL2_SOURCE_DIR}/src/joystick/windows/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${JOYSTICK_SOURCES})
if(HAVE_DINPUT_H)
set(SDL_JOYSTICK_DINPUT 1)
list(APPEND EXTRA_LIBS dinput8)
if(CMAKE_COMPILER_IS_MINGW)
list(APPEND EXTRA_LIBS dxerr8)
elseif (NOT USE_WINSDK_DIRECTX)
list(APPEND EXTRA_LIBS dxerr)
endif()
endif()
if(HAVE_XINPUT_H)
set(SDL_JOYSTICK_XINPUT 1)
endif()
if(NOT HAVE_DINPUT_H AND NOT HAVE_XINPUT_H)
set(SDL_JOYSTICK_WINMM 1)
endif()
set(HAVE_SDL_JOYSTICK TRUE)
if(SDL_HAPTIC)
if(HAVE_DINPUT_H OR HAVE_XINPUT_H)
file(GLOB HAPTIC_SOURCES ${SDL2_SOURCE_DIR}/src/haptic/windows/*.c)
if(HAVE_DINPUT_H)
set(SDL_HAPTIC_DINPUT 1)
endif()
if(HAVE_XINPUT_H)
set(SDL_HAPTIC_XINPUT 1)
endif()
else()
file(GLOB HAPTIC_SOURCES ${SDL2_SOURCE_DIR}/src/haptic/dummy/*.c)
set(SDL_HAPTIC_DUMMY 1)
endif()
set(SOURCE_FILES ${SOURCE_FILES} ${HAPTIC_SOURCES})
set(HAVE_SDL_HAPTIC TRUE)
endif()
endif()
file(GLOB VERSION_SOURCES ${SDL2_SOURCE_DIR}/src/main/windows/*.rc)
file(GLOB SDLMAIN_SOURCES ${SDL2_SOURCE_DIR}/src/main/windows/*.c)
if(MINGW OR CYGWIN)
list(APPEND EXTRA_LIBS mingw32)
list(APPEND EXTRA_LDFLAGS "-mwindows")
set(SDL_CFLAGS "${SDL_CFLAGS} -Dmain=SDL_main")
list(APPEND SDL_LIBS "-lmingw32" "-lSDL2main" "-mwindows")
endif()
elseif(APPLE)
# TODO: rework this all for proper MacOS X, iOS and Darwin support
# We always need these libs on macOS at the moment.
# !!! FIXME: we need Carbon for some very old API calls in
# !!! FIXME: src/video/cocoa/SDL_cocoakeyboard.c, but we should figure out
# !!! FIXME: how to dump those.
if(NOT IOS)
set(SDL_FRAMEWORK_COCOA 1)
set(SDL_FRAMEWORK_CARBON 1)
endif()
# Requires the darwin file implementation
if(SDL_FILE)
file(GLOB EXTRA_SOURCES ${SDL2_SOURCE_DIR}/src/file/cocoa/*.m)
set(SOURCE_FILES ${EXTRA_SOURCES} ${SOURCE_FILES})
# !!! FIXME: modern CMake doesn't need "LANGUAGE C" for Objective-C.
set_source_files_properties(${EXTRA_SOURCES} PROPERTIES LANGUAGE C)
set(HAVE_SDL_FILE TRUE)
# !!! FIXME: why is COREVIDEO inside this if() block?
set(SDL_FRAMEWORK_COREVIDEO 1)
else()
message_error("SDL_FILE must be enabled to build on MacOS X")
endif()
if(SDL_AUDIO)
set(SDL_AUDIO_DRIVER_COREAUDIO 1)
file(GLOB AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/coreaudio/*.m)
# !!! FIXME: modern CMake doesn't need "LANGUAGE C" for Objective-C.
set_source_files_properties(${AUDIO_SOURCES} PROPERTIES LANGUAGE C)
set(SOURCE_FILES ${SOURCE_FILES} ${AUDIO_SOURCES})
set(HAVE_SDL_AUDIO TRUE)
set(SDL_FRAMEWORK_COREAUDIO 1)
set(SDL_FRAMEWORK_AUDIOTOOLBOX 1)
endif()
if(SDL_JOYSTICK)
CheckHIDAPI()
if(HAVE_HIDAPI)
if(IOS)
set(SOURCE_FILES ${SOURCE_FILES} ${SDL2_SOURCE_DIR}/src/hidapi/ios/hid.m)
else()
set(SOURCE_FILES ${SOURCE_FILES} ${SDL2_SOURCE_DIR}/src/hidapi/mac/hid.c)
endif()
endif()
set(SDL_JOYSTICK_IOKIT 1)
if (IOS)
file(GLOB JOYSTICK_SOURCES ${SDL2_SOURCE_DIR}/src/joystick/iphoneos/*.m ${SDL2_SOURCE_DIR}/src/joystick/steam/*.c)
else()
file(GLOB JOYSTICK_SOURCES ${SDL2_SOURCE_DIR}/src/joystick/darwin/*.c)
endif()
set(SOURCE_FILES ${SOURCE_FILES} ${JOYSTICK_SOURCES})
set(HAVE_SDL_JOYSTICK TRUE)
set(SDL_FRAMEWORK_IOKIT 1)
set(SDL_FRAMEWORK_FF 1)
endif()
if(SDL_HAPTIC)
set(SDL_HAPTIC_IOKIT 1)
if (IOS)
file(GLOB HAPTIC_SOURCES ${SDL2_SOURCE_DIR}/src/haptic/dummy/*.c)
set(SDL_HAPTIC_DUMMY 1)
else()
file(GLOB HAPTIC_SOURCES ${SDL2_SOURCE_DIR}/src/haptic/darwin/*.c)
endif()
set(SOURCE_FILES ${SOURCE_FILES} ${HAPTIC_SOURCES})
set(HAVE_SDL_HAPTIC TRUE)
set(SDL_FRAMEWORK_IOKIT 1)
set(SDL_FRAMEWORK_FF 1)
if(NOT SDL_JOYSTICK)
message(FATAL_ERROR "SDL_HAPTIC requires SDL_JOYSTICK to be enabled")
endif()
endif()
if(SDL_POWER)
set(SDL_POWER_MACOSX 1)
if (IOS)
file(GLOB POWER_SOURCES ${SDL2_SOURCE_DIR}/src/power/uikit/*.m)
else()
file(GLOB POWER_SOURCES ${SDL2_SOURCE_DIR}/src/power/macosx/*.c)
endif()
set(SOURCE_FILES ${SOURCE_FILES} ${POWER_SOURCES})
set(HAVE_SDL_POWER TRUE)
set(SDL_FRAMEWORK_IOKIT 1)
endif()
if(SDL_TIMERS)
set(SDL_TIMER_UNIX 1)
file(GLOB TIMER_SOURCES ${SDL2_SOURCE_DIR}/src/timer/unix/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${TIMER_SOURCES})
set(HAVE_SDL_TIMERS TRUE)
endif(SDL_TIMERS)
if(SDL_FILESYSTEM)
set(SDL_FILESYSTEM_COCOA 1)
file(GLOB FILESYSTEM_SOURCES ${SDL2_SOURCE_DIR}/src/filesystem/cocoa/*.m)
# !!! FIXME: modern CMake doesn't need "LANGUAGE C" for Objective-C.
set_source_files_properties(${FILESYSTEM_SOURCES} PROPERTIES LANGUAGE C)
set(SOURCE_FILES ${SOURCE_FILES} ${FILESYSTEM_SOURCES})
set(HAVE_SDL_FILESYSTEM TRUE)
endif()
# Actually load the frameworks at the end so we don't duplicate include.
if(SDL_FRAMEWORK_COREVIDEO)
find_library(COREVIDEO CoreVideo)
list(APPEND EXTRA_LIBS ${COREVIDEO})
endif()
if(SDL_FRAMEWORK_COCOA)
find_library(COCOA_LIBRARY Cocoa)
list(APPEND EXTRA_LIBS ${COCOA_LIBRARY})
endif()
if(SDL_FRAMEWORK_IOKIT)
find_library(IOKIT IOKit)
list(APPEND EXTRA_LIBS ${IOKIT})
endif()
if(SDL_FRAMEWORK_FF)
find_library(FORCEFEEDBACK ForceFeedback)
list(APPEND EXTRA_LIBS ${FORCEFEEDBACK})
endif()
if(SDL_FRAMEWORK_CARBON)
find_library(CARBON_LIBRARY Carbon)
list(APPEND EXTRA_LIBS ${CARBON_LIBRARY})
endif()
if(SDL_FRAMEWORK_COREAUDIO)
find_library(COREAUDIO CoreAudio)
list(APPEND EXTRA_LIBS ${COREAUDIO})
endif()
if(SDL_FRAMEWORK_AUDIOTOOLBOX)
find_library(AUDIOTOOLBOX AudioToolbox)
list(APPEND EXTRA_LIBS ${AUDIOTOOLBOX})
endif()
# iOS hack needed - http://code.google.com/p/ios-cmake/ ?
if(SDL_VIDEO)
if (IOS)
set(SDL_VIDEO_DRIVER_UIKIT 1)
file(GLOB UIKITVIDEO_SOURCES ${SDL2_SOURCE_DIR}/src/video/uikit/*.m)
set(SOURCE_FILES ${SOURCE_FILES} ${UIKITVIDEO_SOURCES})
else()
CheckCOCOA()
if(VIDEO_OPENGL)
set(SDL_VIDEO_OPENGL 1)
set(SDL_VIDEO_OPENGL_CGL 1)
set(SDL_VIDEO_RENDER_OGL 1)
set(HAVE_VIDEO_OPENGL TRUE)
endif()
if(VIDEO_OPENGLES)
set(SDL_VIDEO_OPENGL_EGL 1)
set(SDL_VIDEO_OPENGL_ES2 1)
set(SDL_VIDEO_RENDER_OGL_ES2 1)
set(HAVE_VIDEO_OPENGLES TRUE)
endif()
endif()
endif()
CheckPTHREAD()
elseif(HAIKU)
if(SDL_VIDEO)
set(SDL_VIDEO_DRIVER_HAIKU 1)
file(GLOB HAIKUVIDEO_SOURCES ${SDL2_SOURCE_DIR}/src/video/haiku/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${HAIKUVIDEO_SOURCES})
set(HAVE_SDL_VIDEO TRUE)
set(SDL_FILESYSTEM_HAIKU 1)
file(GLOB FILESYSTEM_SOURCES ${SDL2_SOURCE_DIR}/src/filesystem/haiku/*.cc)
set(SOURCE_FILES ${SOURCE_FILES} ${FILESYSTEM_SOURCES})
set(HAVE_SDL_FILESYSTEM TRUE)
if(SDL_TIMERS)
set(SDL_TIMER_HAIKU 1)
file(GLOB TIMER_SOURCES ${SDL2_SOURCE_DIR}/src/timer/haiku/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${TIMER_SOURCES})
set(HAVE_SDL_TIMERS TRUE)
endif(SDL_TIMERS)
if(VIDEO_OPENGL)
# TODO: Use FIND_PACKAGE(OpenGL) instead
set(SDL_VIDEO_OPENGL 1)
set(SDL_VIDEO_OPENGL_BGL 1)
set(SDL_VIDEO_RENDER_OGL 1)
list(APPEND EXTRA_LIBS GL)
set(HAVE_VIDEO_OPENGL TRUE)
endif()
endif()
CheckPTHREAD()
endif()
if(VIDEO_VULKAN)
set(SDL_VIDEO_VULKAN 1)
set(HAVE_VIDEO_VULKAN TRUE)
endif()
# Dummies
# configure.ac does it differently:
# if not have X
# if enable_X { SDL_X_DISABLED = 1 }
# [add dummy sources]
# so it always adds a dummy, without checking, if it was actually requested.
# This leads to missing internal references on building, since the
# src/X/*.c does not get included.
if(NOT HAVE_SDL_JOYSTICK)
set(SDL_JOYSTICK_DUMMY 1)
if(SDL_JOYSTICK AND NOT APPLE) # results in unresolved symbols on OSX
file(GLOB JOYSTICK_SOURCES ${SDL2_SOURCE_DIR}/src/joystick/dummy/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${JOYSTICK_SOURCES})
endif()
endif()
if(NOT HAVE_SDL_HAPTIC)
set(SDL_HAPTIC_DUMMY 1)
file(GLOB HAPTIC_SOURCES ${SDL2_SOURCE_DIR}/src/haptic/dummy/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${HAPTIC_SOURCES})
endif()
if(NOT HAVE_SDL_SENSORS)
set(SDL_SENSOR_DUMMY 1)
file(GLOB SENSORS_SOURCES ${SDL2_SOURCE_DIR}/src/sensor/dummy/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${SENSORS_SOURCES})
endif()
if(NOT HAVE_SDL_LOADSO)
set(SDL_LOADSO_DISABLED 1)
file(GLOB LOADSO_SOURCES ${SDL2_SOURCE_DIR}/src/loadso/dummy/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${LOADSO_SOURCES})
endif()
if(NOT HAVE_SDL_FILESYSTEM)
set(SDL_FILESYSTEM_DISABLED 1)
file(GLOB FILESYSTEM_SOURCES ${SDL2_SOURCE_DIR}/src/filesystem/dummy/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${FILESYSTEM_SOURCES})
endif()
# We always need to have threads and timers around
if(NOT HAVE_SDL_THREADS)
set(SDL_THREADS_DISABLED 1)
file(GLOB THREADS_SOURCES ${SDL2_SOURCE_DIR}/src/thread/generic/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${THREADS_SOURCES})
endif()
if(NOT HAVE_SDL_TIMERS)
set(SDL_TIMERS_DISABLED 1)
file(GLOB TIMER_SOURCES ${SDL2_SOURCE_DIR}/src/timer/dummy/*.c)
set(SOURCE_FILES ${SOURCE_FILES} ${TIMER_SOURCES})
endif()
if(NOT SDLMAIN_SOURCES)
file(GLOB SDLMAIN_SOURCES ${SDL2_SOURCE_DIR}/src/main/dummy/*.c)
endif()
# Append the -MMD -MT flags
# if(DEPENDENCY_TRACKING)
# if(COMPILER_IS_GNUCC)
# set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -MMD -MT \$@")
# endif()
# endif()
configure_file("${SDL2_SOURCE_DIR}/include/SDL_config.h.cmake"
"${SDL2_BINARY_DIR}/include/SDL_config.h")
# Prepare the flags and remove duplicates
if(EXTRA_LDFLAGS)
list(REMOVE_DUPLICATES EXTRA_LDFLAGS)
endif()
if(EXTRA_LIBS)
list(REMOVE_DUPLICATES EXTRA_LIBS)
endif()
if(EXTRA_CFLAGS)
list(REMOVE_DUPLICATES EXTRA_CFLAGS)
endif()
listtostr(EXTRA_CFLAGS _EXTRA_CFLAGS)
set(EXTRA_CFLAGS ${_EXTRA_CFLAGS})
# Compat helpers for the configuration files
if(NOT WINDOWS OR CYGWIN)
# TODO: we need a Windows script, too
execute_process(COMMAND sh ${SDL2_SOURCE_DIR}/build-scripts/updaterev.sh)
set(prefix ${CMAKE_INSTALL_PREFIX})
set(exec_prefix "\${prefix}")
set(libdir "\${exec_prefix}/lib${LIB_SUFFIX}")
set(bindir "\${exec_prefix}/bin")
set(includedir "\${prefix}/include")
if(SDL_STATIC)
set(ENABLE_STATIC_TRUE "")
set(ENABLE_STATIC_FALSE "#")
else()
set(ENABLE_STATIC_TRUE "#")
set(ENABLE_STATIC_FALSE "")
endif()
if(SDL_SHARED)
set(ENABLE_SHARED_TRUE "")
set(ENABLE_SHARED_FALSE "#")
else()
set(ENABLE_SHARED_TRUE "#")
set(ENABLE_SHARED_FALSE "")
endif()
# Clean up the different lists
listtostr(EXTRA_LIBS _EXTRA_LIBS "-l")
set(SDL_STATIC_LIBS ${SDL_LIBS} ${EXTRA_LDFLAGS} ${_EXTRA_LIBS})
list(REMOVE_DUPLICATES SDL_STATIC_LIBS)
listtostr(SDL_STATIC_LIBS _SDL_STATIC_LIBS)
set(SDL_STATIC_LIBS ${_SDL_STATIC_LIBS})
listtostr(SDL_LIBS _SDL_LIBS)
set(SDL_LIBS ${_SDL_LIBS})
# MESSAGE(STATUS "SDL_LIBS: ${SDL_LIBS}")
# MESSAGE(STATUS "SDL_STATIC_LIBS: ${SDL_STATIC_LIBS}")
configure_file("${SDL2_SOURCE_DIR}/sdl2.pc.in"
"${SDL2_BINARY_DIR}/sdl2.pc" @ONLY)
configure_file("${SDL2_SOURCE_DIR}/sdl2-config.in"
"${SDL2_BINARY_DIR}/sdl2-config")
configure_file("${SDL2_SOURCE_DIR}/sdl2-config.in"
"${SDL2_BINARY_DIR}/sdl2-config" @ONLY)
configure_file("${SDL2_SOURCE_DIR}/SDL2.spec.in"
"${SDL2_BINARY_DIR}/SDL2.spec" @ONLY)
endif()
##### Info output #####
message(STATUS "")
message(STATUS "SDL2 was configured with the following options:")
message(STATUS "")
message(STATUS "Platform: ${CMAKE_SYSTEM}")
message(STATUS "64-bit: ${ARCH_64}")
message(STATUS "Compiler: ${CMAKE_C_COMPILER}")
message(STATUS "")
message(STATUS "Subsystems:")
foreach(_SUB ${SDL_SUBSYSTEMS})
string(TOUPPER ${_SUB} _OPT)
message_bool_option(${_SUB} SDL_${_OPT})
endforeach()
message(STATUS "")
message(STATUS "Options:")
list(SORT ALLOPTIONS)
foreach(_OPT ${ALLOPTIONS})
# Longest option is VIDEO_X11_XSCREENSAVER = 22 characters
# Get the padding
string(LENGTH ${_OPT} _OPTLEN)
math(EXPR _PADLEN "23 - ${_OPTLEN}")
string(RANDOM LENGTH ${_PADLEN} ALPHABET " " _PADDING)
message_tested_option(${_OPT} ${_PADDING})
endforeach()
message(STATUS "")
message(STATUS " CFLAGS: ${CMAKE_C_FLAGS}")
message(STATUS " EXTRA_CFLAGS: ${EXTRA_CFLAGS}")
message(STATUS " EXTRA_LDFLAGS: ${EXTRA_LDFLAGS}")
message(STATUS " EXTRA_LIBS: ${EXTRA_LIBS}")
message(STATUS "")
message(STATUS " Build Shared Library: ${SDL_SHARED}")
message(STATUS " Build Static Library: ${SDL_STATIC}")
if(SDL_STATIC)
message(STATUS " Build Static Library with Position Independent Code: ${SDL_STATIC_PIC}")
endif()
message(STATUS "")
if(UNIX)
message(STATUS "If something was not detected, although the libraries")
message(STATUS "were installed, then make sure you have set the")
message(STATUS "CFLAGS and LDFLAGS environment variables correctly.")
message(STATUS "")
endif()
# Ensure that the extra cflags are used at compile time
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
# Always build SDLmain
add_library(SDL2main STATIC ${SDLMAIN_SOURCES})
target_include_directories(SDL2main PUBLIC "$<BUILD_INTERFACE:${SDL2_SOURCE_DIR}/include>" $<INSTALL_INTERFACE:include/SDL2>)
set(_INSTALL_LIBS "SDL2main")
if (NOT ANDROID)
set_target_properties(SDL2main PROPERTIES DEBUG_POSTFIX ${SDL_CMAKE_DEBUG_POSTFIX})
endif()
if(SDL_SHARED)
add_library(SDL2 SHARED ${SOURCE_FILES} ${VERSION_SOURCES})
if(APPLE)
set_target_properties(SDL2 PROPERTIES
MACOSX_RPATH 1
OUTPUT_NAME "SDL2-${LT_RELEASE}")
elseif(UNIX AND NOT ANDROID)
set_target_properties(SDL2 PROPERTIES
VERSION ${LT_VERSION}
SOVERSION ${LT_REVISION}
OUTPUT_NAME "SDL2-${LT_RELEASE}")
else()
set_target_properties(SDL2 PROPERTIES
VERSION ${SDL_VERSION}
SOVERSION ${LT_REVISION}
OUTPUT_NAME "SDL2")
endif()
if(MSVC AND NOT LIBC)
# Don't try to link with the default set of libraries.
set_target_properties(SDL2 PROPERTIES LINK_FLAGS_RELEASE "/NODEFAULTLIB")
set_target_properties(SDL2 PROPERTIES LINK_FLAGS_DEBUG "/NODEFAULTLIB")
set_target_properties(SDL2 PROPERTIES STATIC_LIBRARY_FLAGS "/NODEFAULTLIB")
endif()
set(_INSTALL_LIBS "SDL2" ${_INSTALL_LIBS})
target_link_libraries(SDL2 ${EXTRA_LIBS} ${EXTRA_LDFLAGS})
target_include_directories(SDL2 PUBLIC "$<BUILD_INTERFACE:${SDL2_SOURCE_DIR}/include>" $<INSTALL_INTERFACE:include/SDL2>)
if (NOT ANDROID)
set_target_properties(SDL2 PROPERTIES DEBUG_POSTFIX ${SDL_CMAKE_DEBUG_POSTFIX})
endif()
endif()
if(ANDROID)
if(HAVE_HIDAPI)
add_library(hidapi SHARED ${SDL2_SOURCE_DIR}/src/hidapi/android/hid.cpp)
endif()
if(MSVC AND NOT LIBC)
# Don't try to link with the default set of libraries.
set_target_properties(hidapi PROPERTIES LINK_FLAGS_RELEASE "/NODEFAULTLIB")
set_target_properties(hidapi PROPERTIES LINK_FLAGS_DEBUG "/NODEFAULTLIB")
set_target_properties(hidapi PROPERTIES STATIC_LIBRARY_FLAGS "/NODEFAULTLIB")
endif()
target_link_libraries(hidapi log)
endif()
if(SDL_STATIC)
set (BUILD_SHARED_LIBS FALSE)
add_library(SDL2-static STATIC ${SOURCE_FILES})
if (NOT SDL_SHARED OR NOT WIN32)
set_target_properties(SDL2-static PROPERTIES OUTPUT_NAME "SDL2")
# Note: Apparently, OUTPUT_NAME must really be unique; even when
# CMAKE_IMPORT_LIBRARY_SUFFIX or the like are given. Otherwise
# the static build may race with the import lib and one will get
# clobbered, when the suffix is realized via subsequent rename.
endif()
set_target_properties(SDL2-static PROPERTIES POSITION_INDEPENDENT_CODE ${SDL_STATIC_PIC})
if(MSVC AND NOT LIBC)
set_target_properties(SDL2-static PROPERTIES LINK_FLAGS_RELEASE "/NODEFAULTLIB")
set_target_properties(SDL2-static PROPERTIES LINK_FLAGS_DEBUG "/NODEFAULTLIB")
set_target_properties(SDL2-static PROPERTIES STATIC_LIBRARY_FLAGS "/NODEFAULTLIB")
endif()
# TODO: Win32 platforms keep the same suffix .lib for import and static
# libraries - do we need to consider this?
set(_INSTALL_LIBS "SDL2-static" ${_INSTALL_LIBS})
target_link_libraries(SDL2-static ${EXTRA_LIBS} ${EXTRA_LDFLAGS})
target_include_directories(SDL2-static PUBLIC "$<BUILD_INTERFACE:${SDL2_SOURCE_DIR}/include>" $<INSTALL_INTERFACE:include/SDL2>)
if (NOT ANDROID)
set_target_properties(SDL2-static PROPERTIES DEBUG_POSTFIX ${SDL_CMAKE_DEBUG_POSTFIX})
endif()
endif()
##### Tests #####
if(SDL_TEST)
file(GLOB TEST_SOURCES ${SDL2_SOURCE_DIR}/src/test/*.c)
add_library(SDL2_test STATIC ${TEST_SOURCES})
add_subdirectory(test)
endif()
##### Installation targets #####
install(TARGETS ${_INSTALL_LIBS} EXPORT SDL2Targets
LIBRARY DESTINATION "lib${LIB_SUFFIX}"
ARCHIVE DESTINATION "lib${LIB_SUFFIX}"
RUNTIME DESTINATION bin)
##### Export files #####
if (WINDOWS)
set(PKG_PREFIX "cmake")
else ()
set(PKG_PREFIX "lib/cmake/SDL2")
endif ()
include(CMakePackageConfigHelpers)
write_basic_package_version_file("${CMAKE_BINARY_DIR}/SDL2ConfigVersion.cmake"
VERSION ${SDL_VERSION}
COMPATIBILITY AnyNewerVersion
)
install(EXPORT SDL2Targets
FILE SDL2Targets.cmake
NAMESPACE SDL2::
DESTINATION ${PKG_PREFIX}
)
install(
FILES
${CMAKE_CURRENT_SOURCE_DIR}/SDL2Config.cmake
${CMAKE_BINARY_DIR}/SDL2ConfigVersion.cmake
DESTINATION ${PKG_PREFIX}
COMPONENT Devel
)
file(GLOB INCLUDE_FILES ${SDL2_SOURCE_DIR}/include/*.h)
file(GLOB BIN_INCLUDE_FILES ${SDL2_BINARY_DIR}/include/*.h)
foreach(_FNAME ${BIN_INCLUDE_FILES})
get_filename_component(_INCNAME ${_FNAME} NAME)
list(REMOVE_ITEM INCLUDE_FILES ${SDL2_SOURCE_DIR}/include/${_INCNAME})
endforeach()
list(APPEND INCLUDE_FILES ${BIN_INCLUDE_FILES})
install(FILES ${INCLUDE_FILES} DESTINATION include/SDL2)
string(TOUPPER "${CMAKE_BUILD_TYPE}" UPPER_BUILD_TYPE)
if (UPPER_BUILD_TYPE MATCHES DEBUG)
set(SOPOSTFIX "${SDL_CMAKE_DEBUG_POSTFIX}")
else()
set(SOPOSTFIX "")
endif()
if(NOT (WINDOWS OR CYGWIN))
if(SDL_SHARED)
set(SOEXT ${CMAKE_SHARED_LIBRARY_SUFFIX}) # ".so", ".dylib", etc.
get_target_property(SONAME SDL2 OUTPUT_NAME)
if(NOT ANDROID)
install(CODE "
execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink
\"lib${SONAME}${SOPOSTFIX}${SOEXT}\" \"libSDL2${SOPOSTFIX}${SOEXT}\"
WORKING_DIRECTORY \"${SDL2_BINARY_DIR}\")")
install(FILES ${SDL2_BINARY_DIR}/libSDL2${SOPOSTFIX}${SOEXT} DESTINATION "lib${LIB_SUFFIX}")
endif()
endif()
if(FREEBSD)
# FreeBSD uses ${PREFIX}/libdata/pkgconfig
install(FILES ${SDL2_BINARY_DIR}/sdl2.pc DESTINATION "libdata/pkgconfig")
else()
install(FILES ${SDL2_BINARY_DIR}/sdl2.pc
DESTINATION "lib${LIB_SUFFIX}/pkgconfig")
endif()
install(PROGRAMS ${SDL2_BINARY_DIR}/sdl2-config DESTINATION bin)
# TODO: what about the .spec file? Is it only needed for RPM creation?
install(FILES "${SDL2_SOURCE_DIR}/sdl2.m4" DESTINATION "${CMAKE_INSTALL_FULL_DATAROOTDIR}/aclocal")
endif()
##### Uninstall target #####
if(NOT TARGET uninstall)
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"
IMMEDIATE @ONLY)
add_custom_target(uninstall
COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake)
endif()
| {
"pile_set_name": "Github"
} |
// custom colors
.form-control {
color: @font-level-2;
}
input.form-control {
line-height: 22px;
}
textarea, input {
// Firefox
&::-moz-placeholder {
color: #a6a6a6;
opacity: 1; // Override Firefox's unusual default opacity; see https://github.com/twbs/bootstrap/pull/11526
}
&:-ms-input-placeholder { color: #a6a6a6; } // Internet Explorer 10+
&::-webkit-input-placeholder { color: #a6a6a6; } // Safari and Chrome
-webkit-font-smoothing: subpixel-antialiased;
}
textarea.form-control {
resize: vertical;
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include "mmaped.h"
#include "Data.h"
#include "blas_routines.h"
using namespace EdgeML;
Data::Data(
DataIngestType ingestType_,
DataFormatParams formatParams_)
: isDataLoaded(false),
formatParams(formatParams_),
ingestType(ingestType_),
numPointsIngested(0)
{
// if(ingestType_ == InterfaceIngest)
// assert(formatParams_.numTestPoints == 0);
}
void Data::loadDataFromFile(
DataFormat format,
std::string infileTrain,
std::string infileValidation,
std::string infileTest)
{
assert(isDataLoaded == false);
assert(ingestType == FileIngest);
trainData = MatrixXuf(0, 0);
validationData = MatrixXuf(0, 0);
testData = MatrixXuf(0, 0);
Xtest = SparseMatrixuf(0, 0);
Xvalidation = SparseMatrixuf(0, 0);
Xtest = SparseMatrixuf(0, 0);
LOG_INFO("");
if (format == tsvFormat) {
if((!infileTrain.empty()) && (formatParams.numTrainPoints > 0)) {
LOG_INFO("Reading train data...");
FileIO::Data train(infileTrain,
trainData, trainLabel,
formatParams.numTrainPoints, 0, 1,
formatParams.dimension + 1, formatParams.dimension, formatParams.numLabels,
format);
}
if((!infileValidation.empty()) && (formatParams.numValidationPoints > 0)) {
LOG_INFO("Reading validation data...");
FileIO::Data validation(infileValidation,
validationData, validationLabel,
formatParams.numValidationPoints, 0, 1,
formatParams.dimension + 1, formatParams.dimension, formatParams.numLabels,
format);
}
if((!infileTest.empty()) && (formatParams.numTestPoints > 0)) {
LOG_INFO("Reading test data...");
FileIO::Data test(infileTest,
testData, testLabel,
formatParams.numTestPoints, 0, 1,
formatParams.dimension + 1, formatParams.dimension, formatParams.numLabels,
format);
}
}
else if (format == libsvmFormat) {
if((!infileTrain.empty()) && (formatParams.numTrainPoints > 0)) {
LOG_INFO("Reading train data...");
FileIO::Data train(infileTrain,
Xtrain, Ytrain,
formatParams.numTrainPoints, -1, -1,
-1, formatParams.dimension, formatParams.numLabels,
format);
}
if ((!infileValidation.empty()) && (formatParams.numValidationPoints > 0)) {
LOG_INFO("Reading validation data...");
FileIO::Data validation(infileValidation,
Xvalidation, Yvalidation,
formatParams.numValidationPoints, -1, -1,
-1, formatParams.dimension, formatParams.numLabels,
format);
}
if ((!infileTest.empty()) && (formatParams.numTestPoints > 0)) {
LOG_INFO("Reading test data...");
FileIO::Data test(infileTest,
Xtest, Ytest,
formatParams.numTestPoints, -1, -1,
-1, formatParams.dimension, formatParams.numLabels,
format);
}
}
else if (format == interfaceIngestFormat) {
labelCount_t *label = new labelCount_t[1];
if (!infileTrain.empty()) {
LOG_INFO("Reading train data...");
std::ifstream trainreader(infileTrain);
trainData = MatrixXuf::Zero(formatParams.dimension, formatParams.numTrainPoints);
trainLabel = MatrixXuf::Zero(formatParams.numLabels, formatParams.numTrainPoints);
FP_TYPE readLbl;
FP_TYPE readFeat;
for (dataCount_t i = 0; i < formatParams.numTrainPoints; ++i) {
trainreader >> readLbl;
label[0] = (labelCount_t)readLbl;
#ifdef ZERO_BASED_IO
trainLabel(label[0], i) = 1;
#else
trainLabel(label[0] - 1, i) = 1;
#endif
featureCount_t count = 0;
while (count < formatParams.dimension - 1) {
trainreader >> readFeat;
trainData(count, i) = readFeat;
count++;
}
trainData(count, i) = 1.0;
}
trainreader.close();
Xtrain = trainData.sparseView(); trainData.resize(0, 0);
Ytrain = trainLabel.sparseView(); trainLabel.resize(0, 0);
}
if (!infileValidation.empty()) {
LOG_INFO("Reading validation data...");
std::ifstream validationreader(infileValidation);
validationData = MatrixXuf::Zero(formatParams.dimension, formatParams.numValidationPoints);
validationLabel = MatrixXuf::Zero(formatParams.numLabels, formatParams.numValidationPoints);
FP_TYPE readLbl;
FP_TYPE readFeat;
for (dataCount_t i = 0; i < formatParams.numValidationPoints; ++i) {
validationreader >> readLbl;
label[0] = (labelCount_t)readLbl;
#ifdef ZERO_BASED_IO
validationLabel(label[0], i) = 1;
#else
validationLabel(label[0] - 1, i) = 1;
#endif
featureCount_t count = 0;
while (count < formatParams.dimension - 1) {
validationreader >> readFeat;
validationData(count, i) = readFeat;
count++;
}
validationData(count, i) = 1.0;
}
validationreader.close();
Xvalidation = validationData.sparseView(); validationData.resize(0, 0);
Yvalidation = validationLabel.sparseView(); validationLabel.resize(0, 0);
}
if (!infileTest.empty()) {
std::ifstream testreader(infileTest);
LOG_INFO("Reading test data...");
testData = MatrixXuf::Zero(formatParams.dimension, formatParams.numTestPoints);
testLabel = MatrixXuf::Zero(formatParams.numLabels, formatParams.numTestPoints);
FP_TYPE readLbl;
FP_TYPE readFeat;
for (dataCount_t i = 0; i < formatParams.numTestPoints; ++i) {
testreader >> readLbl;
label[0] = (labelCount_t)readLbl;
#ifdef ZERO_BASED_IO
testLabel(label[0], i) = 1;
#else
testLabel(label[0] - 1, i) = 1;
#endif
featureCount_t count = 0;
while (count < formatParams.dimension - 1) {
testreader >> readFeat;
testData(count, i) = readFeat;
count++;
}
testData(count, i) = 1.0;
}
testreader.close();
Xtest = testData.sparseView(); testData.resize(0, 0);
Ytest = testLabel.sparseView(); testLabel.resize(0, 0);
}
delete[] label;
}
else
assert(false);
}
void Data::finalizeData()
{
if (ingestType == FileIngest)
assert(sparseDataHolder.size() == 0 && denseDataHolder.size() == 0);
else if (ingestType == InterfaceIngest) {
//assert(!(sparseDataHolder.size() != 0 && denseDataHolder.size() != 0));
assert(sparseDataHolder.size() > 0 || denseDataHolder.size() >0);
formatParams.numTrainPoints = numPointsIngested;
formatParams.numTestPoints = 0;
formatParams.numValidationPoints = 0;
if (sparseDataHolder.size() != 0) {
if (denseDataHolder.size() != 0) {
dataCount_t numDensePointsIngested = (dataCount_t)(denseDataHolder.size() / formatParams.dimension);
dataCount_t numSparsePointsIngested = numPointsIngested - numDensePointsIngested;
for (dataCount_t densePt = 0; densePt < numDensePointsIngested; ++densePt)
for (featureCount_t dim = 0; dim < formatParams.dimension; ++dim)
sparseDataHolder.push_back(Trip(dim,
numSparsePointsIngested + densePt,
denseDataHolder[densePt*formatParams.dimension + dim]));
denseDataHolder.resize(0);
denseDataHolder.shrink_to_fit();
}
Xtrain = SparseMatrixuf(formatParams.dimension, numPointsIngested);
Xtrain.setFromTriplets(sparseDataHolder.begin(), sparseDataHolder.end());
sparseDataHolder.resize(0);
sparseDataHolder.shrink_to_fit();
Ytrain = SparseMatrixuf(formatParams.numLabels, numPointsIngested);
Ytrain.setFromTriplets(sparseLabelHolder.begin(), sparseLabelHolder.end());
sparseLabelHolder.resize(0);
sparseLabelHolder.shrink_to_fit();
}
else if (denseDataHolder.size() != 0) {
trainData = MatrixXuf(formatParams.dimension, numPointsIngested);
memcpy(trainData.data(), denseDataHolder.data(), sizeof(FP_TYPE)*trainData.rows()*trainData.cols());
denseDataHolder.resize(0);
denseDataHolder.shrink_to_fit();
Ytrain = SparseMatrixuf(formatParams.numLabels, numPointsIngested);
Ytrain.setFromTriplets(sparseLabelHolder.begin(), sparseLabelHolder.end());
sparseLabelHolder.resize(0);
sparseLabelHolder.shrink_to_fit();
}
else assert(false);
}
//
// Following lines check if the data was passed to the Data struct in dense or sparse format
// If data was passed in dense format, then it is guaranteed that:
// 1. getnnzs(Xtest) == 0
// 2. getnnzs(Xtrain) == 0
// 3. getnnzs(Ytest) == 0
// 4. getnnzs(Ytrain) == 0
// If these conditions are true, then we set these sparse matrices to their dense counter-parts
// Additionally, we deallocate the dense matrices. ProtoNN only uses the sparse data and label matrices.
//
if (getnnzs(Xtest) == 0) {
Xtest = testData.sparseView();
testData.resize(0, 0);
}
if (getnnzs(Xtrain) == 0) {
Xtrain = trainData.sparseView();
trainData.resize(0, 0);
}
if (getnnzs(Xvalidation) == 0) {
Xvalidation = validationData.sparseView();
validationData.resize(0, 0);
}
if (getnnzs(Ytest) == 0) {
Ytest = testLabel.sparseView();
testLabel.resize(0, 0);
}
if (getnnzs(Ytrain) == 0) {
Ytrain = trainLabel.sparseView();
trainLabel.resize(0, 0);
}
if (getnnzs(Yvalidation) == 0) {
Yvalidation = validationLabel.sparseView();
validationLabel.resize(0, 0);
}
min = MatrixXuf::Zero(0, 0);
max = MatrixXuf::Zero(0, 0);
/*
if(Xtest.cols() == 0){
Xtest = Xtrain;
}
if(Ytest.cols() == 0){
Ytest = Ytrain;
}*/
isDataLoaded = true;
}
void Data::feedDenseData(const DenseDataPoint& point)
{
assert(ingestType == InterfaceIngest);
assert(isDataLoaded == false);
denseDataHolder.insert(denseDataHolder.end(), point.values, point.values + formatParams.dimension);
for (labelCount_t id = 0; id < point.numLabels; id = id + 1) {
assert(point.labels[id] < formatParams.numLabels);
sparseLabelHolder.push_back(Trip(point.labels[id], numPointsIngested, 1.0));
}
numPointsIngested++;
}
void Data::feedSparseData(const SparseDataPoint& point)
{
assert(ingestType == InterfaceIngest);
assert(!isDataLoaded);
for (featureCount_t id = 0; id < point.numIndices; id = id + 1) {
assert(point.indices[id] < formatParams.dimension);
sparseDataHolder.push_back(Trip(point.indices[id], numPointsIngested, point.values[id]));
}
for (labelCount_t id = 0; id < point.numLabels; id = id + 1) {
assert(point.labels[id] < formatParams.numLabels);
sparseLabelHolder.push_back(Trip(point.labels[id], numPointsIngested, 1.0));
}
numPointsIngested++;
}
void EdgeML::computeMinMax(
const SparseMatrixuf& dataMatrix,
MatrixXuf& min,
MatrixXuf& max)
{
#ifdef ROWMAJOR
assert(false);
#endif
FP_TYPE * mn = new FP_TYPE[dataMatrix.rows()];
FP_TYPE * mx = new FP_TYPE[dataMatrix.rows()];
for (Eigen::Index i = 0; i < dataMatrix.rows(); ++i) {
mn[i] = 99999999999.0f;
mx[i] = -99999999999.0f;
}
const FP_TYPE * values = dataMatrix.valuePtr();
const sparseIndex_t * offsets = dataMatrix.innerIndexPtr();
Eigen::Index nnz = getnnzs(dataMatrix);
for (auto i = 0; i < nnz; ++i) {
mn[offsets[i]] = mn[offsets[i]] < values[i] ? mn[offsets[i]] : values[i];
mx[offsets[i]] = mx[offsets[i]] > values[i] ? mx[offsets[i]] : values[i];
}
featureCount_t zero_feats(0);
for (auto i = 0; i < dataMatrix.rows(); ++i) {
if (mn[i] == mx[i]) {
mn[i] = 0;
}
if (mx[i] < mn[i]) {
zero_feats++;
mx[i] = 1;
mn[i] = 0;
}
}
if (zero_feats > 0)
LOG_WARNING(std::to_string(zero_feats) + " features are always zero. Remove them if possible");
//Assert that min max parameter is not assigned
assert(min.rows() == 0);
//Ok, go ahead
min = MatrixXuf::Zero(dataMatrix.rows(), 1);
max = MatrixXuf::Zero(dataMatrix.rows(), 1);
pfor(featureCount_t i = 0; i < dataMatrix.rows(); ++i)
min(i, 0) = mn[i];
pfor(featureCount_t i = 0; i < dataMatrix.rows(); ++i)
max(i, 0) = mx[i];
delete[] mn;
delete[] mx;
}
void EdgeML::minMaxNormalize(
SparseMatrixuf& dataMatrix,
const MatrixXuf& min,
const MatrixXuf& max)
{
#ifdef ROWMAJOR
assert(false);
#endif
//Assert that min max parameter is already initialized
assert(min.rows() == dataMatrix.rows());
assert(max.rows() == dataMatrix.rows());
FP_TYPE * values = dataMatrix.valuePtr();
const sparseIndex_t * offsets = dataMatrix.innerIndexPtr();
Eigen::Index nnz = getnnzs(dataMatrix);
values = dataMatrix.valuePtr();
offsets = dataMatrix.innerIndexPtr();
nnz = getnnzs(dataMatrix);
for (auto i = 0; i < nnz; ++i) {
values[i] =
(values[i] - min(offsets[i], 0)) /
(max(offsets[i], 0) - min(offsets[i], 0));
}
}
void EdgeML::l2Normalize(SparseMatrixuf& dataMatrix)
{
#ifdef ROWMAJOR
assert(false);
#endif
assert(dataMatrix.outerSize() == dataMatrix.cols());
for (auto i = 0; i < dataMatrix.outerSize(); ++i) {
FP_TYPE norm = dataMatrix.col(i).norm();
for (SparseMatrixuf::InnerIterator it(dataMatrix, i); it; ++it) {
it.valueRef() = it.value() / norm;
}
}
}
void EdgeML::meanVarNormalize(
SparseMatrixuf& dataMatrix, //<
MatrixXuf& mean, //< Initialize to vector of size numFeatures
MatrixXuf& stdDev) //< Initialize to vector of size numFeatures
{
MatrixXuf denseDataMatrix = MatrixXuf(dataMatrix);
const Eigen::Index numDataPoints = denseDataMatrix.cols();
const Eigen::Index numFeatures = denseDataMatrix.rows();
// std::cout<<denseDataMatrix<<std::endl<<std::endl;
const MatrixXuf onesVec = MatrixXuf::Ones(numDataPoints, 1);
mm(mean, denseDataMatrix, CblasNoTrans, onesVec, CblasNoTrans, (FP_TYPE)1.0 / numDataPoints, (FP_TYPE)0.0);
mm(denseDataMatrix, mean, CblasNoTrans, onesVec, CblasTrans, (FP_TYPE)-1.0, (FP_TYPE)1.0);
denseDataMatrix.transposeInPlace();
for (Eigen::Index f = 0; f < numFeatures; f++) {
stdDev(f, 0) = (FP_TYPE)std::sqrt(dot(numDataPoints, denseDataMatrix.data() + f*numDataPoints, 1,
denseDataMatrix.data() + f*numDataPoints, 1)
/ numDataPoints);
if (!(fabs(stdDev(f, 0)) < (FP_TYPE)1e-7)) {
scal(numDataPoints, (FP_TYPE)1.0 / stdDev(f, 0), denseDataMatrix.data() + f*numDataPoints, 1);
}
else {
stdDev(f, 0) = (FP_TYPE)1.0;
}
}
for (Eigen::Index d = 0; d < numDataPoints; d++) {
denseDataMatrix(d, numFeatures - 1) = (FP_TYPE)1.0;
}
denseDataMatrix.transposeInPlace();
dataMatrix = denseDataMatrix.sparseView();
}
void EdgeML::saveMinMax(
const MatrixXuf& min,
const MatrixXuf& max,
std::string fileName)
{
#ifdef ROWMAJOR
assert(false);
#endif
// Assert the min max params are already assigned
assert(min.rows() > 0);
assert(max.rows() > 0);
std::ofstream out(fileName);
//out.open(fileName);
for (auto i = 0; i < min.rows(); i++)
out << min(i, 0) << '\t';
out << '\n';
for (auto i = 0; i < max.rows(); i++)
out << max(i, 0) << '\t';
out << '\n';
}
void EdgeML::loadMinMax(
MatrixXuf& min,
MatrixXuf& max,
int dim,
std::string fileName)
{
#ifdef ROWMAJOR
assert(false);
#endif
// Assert that min max params are not assigned
assert(min.rows() == 0);
//Ok, go ahead
min = MatrixXuf::Zero(dim, 1);
max = MatrixXuf::Zero(dim, 1);
LOG_INFO("Loading min-max normalization parameters from file: " + fileName);
std::ifstream in(fileName);
//in.open(fileName);
for (auto i = 0; i < dim; i++)
in >> min(i, 0);
for (auto i = 0; i < dim; i++)
in >> max(i, 0);
in.close();
}
// void EdgeML::meanVarNormalize(
// MatrixXuf& dataMatrix, //<
// MatrixXuf& mean, //< Initialize to vector of size numFeatures
// MatrixXuf& stdDev) //< Initialize to vector of size numFeatures
// {
// const Eigen::Index numDataPoints = dataMatrix.cols();
// const Eigen::Index numFeatures = dataMatrix.rows();
// assert(mean.rows() == numFeatures);
// assert(stdDev.rows() == numFeatures);
// const MatrixXuf onesVec = MatrixXuf::Ones(numDataPoints, 1);
// mm(mean, dataMatrix, CblasNoTrans, onesVec, CblasNoTrans, (FP_TYPE)1.0/numDataPoints, (FP_TYPE)0.0);
// mm(dataMatrix, mean, CblasNoTrans, onesVec, CblasTrans, (FP_TYPE)-1.0, (FP_TYPE)1.0);
// dataMatrix.transposeInPlace();
// for(featureCount_t f = 0; f < numFeatures; f++) {
// stdDev(f,0) = (FP_TYPE)std::sqrt(dot(numDataPoints, dataMatrix.data() + f*numDataPoints, 1,
// dataMatrix.data() + f*numDataPoints, 1)
// / numDataPoints);
// if(!(fabs(stdDev(f, 0)) < (FP_TYPE)1e-7)) {
// scal(numDataPoints, (FP_TYPE)1.0/stdDev(f,0), dataMatrix.data() + f*numDataPoints, 1);
// }
// else {
// stdDev(f, 0) = (FP_TYPE)1.0;
// }
// }
// for(dataCount_t d = 0; d < numDataPoints; d++) {
// dataMatrix(d, numFeatures-1) = (FP_TYPE)1.0;
// }
// dataMatrix.transposeInPlace();
// dataMatrix = dataMatrix.sparseView();
// }
| {
"pile_set_name": "Github"
} |
<a href='https://github.com/angular/angular.js/edit/v1.3.x/src/ngResource/resource.js?message=docs($resource)%3A%20describe%20your%20change...#L62' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<a href='https://github.com/angular/angular.js/tree/v1.3.1/src/ngResource/resource.js#L62' class='view-source pull-right btn btn-primary'>
<i class="glyphicon glyphicon-zoom-in"> </i>View Source
</a>
<header class="api-profile-header">
<h1 class="api-profile-header-heading">$resource</h1>
<ol class="api-profile-header-structure naked-list step-list">
<li>
- service in module <a href="api/ngResource">ngResource</a>
</li>
</ol>
</header>
<div class="api-profile-description">
<p>A factory which creates a resource object that lets you interact with
<a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">RESTful</a> server-side data sources.</p>
<p>The returned resource object has action methods which provide high-level behaviors without
the need to interact with the low level <a href="api/ng/service/$http">$http</a> service.</p>
<p>Requires the <a href="api/ngResource"><code>ngResource</code></a> module to be installed.</p>
<p>By default, trailing slashes will be stripped from the calculated URLs,
which can pose problems with server backends that do not expect that
behavior. This can be disabled by configuring the <code>$resourceProvider</code> like
this:</p>
<pre><code class="lang-js">app.config(['$resourceProvider', function($resourceProvider) {
// Don't strip trailing slashes from calculated URLs
$resourceProvider.defaults.stripTrailingSlashes = false;
}]);
</code></pre>
</div>
<div>
<h2 id="dependencies">Dependencies</h2>
<ul>
<li><a href="api/ng/service/$http"><code>$http</code></a></li>
</ul>
<h2 id="usage">Usage</h2>
<p><code>$resource(url, [paramDefaults], [actions], options);</code></p>
<section class="api-section">
<h3>Arguments</h3>
<table class="variables-matrix input-arguments">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
url
</td>
<td>
<a href="" class="label type-hint type-hint-string">string</a>
</td>
<td>
<p>A parametrized URL template with parameters prefixed by <code>:</code> as in
<code>/user/:username</code>. If you are using a URL with a port number (e.g.
<code>http://example.com:8080/api</code>), it will be respected.</p>
<p> If you are using a url with a suffix, just add the suffix, like this:
<code>$resource('http://example.com/resource.json')</code> or <code>$resource('http://example.com/:id.json')</code>
or even <code>$resource('http://example.com/resource/:resource_id.:format')</code>
If the parameter before the suffix is empty, :resource_id in this case, then the <code>/.</code> will be
collapsed down to a single <code>.</code>. If you need this sequence to appear and not collapse then you
can escape it with <code>/\.</code>.</p>
</td>
</tr>
<tr>
<td>
paramDefaults
<div><em>(optional)</em></div>
</td>
<td>
<a href="" class="label type-hint type-hint-object">Object</a>
</td>
<td>
<p>Default values for <code>url</code> parameters. These can be overridden in
<code>actions</code> methods. If any of the parameter value is a function, it will be executed every time
when a param value needs to be obtained for a request (unless the param was overridden).</p>
<p> Each key value in the parameter object is first bound to url template if present and then any
excess keys are appended to the url search query after the <code>?</code>.</p>
<p> Given a template <code>/path/:verb</code> and parameter <code>{verb:'greet', salutation:'Hello'}</code> results in
URL <code>/path/greet?salutation=Hello</code>.</p>
<p> If the parameter value is prefixed with <code>@</code> then the value for that parameter will be extracted
from the corresponding property on the <code>data</code> object (provided when calling an action method). For
example, if the <code>defaultParam</code> object is <code>{someParam: '@someProp'}</code> then the value of <code>someParam</code>
will be <code>data.someProp</code>.</p>
</td>
</tr>
<tr>
<td>
actions
<div><em>(optional)</em></div>
</td>
<td>
<a href="" class="label type-hint type-hint-object">Object.<Object>=</a>
</td>
<td>
<p>Hash with declaration of custom action that should extend
the default set of resource actions. The declaration should be created in the format of <a href="api/ng/service/$http#usage">$http.config</a>:</p>
<pre><code>{action1: {method:?, params:?, isArray:?, headers:?, ...},
action2: {method:?, params:?, isArray:?, headers:?, ...},
...}
</code></pre>
<p> Where:</p>
<ul>
<li><strong><code>action</code></strong> – {string} – The name of action. This name becomes the name of the method on
your resource object.</li>
<li><strong><code>method</code></strong> – {string} – Case insensitive HTTP method (e.g. <code>GET</code>, <code>POST</code>, <code>PUT</code>,
<code>DELETE</code>, <code>JSONP</code>, etc).</li>
<li><strong><code>params</code></strong> – {Object=} – Optional set of pre-bound parameters for this action. If any of
the parameter value is a function, it will be executed every time when a param value needs to
be obtained for a request (unless the param was overridden).</li>
<li><strong><code>url</code></strong> – {string} – action specific <code>url</code> override. The url templating is supported just
like for the resource-level urls.</li>
<li><strong><code>isArray</code></strong> – {boolean=} – If true then the returned object for this action is an array,
see <code>returns</code> section.</li>
<li><strong><code>transformRequest</code></strong> –
<code>{function(data, headersGetter)|Array.<function(data, headersGetter)>}</code> –
transform function or an array of such functions. The transform function takes the http
request body and headers and returns its transformed (typically serialized) version.
By default, transformRequest will contain one function that checks if the request data is
an object and serializes to using <code>angular.toJson</code>. To prevent this behavior, set
<code>transformRequest</code> to an empty array: <code>transformRequest: []</code></li>
<li><strong><code>transformResponse</code></strong> –
<code>{function(data, headersGetter)|Array.<function(data, headersGetter)>}</code> –
transform function or an array of such functions. The transform function takes the http
response body and headers and returns its transformed (typically deserialized) version.
By default, transformResponse will contain one function that checks if the response looks like
a JSON string and deserializes it using <code>angular.fromJson</code>. To prevent this behavior, set
<code>transformResponse</code> to an empty array: <code>transformResponse: []</code></li>
<li><strong><code>cache</code></strong> – <code>{boolean|Cache}</code> – If true, a default $http cache will be used to cache the
GET request, otherwise if a cache instance built with
<a href="api/ng/service/$cacheFactory">$cacheFactory</a>, this cache will be used for
caching.</li>
<li><strong><code>timeout</code></strong> – <code>{number|Promise}</code> – timeout in milliseconds, or <a href="api/ng/service/$q">promise</a> that
should abort the request when resolved.</li>
<li><strong><code>withCredentials</code></strong> - <code>{boolean}</code> - whether to set the <code>withCredentials</code> flag on the
XHR object. See
<a href="https://developer.mozilla.org/en/http_access_control#section_5">requests with credentials</a>
for more information.</li>
<li><strong><code>responseType</code></strong> - <code>{string}</code> - see
<a href="https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType">requestType</a>.</li>
<li><strong><code>interceptor</code></strong> - <code>{Object=}</code> - The interceptor object has two optional methods -
<code>response</code> and <code>responseError</code>. Both <code>response</code> and <code>responseError</code> interceptors get called
with <code>http response</code> object. See <a href="api/ng/service/$http">$http interceptors</a>.</li>
</ul>
</td>
</tr>
<tr>
<td>
options
</td>
<td>
<a href="" class="label type-hint type-hint-object">Object</a>
</td>
<td>
<p>Hash with custom settings that should extend the
default <code>$resourceProvider</code> behavior. The only supported option is</p>
<p> Where:</p>
<ul>
<li><strong><code>stripTrailingSlashes</code></strong> – {boolean} – If true then the trailing
slashes from any calculated URL will be stripped. (Defaults to true.)</li>
</ul>
</td>
</tr>
</tbody>
</table>
</section>
<h3>Returns</h3>
<table class="variables-matrix return-arguments">
<tr>
<td><a href="" class="label type-hint type-hint-object">Object</a></td>
<td><p>A resource "class" object with methods for the default set of resource actions
optionally extended with custom <code>actions</code>. The default set contains these actions:</p>
<pre><code class="lang-js">{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
</code></pre>
<p> Calling these methods invoke an <a href="api/ng/service/$http"><code>$http</code></a> with the specified http method,
destination and parameters. When the data is returned from the server then the object is an
instance of the resource class. The actions <code>save</code>, <code>remove</code> and <code>delete</code> are available on it
as methods with the <code>$</code> prefix. This allows you to easily perform CRUD operations (create,
read, update, delete) on server-side data like this:</p>
<pre><code class="lang-js">var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</code></pre>
<p> It is important to realize that invoking a $resource object method immediately returns an
empty reference (object or array depending on <code>isArray</code>). Once the data is returned from the
server the existing reference is populated with the actual data. This is a useful trick since
usually the resource is assigned to a model which is then rendered by the view. Having an empty
object results in no rendering, once the data arrives from the server then the object is
populated with the data and the view automatically re-renders itself showing the new data. This
means that in most cases one never has to write a callback function for the action methods.</p>
<p> The action methods on the class object or instance object can be invoked with the following
parameters:</p>
<ul>
<li>HTTP GET "class" actions: <code>Resource.action([parameters], [success], [error])</code></li>
<li>non-GET "class" actions: <code>Resource.action([parameters], postData, [success], [error])</code></li>
<li><p>non-GET instance actions: <code>instance.$action([parameters], [success], [error])</code></p>
<p>Success callback is called with (value, responseHeaders) arguments. Error callback is called
with (httpResponse) argument.</p>
<p>Class actions return empty instance (with additional properties below).
Instance actions return promise of the action.</p>
<p>The Resource instances and collection have these additional properties:</p>
</li>
<li><p><code>$promise</code>: the <a href="api/ng/service/$q">promise</a> of the original server interaction that created this
instance or collection.</p>
<p>On success, the promise is resolved with the same resource instance or collection object,
updated with data from server. This makes it easy to use in
<a href="api/ngRoute/provider/$routeProvider">resolve section of $routeProvider.when()</a> to defer view
rendering until the resource(s) are loaded.</p>
<p>On failure, the promise is resolved with the <a href="api/ng/service/$http">http response</a> object, without
the <code>resource</code> property.</p>
<p>If an interceptor object was provided, the promise will instead be resolved with the value
returned by the interceptor.</p>
</li>
<li><p><code>$resolved</code>: <code>true</code> after first server interaction is completed (either with success or
rejection), <code>false</code> before that. Knowing if the Resource has been resolved is useful in
data-binding.</p>
</li>
</ul>
</td>
</tr>
</table>
<h2 id="example">Example</h2><h1 id="credit-card-resource">Credit card resource</h1>
<pre><code class="lang-js">// Define CreditCard class
var CreditCard = $resource('/user/:userId/card/:cardId',
{userId:123, cardId:'@id'}, {
charge: {method:'POST', params:{charge:true}}
});
// We can retrieve a collection from the server
var cards = CreditCard.query(function() {
// GET: /user/123/card
// server returns: [ {id:456, number:'1234', name:'Smith'} ];
var card = cards[0];
// each item is an instance of CreditCard
expect(card instanceof CreditCard).toEqual(true);
card.name = "J. Smith";
// non GET methods are mapped onto the instances
card.$save();
// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
// our custom method is mapped as well.
card.$charge({amount:9.99});
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
});
// we can create an instance as well
var newCard = new CreditCard({number:'0123'});
newCard.name = "Mike Smith";
newCard.$save();
// POST: /user/123/card {number:'0123', name:'Mike Smith'}
// server returns: {id:789, number:'0123', name: 'Mike Smith'};
expect(newCard.id).toEqual(789);
</code></pre>
<p>The object returned from this function execution is a resource "class" which has "static" method
for each action in the definition.</p>
<p>Calling these methods invoke <code>$http</code> on the <code>url</code> template with the given <code>method</code>, <code>params</code> and
<code>headers</code>.
When the data is returned from the server then the object is an instance of the resource type and
all of the non-GET methods are available with <code>$</code> prefix. This allows you to easily support CRUD
operations (create, read, update, delete) on server-side data.</p>
<pre><code class="lang-js">var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(user) {
user.abc = true;
user.$save();
});
</code></pre>
<p>It's worth noting that the success callback for <code>get</code>, <code>query</code> and other methods gets passed
in the response that came from the server as well as $http header getter function, so one
could rewrite the above example and get access to http headers as:</p>
<pre><code class="lang-js">var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(u, getResponseHeaders){
u.abc = true;
u.$save(function(u, putResponseHeaders) {
//u => saved user object
//putResponseHeaders => $http header getter
});
});
</code></pre>
<p>You can also access the raw <code>$http</code> promise via the <code>$promise</code> property on the object returned</p>
<pre><code>var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123})
.$promise.then(function(user) {
$scope.user = user;
});
</code></pre>
<h1 id="creating-a-custom-put-request">Creating a custom 'PUT' request</h1>
<p>In this example we create a custom method on our resource to make a PUT request</p>
<pre><code class="lang-js">var app = angular.module('app', ['ngResource', 'ngRoute']);
// Some APIs expect a PUT request in the format URL/object/ID
// Here we are creating an 'update' method
app.factory('Notes', ['$resource', function($resource) {
return $resource('/notes/:id', null,
{
'update': { method:'PUT' }
});
}]);
// In our controller we get the ID from the URL using ngRoute and $routeParams
// We pass in $routeParams and our Notes factory along with $scope
app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
function($scope, $routeParams, Notes) {
// First get a note object from the factory
var note = Notes.get({ id:$routeParams.id });
$id = note.id;
// Now call update passing in the ID first then the object you are updating
Notes.update({ id:$id }, note);
// This will PUT /notes/ID with the note object in the request payload
}]);
</code></pre>
</div>
| {
"pile_set_name": "Github"
} |
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>spec.html</title>
<link href="toc/style/github-bf51422f4bb36427d391e4b75a1daa083c2d840e.css" media="all" rel="stylesheet" type="text/css"/>
<link href="toc/style/github2-d731afd4f624c99a4b19ad69f3083cd6d02b81d5.css" media="all" rel="stylesheet" type="text/css"/>
<link href="toc/css/zTreeStyle/zTreeStyle.css" media="all" rel="stylesheet" type="text/css"/>
<style>
pre {
counter-reset: line-numbering;
border: solid 1px #d9d9d9;
border-radius: 0;
background: #fff;
padding: 0;
line-height: 23px;
margin-bottom: 30px;
white-space: pre;
overflow-x: auto;
word-break: inherit;
word-wrap: inherit;
}
pre a::before {
content: counter(line-numbering);
counter-increment: line-numbering;
padding-right: 1em; /* space after numbers */
width: 25px;
text-align: right;
opacity: 0.7;
display: inline-block;
color: #aaa;
background: #eee;
margin-right: 16px;
padding: 2px 10px;
font-size: 13px;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
pre a:first-of-type::before {
padding-top: 10px;
}
pre a:last-of-type::before {
padding-bottom: 10px;
}
pre a:only-of-type::before {
padding: 10px;
}
.highlight { background-color: #ffffcc } /* RIGHT */
.highlight .hll { background-color: #ffffcc }
.highlight { background: #f0f0f0; }
.highlight .c { color: #60a0b0; font-style: italic } /* Comment */
.highlight .err { border: 1px solid #FF0000 } /* Error */
.highlight .k { color: #007020; font-weight: bold } /* Keyword */
.highlight .o { color: #666666 } /* Operator */
.highlight .ch { color: #60a0b0; font-style: italic } /* Comment.Hashbang */
.highlight .cm { color: #60a0b0; font-style: italic } /* Comment.Multiline */
.highlight .cp { color: #007020 } /* Comment.Preproc */
.highlight .cpf { color: #60a0b0; font-style: italic } /* Comment.PreprocFile */
.highlight .c1 { color: #60a0b0; font-style: italic } /* Comment.Single */
.highlight .cs { color: #60a0b0; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #A00000 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #FF0000 } /* Generic.Error */
.highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.highlight .gi { color: #00A000 } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.highlight .gt { color: #0044DD } /* Generic.Traceback */
.highlight .kc { color: #007020; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #007020; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #007020; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #007020 } /* Keyword.Pseudo */
.highlight .kr { color: #007020; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #902000 } /* Keyword.Type */
.highlight .m { color: #40a070 } /* Literal.Number */
.highlight .s { color: #4070a0 } /* Literal.String */
.highlight .na { color: #4070a0 } /* Name.Attribute */
.highlight .nb { color: #007020 } /* Name.Builtin */
.highlight .nc { color: #0e84b5; font-weight: bold } /* Name.Class */
.highlight .no { color: #60add5 } /* Name.Constant */
.highlight .nd { color: #555555; font-weight: bold } /* Name.Decorator */
.highlight .ni { color: #d55537; font-weight: bold } /* Name.Entity */
.highlight .ne { color: #007020 } /* Name.Exception */
.highlight .nf { color: #06287e } /* Name.Function */
.highlight .nl { color: #002070; font-weight: bold } /* Name.Label */
.highlight .nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */
.highlight .nt { color: #062873; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #bb60d5 } /* Name.Variable */
.highlight .ow { color: #007020; font-weight: bold } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #40a070 } /* Literal.Number.Bin */
.highlight .mf { color: #40a070 } /* Literal.Number.Float */
.highlight .mh { color: #40a070 } /* Literal.Number.Hex */
.highlight .mi { color: #40a070 } /* Literal.Number.Integer */
.highlight .mo { color: #40a070 } /* Literal.Number.Oct */
.highlight .sa { color: #4070a0 } /* Literal.String.Affix */
.highlight .sb { color: #4070a0 } /* Literal.String.Backtick */
.highlight .sc { color: #4070a0 } /* Literal.String.Char */
.highlight .dl { color: #4070a0 } /* Literal.String.Delimiter */
.highlight .sd { color: #4070a0; font-style: italic } /* Literal.String.Doc */
.highlight .s2 { color: #4070a0 } /* Literal.String.Double */
.highlight .se { color: #4070a0; font-weight: bold } /* Literal.String.Escape */
.highlight .sh { color: #4070a0 } /* Literal.String.Heredoc */
.highlight .si { color: #70a0d0; font-style: italic } /* Literal.String.Interpol */
.highlight .sx { color: #c65d09 } /* Literal.String.Other */
.highlight .sr { color: #235388 } /* Literal.String.Regex */
.highlight .s1 { color: #4070a0 } /* Literal.String.Single */
.highlight .ss { color: #517918 } /* Literal.String.Symbol */
.highlight .bp { color: #007020 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #06287e } /* Name.Function.Magic */
.highlight .vc { color: #bb60d5 } /* Name.Variable.Class */
.highlight .vg { color: #bb60d5 } /* Name.Variable.Global */
.highlight .vi { color: #bb60d5 } /* Name.Variable.Instance */
.highlight .vm { color: #bb60d5 } /* Name.Variable.Magic */
.highlight .il { color: #40a070 } /* Literal.Number.Integer.Long */</style>
</head>
<body>
<div>
<div style='width:25%; '>
<ul id="tree" class="ztree" style='width:100%;'>
</ul>
</div>
<div id='readme' style='width:70%;margin-left:20%;'>
<article class='markdown-body'>
<h1 id="toc_0">百度DuerOS车载版接入指南</h1>
<blockquote>
<p>百度DuerOS车载版,版权归百度公司所有,侵权必究</p>
<p>联系email:[email protected]</p>
</blockquote>
<h1 id="toc_1">简介</h1>
<h2 id="toc_2">DuerOS车载版是什么</h2>
<p>百度DuerOS是百度推出的对话式人工智能系统,广泛支持各类硬件设备,已具备70多项能力。百度DuerOS车载版是针对联网汽车,以智能语音为人机交互方式,基于百度的语音技术和自然语言处理技术等AI技术打造的全语音交互整体解决方案。</p>
<p>DuerOS车载版可以提供语音交互、电话、音乐和导航四大功能。车主在驾驶过程中可以随时通过语音完成导航、音乐、电话等操作,可以让驾驶者从繁琐枯燥的驾车程序中解脱出来,让行车更安全、便捷和经济,并且借助于百度所连接的众多O2O生态获取停车、加油、保养等车后服务。</p>
<p>本文档是DuerOS车载版 语音交互接入详细指南,为合作方在车机端接入DuerOS车载版的开发提供硬件、系统和软件实现等方面特别是语音交互集成的详细指导。</p>
<h2 id="toc_3">怎么接入DuerOS车载版</h2>
<blockquote>
<p>DuerOS车载版暂时不支持个人开发者的接入。
目前DuerOS车载版主要发布了Andriod系统的解决方案及在线云API服务。Linux、QNX、IOS等其他系统的解决方案暂未支持。</p>
</blockquote>
<p>DuerOS车载版目前主要面向车厂、车机方案商、芯片商、运营商等开放接入,下面简称DuerOS合作方。接入流程有</p>
<ol>
<li>商务沟通:DuerOS合作方联系百度商务(<a href="mailto:[email protected]" title="[email protected]">[email protected]</a>),进行NDA等合同签署。</li>
<li>开发包获取:完成商务流程后,DuerOS合作方即可获得<a href="#DuerOS%E5%8F%91%E5%B8%83%E5%8C%85%E5%8C%85%E5%90%AB%E4%BB%80%E4%B9%88%E5%86%85%E5%AE%B9">DuerOS车载版发布包及其相关文档</a>下载地址。</li>
<li>接入适配:拿到发布包后,根据文档及自己的需求进行适配接入,完成接入后DuerOS合作方需根据百度提供的<a href="#DuerOS%E6%B5%8B%E8%AF%95%E9%AA%8C%E6%94%B6%E6%B5%81%E7%A8%8B">验收文档</a>
进行验收。</li>
<li>百度验收:在DuerOS合作方验收通过后,邮寄预量产的设备给百度,由百度进行验收,百度验收通过的设备都将获得授权、发布签名和认证。邮寄地址请联系百度商务获得。</li>
<li>量产发布:由DuerOS合作方负责,百度可适当参与PR等工作。</li>
</ol>
<p>如下情况,请联系百度商务(<a href="mailto:[email protected]" title="[email protected]">[email protected]</a>)沟通确定。</p>
<blockquote>
<p>1.针对前装车厂,需要更多紧密研发和耦合获得更好效果的。</p>
<p>2.存在定制需求的。</p>
</blockquote>
<h2 id="toc_4">发布包包含什么内容</h2>
<p><a name="DuerOS发布包包含什么内容" ></a></p>
<blockquote>
<p>所有DuerOS合作方只要与百度商务(<a href="mailto:[email protected]" title="[email protected]">[email protected]</a>)完成NDA协议签订,就可以获得DuerOS车载版发布包。</p>
</blockquote>
<p>DuerOS发布包主要包含了3个APK、1个SDK、文档和示例代码组成。</p>
<h3 id="toc_5">APK目录</h3>
<p>该目录包含3个APK:</p>
<ul>
<li>DuerOS_Auto_*.*.*_Release.apk:语音交互核心模块,是DuerOS运行必选。</li>
<li>DuerOS_CarRadio_*.*.*_Release.apk:语音内容生态电台,与语音交互结合提供海量语音内容,如歌曲、戏曲、广播等。</li>
<li>DuerOS_MapAuto*.*.*_Release.apk:车载版本百度地图。</li>
</ul>
<h3 id="toc_6">SDK目录</h3>
<p>custom-sdk-release-*.*.*.jar: DuerOS提供的SDK,通过该SDK可以与DuerOS进行通信,实现各种SDK开发者定制功能。</p>
<h3 id="toc_7">Doc目录</h3>
<p>该目录主要包含3个说明文档:</p>
<ul>
<li>接入指南.html:包含了DuerOS车载版的架构、策略、API、注意事项说明,是开发者的主要参考依据。</li>
<li>语音指令集.xlsx: 目前DuerOS推荐的指令样例集合。</li>
<li>api文档:包含所有的类和接口说明</li>
</ul>
<h3 id="toc_8">Demo目录</h3>
<p>这是百度apollo开源计划的代码开源一小分支,该目录包含了如下开源代码:</p>
<ul>
<li>DuerOS CustomAPP代码:该代码主要包含如何使用SDK开发自己的应用与DuerOS进行通信互动。</li>
</ul>
<h2 id="toc_9">推荐的软硬件配置</h2>
<p>为了让DuerOS在你的设备上运行良好,我们推荐设备配置如下</p>
<table>
<thead>
<tr>
<th style="text-align: left">Head Unit Specs</th>
<th style="text-align: left">Recommended Requirement</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">CPU</td>
<td style="text-align: left">Cortex A9 dual cores、 1.2GHz</td>
</tr>
<tr>
<td style="text-align: left">RAM</td>
<td style="text-align: left">2GB</td>
</tr>
<tr>
<td style="text-align: left">NETWORK</td>
<td style="text-align: left">3G、4G</td>
</tr>
<tr>
<td style="text-align: left">STORAGE</td>
<td style="text-align: left">8GB</td>
</tr>
<tr>
<td style="text-align: left">TELEPHONE</td>
<td style="text-align: left">BLUETOOTH 4.0 or beyond</td>
</tr>
<tr>
<td style="text-align: left">Mic Input</td>
<td style="text-align: left">Support echo cancellation, SNR > 10dB, 16bit, 16KHz, mplitude ∈ (2000、 30000)</td>
</tr>
<tr>
<td style="text-align: left">OS</td>
<td style="text-align: left">Android 4.1 or beyond</td>
</tr>
<tr>
<td style="text-align: left">GPS</td>
<td style="text-align: left">GPS、A-GPS</td>
</tr>
</tbody>
</table>
<h2 id="toc_10">整体架构</h2>
<p>DuerOS车载版技术架构主要包含三个方面,分别是硬件平台层、核心层以及第三方服务和内容(比如音乐、导航、地图以及FM等应用),主要架构如下图:
<img src="img/DuerOS%20Auto%E6%8A%80%E6%9C%AF%E6%9E%B6%E6%9E%84.png" alt="DuerOS车载版框架图"></p>
<p>核心模块是语音模块和通信模块。语音模块获取用户的输入,与服务端进行交互对用户的语音进行识别、解析,得到语义解析的结果传给指令模块生成对应的指令,并传给通信模块,通过IPC将各指令传递给第三方服务或者内容进行执行,并将执行结果以及数据反馈给通信模块,传递到UI层进行展示。其中语音模块作为客户端的核心模块,主要包括语音引擎管理、自定义唤醒词、自定义场景化命令词、自定义离线指令、第三方录音、回声消噪等模块。除此之外,客户端还需要支持统计埋点、根据服务端配置动态调整策略、路况电台、OTA升级等功能。</p>
<p>语音引擎目前使用百度自主研发的语音识别引擎,封装了语音采集、语音预处理、在线识别、离线识别等功能,识别准确率高达97%。语音播报使用百度自主研发的TTS引擎,目前支持对语速、音调、音量等的配置,支持标准男女声、情感化男女声的TTS播报服务,支持离在线结合的方式。语音模块除了考虑使用百度公司自有的语音SDK外,后续还会考虑灵活支持第三方语音解决方案的需求。</p>
<p>DuerOS车载版与百度汽车版地图进行了深度整合,力图为车主打造出最好的语音导航交互体验。UIUE方面,DuerOS车载版尽量采人性化的诱导式交互、支持用户自定义UI、NLP各类目界面展示以及较为灵活的多分辨率适配方案等等。</p>
<p>DuerOS车载版整体方案需要实现平台化,一方面需要提供SDK、Src Code以及Demo给方案商、Tier One或者OEM进行集成开发,提供语音初始化接口、UI定制、语音唤醒以及场景命令词配置等功能。另一方面需要提供SDK给第三方服务和内容开发商集成,DuerOS车载版核心模块对用户的语音进行识别、解析以后,生成Cammand指令,发送给第三方进行处理执行,同时第三方也可以通过SDK提供的相关接口将执行结果、数据等信息回传给核心模块。DuerOS车载版核心模块集成语音服务(语音识别和语义解析),通信模块(和Custom APP之间的通信)以及和第三方服务或者内容之间的通信。整体架构如下图:
<img src="img/DuerOS%20Auto%E7%AB%AF%E5%88%B0%E7%AB%AF%E6%9E%B6%E6%9E%84%E5%9B%BE.png" alt="DuerOS车载版客户端框架图"></p>
<h1 id="toc_11">DuerOS车载版接入</h1>
<p>如果想通过SDK与DuerOS进行通信,则需先进行工程配置和初始化SDK,完成这二步操作后就能通过SDK与DuerOS互动,开发定制功能。</p>
<h2 id="toc_12">工程配置</h2>
<p>将custom-sdk.jar和gson-2.2.4.jar导入到CustomApp工程中</p>
<p><img src="img/import_sdk.png" alt="DuerOS SDK导入"></p>
<p>参考CustomAppDemo工程,在AndroidManifest.xml中加入以下代码:</p>
<div><pre><code class="language-markup"><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<service android:name="com.baidu.che.codriversdk.PlatformService">
</service>
<receiver android:name="com.baidu.che.codriversdk.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="com.baidu.che.codrivercustom.START"/>
</intent-filter>
</receiver></code></pre></div>
<h2 id="toc_13">初始化SDK</h2>
<p>在Application类onCreate()函数中进行初始化。</p>
<div><pre><code class="language-java">CdConfigManager.getInstance().initialize(getApplicationContext(), new InitListener() {
@Override
public void onConnectedToRemote() {
// 与DuerOS连接成功:可以调用定制化接口
// 这里初始化各种模块,进行功能定制
// 建议将所有的sdk配置相关的都放到这里
// 切不要重复配置,否则将可能引起一些未知的问题
}
@Override
public void onDisconnectedToRemote() {
// 与DuerOS连接断开:可以做一些清理工作
}
});</code></pre></div>
<h2 id="toc_14">休眠唤醒</h2>
<h3 id="toc_15">休眠</h3>
<p>休眠设备可调用此接口,关闭其他相关APK及功能,降低消耗。此时语音唤醒功能失效</p>
<div><pre><code class="language-java">CdConfigManager.getInstance().notifySystemSleep();</code></pre></div>
<h3 id="toc_16">唤醒</h3>
<p>唤醒设备可调用此接口,打开DuerOS唤醒及相关功能。此时语音唤醒功能生效</p>
<div><pre><code class="language-java">CdConfigManager.getInstance().notifySystemWakeUp();</code></pre></div>
<h2 id="toc_17">语音识别ASR</h2>
<p>CdAsrManager类负责管理ASR相关的功能,通过CdAsrManager.getInstance()获取单例。</p>
<h3 id="toc_18">添加/删除自定义唤醒词</h3>
<p>addWakeUpWord方法设置自定义唤醒词,实例代码如下:
<code>java
CdAsrManager.getInstance().addWakeUpWord("你好百度汽车"); //添加唤醒词
CdAsrManager.getInstance().removeWakeUpWord("你好百度汽车") //删除唤醒词
</code>
可以多次调用该接口来添加多个唤醒词,但唤醒词的个数建议不超过三个,以便取得最佳唤醒效果。
<strong>注意: 已经支持自定义唤醒词, 需要请联系百度商务(<a href="mailto:[email protected]" title="[email protected]">[email protected]</a>)</strong></p>
<h3 id="toc_19">对话流界面控制</h3>
<p>对话流的打开和关闭可以通过CdAsrManager.getInstance().openDialog()和closeDialog()实现。</p>
<div><pre><code class="language-java">CdAsrManager.getInstance().setAsrTool(new CdAsrManager.AsrTool() {
@Override
public void onVrDialogShow() {
LogUtil.d(TAG, "显示对话流界面");
}
@Override
public void onVrDialogDismiss() {
LogUtil.d(TAG, "退出对话流界面");
}
});</code></pre></div>
<h3 id="toc_20">注册非场景化命令词</h3>
<p>非场景化命令词的动态注册,用于唤醒后在语音对话流中的指令定制。</p>
<p>注册非场景化命令词的示例代码如下:</p>
<div><pre><code class="language-java">CdAsrManager.VrCommand vrCommand = new CdAsrManager. CdAsrManager.VrCommand() {
@Override
public void onCommand(String type, String cmd) {
LogUtil.e(LOG_TAG, "onCommand(): type=" + type + " cmd=" + cmd);
}
@Override
public String getId() {
return "vr_cmd_test";
}
};
vrCommand.addCommand("run", "跑步", "快跑");
vrCommand.addCommand("play", "篮球", "足球");
CdAsrManager.getInstance().registerVrCmd(vrCommand);</code></pre></div>
<p>重点说明:当自定义非场景化命令词和内置非场景化命令词冲突时,会优先走自定义逻辑。</p>
<p>反注册(即取消注册)非场景化命令词的示例如下:</p>
<div><pre><code class="language-java">CdAsrManager.getInstance().unRegisterVrCmd("vr_cmd_test");</code></pre></div>
<h3 id="toc_21">其他API说明</h3>
<table>
<thead>
<tr>
<th style="text-align: left">API</th>
<th style="text-align: left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">disableAsr</td>
<td style="text-align: left">关闭语音功能开关(关闭唤醒,会释放MIC)</td>
</tr>
<tr>
<td style="text-align: left">enableAsr</td>
<td style="text-align: left">打开语音功能开关(开启唤醒,会使用MIC)</td>
</tr>
<tr>
<td style="text-align: left">openFullBargin</td>
<td style="text-align: left">开启任意打断能力</td>
</tr>
<tr>
<td style="text-align: left">closeFullBargin</td>
<td style="text-align: left">关闭任意打断能力</td>
</tr>
<tr>
<td style="text-align: left">openSceneCmd</td>
<td style="text-align: left">开启场景化命令词能力</td>
</tr>
<tr>
<td style="text-align: left">closeSceneCmd</td>
<td style="text-align: left">关闭场景化命令词能力</td>
</tr>
<tr>
<td style="text-align: left">openOneShot</td>
<td style="text-align: left">开启oneShot能力(暂不可用)</td>
</tr>
<tr>
<td style="text-align: left">closeOneShot</td>
<td style="text-align: left">关闭oneShot能力(暂不可用)</td>
</tr>
</tbody>
</table>
<p>解释:oneshot: 用户可以把唤醒词和指令一起说完,而不用等先唤醒,再发出指令; 例如: "小度小度打开导航"</p>
<h2 id="toc_22">语音合成TTS</h2>
<p>com.baidu.che.codriversdk.manager.CdTTSPlayerManager是负责管理TTS的类对象,获取到该类的单例即可使用TTS播报,详细API说明如下所示:</p>
<table>
<thead>
<tr>
<th style="text-align: left">关键API</th>
<th style="text-align: left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">play(String text)</td>
<td style="text-align: left">播放合成语音</td>
</tr>
<tr>
<td style="text-align: left">playWithUtteranceId(String text, String utteranceId)</td>
<td style="text-align: left">播放合成语音,带有文本对应的标识ID</td>
</tr>
<tr>
<td style="text-align: left">playAndShow(String text, PlayAndShowListener listener)</td>
<td style="text-align: left">播放合成语音,且展示出来,带播放完成的回调</td>
</tr>
<tr>
<td style="text-align: left">playAndShow(String text)</td>
<td style="text-align: left">播放合成语音,且展示出来</td>
</tr>
<tr>
<td style="text-align: left">setTTSPlayerListener(TTSPlayerListener listener)</td>
<td style="text-align: left">设置所有TTS播报的listener</td>
</tr>
<tr>
<td style="text-align: left">setTTSPlayStatusListener(TTSPlayStatusListener listener)</td>
<td style="text-align: left">设置当前应用通过play或playWithUtteranceId接口播报TTS的listener</td>
</tr>
<tr>
<td style="text-align: left">stop()</td>
<td style="text-align: left">停止播放</td>
</tr>
<tr>
<td style="text-align: left">switchSpeak(SpeechType type)</td>
<td style="text-align: left">设置发音类型,具体发音类型支持见下表。</td>
</tr>
<tr>
<td style="text-align: left">setAudioStreamType(int mType)</td>
<td style="text-align: left">设置TTS的StreamType</td>
</tr>
</tbody>
</table>
<p>目前DuerOS支持的发音类型有</p>
<table>
<thead>
<tr>
<th style="text-align: left">类型</th>
<th style="text-align: left">枚举类型</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">标准男生</td>
<td style="text-align: left">NORMAL_MALE</td>
</tr>
<tr>
<td style="text-align: left">标准女生</td>
<td style="text-align: left">NORMAL_FEMALE</td>
</tr>
<tr>
<td style="text-align: left">情感男生</td>
<td style="text-align: left">EMOTION_MALE</td>
</tr>
<tr>
<td style="text-align: left">情感女生</td>
<td style="text-align: left">EMOTION_FEMALE</td>
</tr>
</tbody>
</table>
<h2 id="toc_23">导航功能</h2>
<h3 id="toc_24">根据POI点信息发起导航</h3>
<div><pre><code class="language-java">PoiModel mPoiModel = new PoiModel();
mPoiModel.latitude = 22.524674; // 必填
mPoiModel.longitude = 113.943024; // 必填
mPoiModel.poiName = "深圳百度国际大厦"; // 选填
mPoiModel.poiAddress = "深圳市南山区学府路东百度国际大厦" // 选填
boolean isSendSuccess = CdNaviManager.getInstance().sendStartNaviCommand(PoiModel mPoi);</code></pre></div>
<h3 id="toc_25">设置默认导航APP</h3>
<div><pre><code class="language-java">//目前可选的地图有:
百度地图 CdNaviManager.NaviApp.Baidu
高德地图车机版 CdNaviManager.NaviApp.Amap
高德地图后视镜版 CdNaviManager.NaviApp.Amap_Lite
CdNaviManager.getInstance().setDefaultNaviApp(CdNaviManager.NaviApp.Baidu);</code></pre></div>
<h4 id="toc_26">获取地图导航状态</h4>
<div><pre><code class="language-java">CdNaviManager.getInstance().setNaviTool(new CdNaviManager.NaviTool() {
@Override
public void isMapInUse(NaviStatus status) {
//回调地图导航状态枚举值NaviStatus:status
}
});
public enum NaviStatus implements INoProguard {
/**
* 进入导航
*/
Navi_Front,
/**
* 退出导航
*/
Navi_Background,
/**
* 进入地图
*/
Navi_App_Launcher,
/**
* 退出地图
*/
Navi_App_Exit,
/**
* 导航开始
*/
Navi_Start,
/**
* 导航结束
*/
Navi_EXIT,
/**
* 巡航开始
*/
Cruise_Start,
/**
* 巡航结束
*/
Cruise_End;
}</code></pre></div>
<h4 id="toc_27">设置地图白天、黑夜模式</h4>
<div><pre><code class="language-java">//true 白天 false 黑夜
CdNaviManager.getInstance().setDayOrNightMode(true);</code></pre></div>
<h4 id="toc_28">尝试触发设置或取消地图为黑夜模式</h4>
<p>注意: 当地图为自动模式时才生效(如果强制设置了地图为白天/黑夜模式,则下面的方法均不生效)
<code>
//true 触发设置黑夜模式 false 取消设置黑夜模式
CdNaviManager.getInstance().triggerNightMode(true);
</code></p>
<h4 id="toc_29">判断地图是否在导航中</h4>
<div><pre><code class="language-java">CdNaviManager.getInstance().isInNavi(new CdNaviManager.IsNaviCallback() {
@Override
public void isInNavi(boolean isNavi) {
ToastUtils.show(isNavi ? "正在导航" : "没有导航");
}
});</code></pre></div>
<h4 id="toc_30">设置家/公司的位置</h4>
<div><pre><code class="language-java">CdNaviManager.PoiAddress address = new CdNaviManager.PoiAddress();
address.name = "xx";
//CdNaviManager.AddressType.office.name()为公司
address.type = CdNaviManager.AddressType.home.name();
address.address = "xx";
address.longitude = xx;
address.latitude = xx;
CdNaviManager.getInstance().setAppointAddress(address);</code></pre></div>
<h4 id="toc_31">获取家/公司的位置</h4>
<div><pre><code class="language-none">//CdNaviManager.AddressType.office / home
CdNaviManager.getInstance().getAppointAddress(CdNaviManager.AddressType.home,
new CdNaviManager.AddressCallback() {
@Override
public void onResultAddress(CdNaviManager.PoiAddress address){
ToastUtils.show("家的地址 = " + address.name);
}
});</code></pre></div>
<h4 id="toc_32">导航回家/公司</h4>
<div><pre><code class="language-none">//CdNaviManager.AddressType.office / home
CdNaviManager.getInstance().sendStartNaviHomeOrAddress(CdNaviManager.AddressType.home);</code></pre></div>
<h2 id="toc_33">蓝牙电话接入</h2>
<h3 id="toc_34">设置蓝牙功能</h3>
<p>使用CdBlueToothManager.getInstance().setBlueToothTool(BlueToothTool tool)设置蓝牙工具实例,由该实例实现打开系统蓝牙页面、下载联系人等功能,示例代码如下:</p>
<div><pre><code class="language-java">/**
* 设置蓝牙工具
*/
CdBlueToothManager.getInstance().setBlueToothTool(new CdBlueToothManager.BlueToothTool() {
@Override
public void openBlueToothView() {
LogUtil.d(TAG, "打开蓝牙连接界面");
// TODO: 打开蓝牙连接界面
}
@Override
public void openContractDownloadView() {
LogUtil.d(TAG, "打开电话本下载界面");
// TODO: 打开电话本下载界面
}
});</code></pre></div>
<h3 id="toc_35">BlueToothTool API说明</h3>
<table>
<thead>
<tr>
<th style="text-align: left">API</th>
<th style="text-align: left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">openBlueToothView()</td>
<td style="text-align: left">在语音打电话给某某人,DuerOS收到状态为未连接蓝牙时调用,目的打开蓝牙页面,厂商需要在里面重写实现。</td>
</tr>
<tr>
<td style="text-align: left">openContractDownloadView()</td>
<td style="text-align: left">在语音打电话给某某人,DuerOS收到状态已连接蓝牙,但是为无联系人时调用,目的打开联系人页面,厂商需要在里面重写实现方法</td>
</tr>
</tbody>
</table>
<h3 id="toc_36">设置电话功能</h3>
<p>使用CdPhoneManager.getInstance().setPhoneTool(PhoneTool tool)一个新的PhoneTool实例,由该实例来实现拨打电话功能,即可在声控拨打电话时调用到此处。示例代码如下:</p>
<div><pre><code class="language-java">CdPhoneManager.getInstance().setPhoneTool(new CdPhoneManager.PhoneTool() {
@Override
public void dialNum(String number) {
LogUtil.d(TAG, "拨打电话:" + number);
// TODO: 拨打电话
}
});</code></pre></div>
<h3 id="toc_37">蓝牙电话状态同步</h3>
<p>由于不同厂商的车机系统,获取蓝牙状态的接口各不相同,执行示例代码,可以通知蓝牙连接状态到DuerOS语音模
<code>java
//示例代码:
CdBlueToothManager.getInstance().onNotifyBTStatus(BtStatus status)</code>
CdBlueToothManager.BtStatus中定义如下几种蓝牙状态:</p>
<table>
<thead>
<tr>
<th style="text-align: left">宏</th>
<th style="text-align: center">参数值(status)</th>
<th style="text-align: left">备注</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">BT_DISCONNECTED</td>
<td style="text-align: center">0</td>
<td style="text-align: left">断开连接</td>
</tr>
<tr>
<td style="text-align: left">BT_CONNECTING</td>
<td style="text-align: center">1</td>
<td style="text-align: left">正在连接</td>
</tr>
<tr>
<td style="text-align: left">BT_CONNECTED</td>
<td style="text-align: center">2</td>
<td style="text-align: left">连接成功</td>
</tr>
<tr>
<td style="text-align: left">BT_DISCONNECTING</td>
<td style="text-align: center">3</td>
<td style="text-align: left">正在断开连接</td>
</tr>
<tr>
<td style="text-align: left">BT_CANCELLING</td>
<td style="text-align: center">4</td>
<td style="text-align: left">正在取消</td>
</tr>
<tr>
<td style="text-align: left">BT_CANCELLED</td>
<td style="text-align: center">5</td>
<td style="text-align: left">已经取消</td>
</tr>
<tr>
<td style="text-align: left">BT_PAIRED</td>
<td style="text-align: center">6</td>
<td style="text-align: left">已经配对</td>
</tr>
<tr>
<td style="text-align: left">BT_NOPAIR</td>
<td style="text-align: center">7</td>
<td style="text-align: left">未配对</td>
</tr>
</tbody>
</table>
<h3 id="toc_38">通知电话本授权状态</h3>
<div><pre><code class="language-none">//示例代码:
CdBlueToothManager.getInstance().onNotifyBTPhoneStatus(BTPhoneStatus status)
</code></pre></div>
<p>执行示例代码,可以通知电话本授权情况到DuerOS语音模块,CdBlueToothManager.BTPhoneStatus中定义如下目几种电话本授权状态:</p>
<table>
<thead>
<tr>
<th style="text-align: left">宏</th>
<th style="text-align: center">参数值(status)</th>
<th style="text-align: left">备注</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">BT_PHONE_NO_AUTHORIZED</td>
<td style="text-align: center">0</td>
<td style="text-align: left">无授权</td>
</tr>
<tr>
<td style="text-align: left">BT_PHONE_AUTHORIZING</td>
<td style="text-align: center">1</td>
<td style="text-align: left">正在授权</td>
</tr>
<tr>
<td style="text-align: left">BT_PHONE_AUTHORIZED</td>
<td style="text-align: center">2</td>
<td style="text-align: left">已授权</td>
</tr>
<tr>
<td style="text-align: left">BT_PHONE_REQUESTING</td>
<td style="text-align: center">3</td>
<td style="text-align: left">请求授权中</td>
</tr>
<tr>
<td style="text-align: left">BT_PHONE_RESERVED_1</td>
<td style="text-align: center">4</td>
<td style="text-align: left">保留字段</td>
</tr>
<tr>
<td style="text-align: left">BT_PHONE_RESERVED_2</td>
<td style="text-align: center">5</td>
<td style="text-align: left">保留字段</td>
</tr>
<tr>
<td style="text-align: left">BT_PHONE_CANNOT_AUTHORIZED</td>
<td style="text-align: center">6</td>
<td style="text-align: left">无法获取授权</td>
</tr>
</tbody>
</table>
<h3 id="toc_39">通知电话本下载情况</h3>
<div><pre><code class="language-none">//示例代码:
CdPhoneManager.getInstance().onNotifyPhoneStatus(PhoneDownload Status status)```
CdPhoneManager.PhoneDownloadStatus中定义如下几种电话本下载状态:
| 宏 | 参数值(status) | 备注 |
| :-- | :-------------: | :--- |
| CONTACTS\_NO_DOWNLOADED | 0 | 默认状态 |
| ACTION\_PBAP\_DOWNLOAD_SUPPORT | 1 | 访问配置文件成功 |
| CONTACTS\_DOWNLOAD_REQUEST | 2 | 电话本下载请求 |
| CONTACTS\_DOWNLOAD_STARTED | 3 | 电话本下载开始 |
| CONTACTS\_DOWNLOAD_PROGRESS | 4 | 电话本下载中 |
| CONTACTS\_DOWNLOAD_COMPLETE | 5 | 通讯电话本下载完成 |
| CONTACTS\_UPDATE_READY | 6 | 联系人准备更新 |
| CONTACTS\_UPDATE_COMPLETE | 7| 联系人更新完毕 |
| CALLLOGS\_DOWNLOAD_STARTED | 8 | 通讯记录下载开始 |
| CALLLOGS\_DOWNLOAD_PROGRESS | 9 | 通讯记录下载中 |
| CALLLOGS\_DOWNLOAD_COMPLETE | 10 | 通讯记录下载完成 |
| OTHER | 11 | 其他 |
### 同步联系人通讯录数据
```java
//初始化Model
CdPhoneManager.PhoneContactList mPhoneModel = new CdPhoneManager.PhoneContactList();
//增加每个联系人名称以及电话
//@note 同一联系人有多个号码当成不同的联系人处理
mPhoneModel.addContact("张三", "13888888888");
mPhoneModel.addContact("张三", "13899999999");
mPhoneModel.addContact("李四", "13800000000");
//设置完毕传递数据并通知:
CdPhoneManager.getInstance().sendPhoneBookData(mPhoneModel);</code></pre></div>
<h2 id="toc_40">多媒体功能接入</h2>
<p>为了实现“打开无线电、打开FM、打开AM、打开USB音乐、打开CD音乐、打开AUX音乐、打开Ipod音乐、打开蓝牙音乐”等指令,DuerOS提供了统一的接口<code>setMediaTool</code>供SDK开发厂商进行使用,适配各车机系统提供多媒体接口。</p>
<p>可通过CdMediaManager.getInstance().setMediaTool(MediaTool tool)设置多媒体工具实例,通过实现该实例中的各个接口,可以实现“打开无线电、打开FM、打开AM、打开USB音乐、打开CD音乐、打开AUX音乐、打开Ipod音乐、打开蓝牙音乐”等功能。</p>
<div><pre><code class="language-java">//示例代码:
CdMediaManager.getInstance().setMediaTool(new MediaTool() {
@Override
public void openRadio() {
// TODO Auto-generated method stub
}
@Override
public void closeRadio() {
// TODO Auto-generated method stub
}
@Override
public void openMyMusic() {
// TODO Auto-generated method stub
}
@Override
public void openMusicUsb() {
// TODO Auto-generated method stub
}
@Override
public void openMusicIpod() {
// TODO Auto-generated method stub
}
@Override
public void openMusicCd() {
// TODO Auto-generated method stub
}
@Override
public void openMusicBt() {
// TODO Auto-generated method stub
}
@Override
public void openMusicAux() {
// TODO Auto-generated method stub
}
@Override
public void openFMChannel(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void openFM() {
// TODO Auto-generated method stub
}
@Override
public void openAMChannel(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void openAM() {
// TODO Auto-generated method stub
}
@Override
public void playCollectionFM() {
// TODO Auto-generated method stub
}
@Override
public void collectFMChannel() {
// TODO Auto-generated method stub
}
@Override
public void cancelFMChannel() {
// TODO Auto-generated method stub
}
@Override
public void searchAndRefreshFMChannel() {
// TODO Auto-generated method stub
}
});</code></pre></div>
<h2 id="toc_41">音乐功能接入</h2>
<p>针对音乐的诉求,DuerOS适配了三个音乐播放器:</p>
<p>1.百度随心听。由百度提供,包含海量的正版声音类资源。</p>
<p>2.酷我音乐播放器。百度与酷我音乐合作,包含大量酷我音乐资源。</p>
<p>3.厂商自有播放器。厂商如果本身具有音乐资源,可以通过DuerOS直接进行适配,达到声控播放器的效果。</p>
<blockquote>
<p>由于数字版权问题,音乐资源的正式量产使用请咨询百度车联网商务[email protected]。</p>
</blockquote>
<h3 id="toc_42">默认音乐播放器设置</h3>
<p>厂商可以通过下面接口选择默认的播放器接口</p>
<div><pre><code class="language-java">CdConfigManager.getInstance().setMusicType(MusicType musicType);</code></pre></div>
<p>MusicType:</p>
<table>
<thead>
<tr>
<th style="text-align: left">类型</th>
<th style="text-align: left">枚举类型</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">自定义播放器</td>
<td style="text-align: left">CUSTOM_MUSIC</td>
</tr>
<tr>
<td style="text-align: left">百度随心听</td>
<td style="text-align: left">BAIDU_RADIO</td>
</tr>
<tr>
<td style="text-align: left">QQ音乐</td>
<td style="text-align: left">QQ_MUSIC</td>
</tr>
<tr>
<td style="text-align: left">酷我音乐</td>
<td style="text-align: left">KUWO_MUSIC</td>
</tr>
</tbody>
</table>
<p>对于自厂商自有播放器,需通过CdMusicManager.getInstance().setMusicTool(MusicTool tool)进行音乐工具实例设置,从而控制自己的音乐播放器,示例代码如下:</p>
<div><pre><code class="language-java">CdMusicManager.getInstance().setMusicTool(new MusicTool() {
@Override
public void searchMusic(String arg0, String arg1,
OnSearchResultListener arg2) {
//如果不回调OnSearchResultListener的方法仍会调用随心听来处理该搜索结果
// TODO Auto-generated method stub
}
@Override
public void playMusic(MusicModel arg0) {
// TODO Auto-generated method stub
}
@Override
public void playList(List<MusicModel> arg0, int arg1) {
// TODO Auto-generated method stub
}
});</code></pre></div>
<h3 id="toc_43">默认音乐播放器启动设置</h3>
<p>通知DuerOS在下次控制音乐(切歌、上一曲、下一曲...)时,是否拉起正在播放的音乐播放器到前台(默认不拉起音乐播放器)</p>
<div><pre><code class="language-java">// true 拉起 false 不拉起
// 注意: 该接口调用一次即可生效, 不需要重复调用
CdPlayerManager.getInstance().notifyNeedLaunchApp(boolean needLaunch)</code></pre></div>
<h2 id="toc_44">播放器功能接入</h2>
<p>厂商可以通过CdPlayerManager.getInstance().setPlayerTool(PlayerTool tool)设置播放器工具,通过实现该实例的各个接口可以实现切换播放模式、切换上一首、切换下一首、播放、暂停、退出等功能。这几个功能是<strong>公共行为</strong>,以暂停为例,可能是暂停播放音乐,也可能是暂停FM、AM等。示例代码如下:</p>
<div><pre><code class="language-java">CdPlayerManager.getInstance().setPlayerTool(new PlayerTool() {
@Override
public void switchMode(int mode) {
// TODO Auto-generated method stub
}
@Override
public void prev() {
// TODO Auto-generated method stub
}
@Override
public void play() {
// TODO Auto-generated method stub
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void next() {
// TODO Auto-generated method stub
}
@Override
public void exit() {
// TODO Auto-generated method stub
}
});</code></pre></div>
<p>其中swithMode(int mode)支持三种模式,在PlayerTool:</p>
<table>
<thead>
<tr>
<th style="text-align: left">宏</th>
<th style="text-align: left">参数值</th>
<th style="text-align: left">备注</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">PlayerTool.MODE_SINGLE_LOOP</td>
<td style="text-align: left">0</td>
<td style="text-align: left">单曲循环</td>
</tr>
<tr>
<td style="text-align: left">PlayerTool.MODE_RANDOM</td>
<td style="text-align: left">1</td>
<td style="text-align: left">随机播放</td>
</tr>
<tr>
<td style="text-align: left">PlayerTool.MODE_FULL_LOOP</td>
<td style="text-align: left">2</td>
<td style="text-align: left">循环播放</td>
</tr>
</tbody>
</table>
<p>说明:音乐搜索(比如唤醒小度,我想听刘德华的冰雨),结果会由默认播放器去播放(调用setMusictype())。但是控制指令(比如下一首,上一首暂停播放等等..),会拉起最近使用的播放器去执行指令。</p>
<h2 id="toc_45">手动控制播放器</h2>
<p>厂商除了通过实现PlayTools借口来语音控制音乐播放外,还可以手动调用方法来控制接入了sdk的音乐播放器的上一首,下一首,暂停,播放,退出,循环模式,换歌等功能.
```java
CdPlayerManager.getInstance().play();// 播放
CdPlayerManager.getInstance().pause();// 播放
CdPlayerManager.getInstance().stop();// 播放
CdPlayerManager.getInstance().next();// 播放
CdPlayerManager.getInstance().prev();// 播放
CdPlayerManager.getInstance().change();// 播放
CdPlayerManager.getInstance().switchMode(int mode);// 播放</p>
<div><pre><code class="language-none">
###通知DuerOS当前正在播放的播放器类型
```java
public void notifyInUse(CdConfigManager.MusicType musicType)</code></pre></div>
<p>说明:
本地播放器可通过调用此接口,并设置musicType值为MusicType.CUSTOM_MUSIC,通知duerOS将播放器控制指令发送到本地播放器。</p>
<h2 id="toc_46">系统控制功能接入</h2>
<h3 id="toc_47">车辆控制功能接入</h3>
<p>厂商可以通过CdSystemManager.getInstance().setSystemTool(SystemTool tool)设置系统工具,通过该工具厂商可以实现开关空调、调节温度、开关车窗、调节系统音量等功能。示例代码如下:</p>
<div><pre><code class="language-java">CdSystemManager.getInstance().setSystemTool(new SystemTool() {
@Override
public boolean reduceFeature(String feature, String value) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean operateFeature(String feature, String value) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean openFeature(String feature, String value) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean minFeature(String feature, String value) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean maxFeature(String feature, String value) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean increaseFeature(String feature, String value) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean closeFeature(String feature, String value) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean searchFeature(String feature, String value) {
// TODO Auto-generated method stub
return false;
}
});</code></pre></div>
<p>说明:</p>
<ul>
<li>返回值:true表示成功执行指令,DuerOS对话流会自动关闭;false表示指令未处理</li>
<li>如果不做任何处理,超时3s后,DuerOS会提示“执行指令超时”并退出语音对话流</li>
</ul>
<p>Feature常量定义如下:</p>
<table>
<thead>
<tr>
<th style="text-align: left">常量名</th>
<th style="text-align: left">常量值</th>
<th style="text-align: left">支持的方法</th>
<th style="text-align: left">备注</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">FEATURE_VOLUME</td>
<td style="text-align: left">volume</td>
<td style="text-align: left">increase/reduce</td>
<td style="text-align: left">增大/减小音量</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_BLUETOOTH</td>
<td style="text-align: left">bluetooth</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">打开/关闭蓝牙</td>
</tr>
<tr>
<td style="text-align: left">FEATURE<em>VEHICLE</em>LIGHT</td>
<td style="text-align: left">vehicle_light</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">打开/关闭车灯</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_LIGHT</td>
<td style="text-align: left">light</td>
<td style="text-align: left">oprate(up/down/max/min)</td>
<td style="text-align: left">调节屏幕亮度</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_WIFI</td>
<td style="text-align: left">wifi</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">打开/关闭WIFI</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_NETWORK</td>
<td style="text-align: left">network</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">打开/关闭网络</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_SETTING</td>
<td style="text-align: left">system_setting</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">打开/关闭设置</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_PICTURE</td>
<td style="text-align: left">picture</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">打开/关闭相册</td>
</tr>
<tr>
<td style="text-align: left">FEATURE<em>NETWORK</em>SHARING</td>
<td style="text-align: left">network_sharing</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">wifi热点分享</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_WIND_FLOW</td>
<td style="text-align: left">wind_flow</td>
<td style="text-align: left">operate(up/down/high/low/normal)</td>
<td style="text-align: left">调节风量大小</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_WIND_DIRECTION</td>
<td style="text-align: left">wind_direction</td>
<td style="text-align: left">operate(next)</td>
<td style="text-align: left">下一个出风方向</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_TEMP</td>
<td style="text-align: left">temp</td>
<td style="text-align: left">operate(max/min/up/down/cold/hot)</td>
<td style="text-align: left">调节空调温度</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_CLIMATE</td>
<td style="text-align: left">climate</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">气温系统</td>
</tr>
<tr>
<td style="text-align: left">FEATURE<em>AIR</em>SYNC</td>
<td style="text-align: left">air_sync</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">同步模式</td>
</tr>
<tr>
<td style="text-align: left">FEATURE<em>VEHICLE</em>DOOR</td>
<td style="text-align: left">vehicle_door</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">车门</td>
</tr>
<tr>
<td style="text-align: left">FEATURE<em>VEHICLE</em>BOX</td>
<td style="text-align: left">veicle_box</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">车尾箱</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_AIR_CONDITIONER</td>
<td style="text-align: left">air_conditioner</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">空调</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_INTERNAL_RECYCLE</td>
<td style="text-align: left">internal_recycle</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">内循环</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_AIR_CLEAN</td>
<td style="text-align: left">air_clean</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">空气清新系统</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_DEFROST</td>
<td style="text-align: left">defrost</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">挡风除霜</td>
</tr>
<tr>
<td style="text-align: left">FEATURE<em>AUTO</em>DEFROST</td>
<td style="text-align: left">auto_defrost</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">自动挡风除霜</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_MUTE</td>
<td style="text-align: left">mute</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">打开/关闭静音</td>
</tr>
<tr>
<td style="text-align: left">FEATURE<em>SET</em>HEAT</td>
<td style="text-align: left">heat</td>
<td style="text-align: left">open/close</td>
<td style="text-align: left">座位加热</td>
</tr>
<tr>
<td style="text-align: left">FEATURE_HELP</td>
<td style="text-align: left">help</td>
<td style="text-align: left">-</td>
<td style="text-align: left">帮助</td>
</tr>
</tbody>
</table>
<h3 id="toc_48">行车记录仪控制功能接入</h3>
<p>厂商可以通过以下示例代码来实现相应的功能</p>
<div><pre><code class="language-none">CdCameraManager.getInstance().setCameraTool(new CdCameraManager.DrivingRecorderTool() {
@Override
public void drivingRecorder(DrivingRecorderState drivingRecorderState) {
//drivingRecorderState == DrivingRecorderState.WATCH 查看录像
//DrivingRecorderState.START 开始录像
//DrivingRecorderState.STOP 停止录像
}
@Override
public void openCamera(CameraType cameraType) {
//打开摄像头
//cameraType == CameraType.FRONT_CAMERA 前置摄像头
//CameraType.INNER_CAMERA 内置摄像头
//CameraType.BACK_CAMERA 后置摄像头
}
@Override
public void takePicture() {
//拍照
}
});
</code></pre></div>
<p>1) sdk把车辆相关信息传给DuerOS, 示例代码如下:
<code>
CdSystemManager.getInstance().setCarStateListener
(new CdSystemManager.CarStateListener() {
@Override
public void carStateCmd(String feature, String extra) {
//厂商根据feature,返回相应的值
// data 格式如下:
{ code: AIR_TEMPERATURE,
ext: {
ext1: value1
ext2: value2
}
}
CdSystemManager.getInstance().sendCarInfo(data);
}
});
</code>
Feature常量定义如下:
CarState.AIR<em>TEMPERATURE 空调温度
CarState.FUEL</em>OIL 燃油量</p>
<p>2) sdk发送车辆具体型号给DuerOS, 示例代码如下:
<code>
CdSystemManager.getInstance().sendCarModel("保时捷911");
</code></p>
<h3 id="toc_49">电子手册功能接入(注:目前仅一汽渠道可用)</h3>
<p>1) 设置电子手册监听即可, 代码如下:
<code>
CdCarInfoQueryManager.getInstance().setQueryCarInfoTool(new CdCarInfoQueryManager.QueryCarInfoTool() {
@Override
public boolean answerContent(String feature, String extra) {
// 返回的内容就是feature, extra字段暂不生效
return true;
}
});
</code></p>
<h3 id="toc_50">界面跳转</h3>
<p>跳转到语音设置界面</p>
<div><pre><code class="language-java">CdSystemManager.getInstance().jumpToAsrSetting();</code></pre></div>
<p>跳转到帮助界面</p>
<div><pre><code class="language-java">CdSystemManager.getInstance().jumpToHelpSetting();</code></pre></div>
<h2 id="toc_51">在线更新功能接入</h2>
<h3 id="toc_52">在线更新功能简介</h3>
<p>在线更新模块通过单次下载和静默安装,实现DuerOS生态内所有App的整体升级。主要流程如下:</p>
<p>1) 检测升级配置:分为用户手动检测和系统自动检测两种方式,自动检测在DuerOS启动30秒后进行;</p>
<p>2) 下载升级包:以zip压缩包的形式下载DuerOS生态内所有需要升级的App;</p>
<p>3) 静默安装:升级包下载完成后,DuerOS发出广播,由车机系统接收广播并完成指定目录下apk文件的批量静默安装</p>
<h3 id="toc_53">需要车机系统开发的功能</h3>
<p>1)接收DuerOS发送的在线更新升级广播,广播Intent如下:</p>
<div><pre><code class="language-java">Intent intent = new Intent();
intent.setAction("codriver.intent.action.SYSTEM_RESTART");
intent.putExtra("dueros_ota_dir", otaCacheDir);</code></pre></div>
<p>2)通过在线更新升级广播intent的dueros<em>ota</em>dir参数获取在线更新安装包的存储目录,静默安装该目录下全部apk文件;</p>
<p>3)安装成功后,删除在线更新安装包存储目录下的全部apk文件,并重启车机。</p>
<h2 id="toc_54">天气获取</h2>
<p>可以发送广播主动获取天气信息
<code>java
context.sendBroadcast(new Intent("com.hkmc.intent.action.request_weather_update"));
</code>
Dueros在接收到广播后会发送包含天气信息的广播,注册如下广播接受者
<code>java
IntentFilter intentFilter =
new IntentFilter("com.hkmc.intent.action.weather_update");
context.registerReceiver(mReceiver, intentFilter);
</code>
在广播接受者onReceive的Intent中通过"com.hkmc.extras.weather.weather<em>condition"和
"com.hkmc.extras.weather.weather</em>name"可以分别获取天气类型和天气名字。</p>
<p>除此之外Dueros每隔一段时间会通过此广播接受者更新天气。</p>
<h1 id="toc_55">DuerOS常见问题</h1>
<h2 id="toc_56">音乐播放操作逻辑问题</h2>
<h3 id="toc_57">控制指令执行逻辑(打开音乐、上一首、下一首...)</h3>
<h4 id="toc_58">复现步骤:</h4>
<p>1.设置百度随心听为默认播放器,打开随心听和酷我,同时暂停挂在后台(随心听先暂停,酷我后暂停)。
2.说"下一首,上一首"等控制指令,打开了酷我播放下一首歌曲,而不是默认播放播放器。</p>
<h4 id="toc_59">逻辑描述:</h4>
<p>为了保持用户在音乐体验上的一致性和流畅性,类似上一首,下一首,暂停这种控制命令词,会派发给最近打开的播放器去执行,上述描述问题中后暂停的为酷我,即为最近使用播放器,所以酷我会去执行命令。</p>
<h3 id="toc_60">搜索音乐执行逻辑(我要听XXX的XXX)</h3>
<h4 id="toc_61">复现步骤:</h4>
<p>1.设置百度随心听为默认播放器,打开使用酷我播放器
2.发出指令"我想听刘德华的冰雨"
3.随心听打开,播放刘德华的冰雨,酷我暂停,而不是酷我播放</p>
<h4 id="toc_62">逻辑描述:</h4>
<p>"我想听XXX的XXX"这种搜索指令会派发给默认播放器去执行,上述问题中,如果想制定酷我去播放,可以使用
<code>java
CdConfigManager.getInstance().setMusicType(MusicType.KUWO_MUSIC)
</code>
来设置酷我为默认播放器。可设置的音乐类型有以下四种枚举:MusicType.CUSTOM<em>MUSIC、MusicType.KUWO</em>MUSIC、MusicType.BAIDU<em>RADIO、MusicType.QQ</em>MUSIC。</p>
<h1 id="toc_63">核心功能指令</h1>
<p>具体请参见<a href="#DuerOS%E5%8F%91%E5%B8%83%E5%8C%85%E5%8C%85%E5%90%AB%E4%BB%80%E4%B9%88%E5%86%85%E5%AE%B9">百度DuerOS车载版语音指令集.xlsx</a></p>
<h1 id="toc_64">Launcher开源项目简介</h1>
<h2 id="toc_65">源代码github地址</h2>
<p>具体请参见<a href="http://github.com/ApolloAuto/apollo-DuerOS/tree/master/DuerOS-Launcher">Launcher源码</a></p>
<h2 id="toc_66">Launcher工程目录结构说明</h2>
<ul>
<li>app-headunit-open:launcher车机版主module</li>
<li>app-mirror-open:launcher车镜版主module</li>
<li>core:launcher公共库</li>
<li>map-sdk:用于封装定位 sdk </li>
<li>build-app-headunit-open.sh:车机版 launcher 的构建脚本</li>
<li>build-app-mirror-open.sh:车镜版 launcher 的构建脚本</li>
<li>output:用于存放上述构建脚本生产的 apk 文件 </li>
</ul>
<h2 id="toc_67">Launcher项目架构</h2>
<p>DuerOS Launcher开源项目基于Android Studio研发,使用gradle作为自动化构建工具。包括4个module,其中core,map-sdk为 library 类型,app-mirror-open,app-headunit-open为application类型。各module的依赖关系如下图。</p>
<p><img src="img/launcher_arch.png" alt="Launcher架构"></p>
<p>具体介绍如下: </p>
<ol>
<li>core:是launcher的核心库,主要作用是集成DuerOS SDK, 封装launcher需要的基础类库,包括屏幕适配,网络库(基于OKHttp3),图片库(Fresco),Log工具类等能力。</li>
<li>map-sdk: 主要作用是独立封装了定位sdk,供车机版launcher使用。</li>
<li>app-headunit-open: 是车机版launcher的主module,用于车机版launcher UI交互的实现。 </li>
<li>app-mirror-open: 是车镜版launcher的主module。用于车镜版launcher UI交互的实现。 </li>
</ol>
<p>安装说明:
1. 以push进/system/app覆盖系统Launcher方式安装时,需要将对应.so文件同时push进/system/lib。对应so文件可以将apk文件解压,复制lib下所有so文件获取。
2. 以adb install方式安装(普通安装),无需做特殊处理。</p>
<p>说明:电话,收音机等功能需自行接入。</p>
<h1 id="toc_68">回音去除和降噪(ECNS)</h1>
<p>大部分语音应用都有个无法回避的痛点,就是MIC不得不将设备本身喇叭发出来的声音(简称Speaker信号,比如音乐、TTS等音源)录进来,作为录音识别的语料与人声一同送往语音引擎而造成识别率下降。目前主流语音技术仍然无法从混杂声音信号中自动分辨人声,在这种情况下,语音引擎一直接收混杂着设备喇叭与人声的信号,与单纯人声输入相比,效果相差很大。</p>
<p>车载语音又远比手机语音环境复杂很多,比如在手机场景中,用户可以用MIC贴近嘴进行录音可以有效避免其他干扰,或者手动关闭声音也很方便。然而,在车载场景中,MIC离用户至少有一臂的距离,为保证用户的驾车安全,更不能要求用户降低喇叭音量才来使用语音。</p>
<p>针对不同合作方的需求,DuerOS开发了软件消噪和硬件消噪两套算法,满足不同定位产品的需求。根据目前的评测硬件降噪方案效果优于软件降噪方案。</p>
<h2 id="toc_69">硬件消噪方案</h2>
<p>详情请参考
<a href="https://github.com/ApolloAuto/apollo-DuerOS/tree/master/DSP-Solution-For-DuerOS">硬件消噪方案</a></p>
<h2 id="toc_70">软件消噪方案</h2>
<p>百度软件消噪方案采用了AEC(Acoustic Echo Canceling)声学回声消除技术。这项技术起源于电话通信和VOIP的发展,下图展示了一个应用AEC算法的通信系统。在此例中,通信链路近端的扬声器和话筒之间的声学耦合会产生回声,这导致在远端产生明显的干扰回声。在这种情况下,近端运行的AEC算法将抑制回声并提高系统的性能。
<img src="img/aec.png" alt="回声消噪">
其基本原理和步骤如下:</p>
<ul>
<li>输送给近端喇叭的语音信号被采样,作为回声消除参考信号Speaker信号</li>
<li>近端MIC拾取语音输入,作为MIC信号</li>
<li>针对MIC信号和Speaker信号进行相关性分析(起始的时延和比对窗口)</li>
<li>自适应滤波器降噪处理</li>
</ul>
<p>百度DuerOS车载版使用的AEC算法是由百度语音技术部提供的,该算法已经在多款车载设备上得到应用,是一套鲁棒性很高的算法。</p>
<h3 id="toc_71">关键依赖项</h3>
<p>百度既已实现回声消除算法,进入工程阶段的关键依赖项就变成如何能获得Speaker信号了,对于该路信号我们有两点要求:</p>
<ul>
<li>客户端在接收MIC信号同时,也能连续不断地获取到Speaker信号</li>
<li>MIC信号和从底层获取的Speaker信号要保证同步,两者的时延必须严格控制在400ms以内。</li>
</ul>
<p>要获取到高质量的Speaker信号,推荐采用修改Linux 驱动层或者通过修改IIS总线(Inter-IC Sound,集成电路内置音频总线)去获取Speaker信号。因为只有在Linux驱动层或者IIS最接近Codec硬件,而且通常情况下,录音和播放是同样的Codec芯片,所以会采用相同的采样率,所以,如果能在同一个采样周期里,获取到的Speaker信号和MIC信号应该是对齐的,严格来说,不会有时差,这是取得良好性能的关键。如果时延不能保证,依靠纯软件算法去动态对齐,是非常消耗CPU运算的,效果也得不到保障。整个技术流程如下:</p>
<ul>
<li>客户端打开录音设备,要求系统进行双声道立体声录音,以android系统为例</li>
</ul>
<div><pre><code class="language-java">AudioRecord recordInstance = new AudioRecord(audioSource,
RECORD_SAMPLE_RATE_16K,
AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT,
DEFAULT_BUFFER_SIZE);</code></pre></div>
<ul>
<li>Linux驱动层或者IIS总线层在接收到客户端调用后进行录音,收到的MIC信号放入左声道</li>
<li>同时,Linux驱动层或者IIS总线层要把送给喇叭的Speaker信号填入右声道</li>
<li>客户端要将收到的立体声数据分离,分离成两路信号</li>
<li>客户端继而要将这两路信号进行AEC模块处理</li>
<li>客户端再将经过AEC处理后的音频流送入百度语音引擎进行识别</li>
</ul>
<h3 id="toc_72">接入流程</h3>
<p>合作厂商先内部评估下能否从Linux驱动层或者IIS总线层去获取到Speaker信号。
确定可行后,可以开发一个demo出来,将MIC信号和Speaker信号分别以PCM流形式保存在本地,送给百度侧评估。
百度会验证这两个文件是否符合算法要求,并会交给AEC模块处理,得到一路信号保存下来分析。
百度确认可行之后,合作厂商可以实施Linux驱动层或者IIS总线层的修改工作。
实施过程中,要保证MIC信号塞入左声道,Speaker信号塞入右声道;且没有音乐或者TTS播放时,也需要往右声道塞入空数据。
实施完成后,双方进行联调测试,优化Barge-In效果。</p>
<h3 id="toc_73">SDK相关API</h3>
<p>如果厂商的设备已经满足上述要求,可以通过通过CdRecordManager类的相关接口来设置AEC和录音相关的特性,详见下面的接口说明。</p>
<h4 id="toc_74">setRecordType(RecordType type)</h4>
<p>设置AEC和录音相关特性,示例代码如下:
<code>
//注意: 该方法仅第一次调用时生效, 多次调用无效
CdRecordManager.getInstance().setRecordType(RecordType type)
</code></p>
<p>参数类型为RecordType枚举,可设置的类型如下:</p>
<table>
<thead>
<tr>
<th style="text-align: left">宏</th>
<th style="text-align: left">录音类型</th>
<th style="text-align: left">备注</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left"><code>INSIDE_RAW</code></td>
<td style="text-align: left">内部录音</td>
<td style="text-align: left">无AEC,单声道,只有Mic信号</td>
</tr>
<tr>
<td style="text-align: left"><code>INSIDE_AEC_MIC_LEFT</code></td>
<td style="text-align: left">内部录音</td>
<td style="text-align: left">有AEC,左声道是Mic,右声道是Speaker</td>
</tr>
<tr>
<td style="text-align: left"><code>INSIDE_AEC_MIC_RIGHT</code></td>
<td style="text-align: left">内部录音</td>
<td style="text-align: left">有AEC,右声道是Mic,左声道是Speaker</td>
</tr>
<tr>
<td style="text-align: left"><code>OUTSIDE_RAW</code></td>
<td style="text-align: left">外部录音</td>
<td style="text-align: left">无AEC,单声道,只有Mic信号</td>
</tr>
<tr>
<td style="text-align: left"><code>OUTSIDE_AEC_MIC_LEFT</code></td>
<td style="text-align: left">外部录音</td>
<td style="text-align: left">有AEC,左声道是Mic,右声道是Speaker</td>
</tr>
<tr>
<td style="text-align: left"><code>OUTSIDE_AEC_MIC_RIGHT</code></td>
<td style="text-align: left">外部录音</td>
<td style="text-align: left">有AEC,右声道是Mic,左声道是Speaker</td>
</tr>
<tr>
<td style="text-align: left"><code>OUTSIDE_AEC_DUAL_CHANNEL</code></td>
<td style="text-align: left">外部录音</td>
<td style="text-align: left">有AEC,厂商自己分离Mic和Speaker信号</td>
</tr>
</tbody>
</table>
<p>说明:</p>
<ul>
<li>如果设置的RecordType属于外部录音(<code>OUTSIDE_***</code>),需要厂商自行实现录音逻辑,并把录音数据通过接口传到DuerOS</li>
<li>通过setRecordTool()接口来设置录音开始和结束的状态回调</li>
<li>通过feedAudioBuffer()接口来给DuerOS传输录音信号</li>
</ul>
<h4 id="toc_75">setRecordTool(RecordTool tool)</h4>
<p>设置录音状态回调,示例代码如下:</p>
<div><pre><code class="language-java">CdRecordManager.getInstance().setRecordTool(new CdRecordManager.RecordTool() {
@Override
public void startRecord() {
LogUtil.d(TAG, "-----startRecord------");
startRecord();
}
@Override
public void endRecord() {
LogUtil.d(TAG, "-----endRecord------");
endRecord();
}
@Override
public void initRecorder() {
LogUtil.d(TAG, "-----initRecorder------");
initRecorder();
}
});</code></pre></div>
<h4 id="toc_76">feedAudioBuffer(byte[] rawData)</h4>
<p>此接口用于传输录音数据到DuerOS。</p>
<ul>
<li>RecordType为<code>OUTSIDE_RAW</code>、<code>OUTSIDE_AEC_MIC_LEFT</code>或<code>OUTSIDE_AEC_MIC_RIGHT</code>类型时使用</li>
<li>参数rawData为外部录音PCM数据的字节数组</li>
<li>RecordType为<code>OUTSIDE_RAW</code>时,rawData的长度必须为2560</li>
<li>RecordType为<code>OUTSIDE_AEC_MIC_LEFT</code>或<code>OUTSIDE_AEC_MIC_RIGHT</code>时,参数rawData的长度必须为2560*2,同时包括Mic信号和Speaker参考信号,二者以两个字节为单位交错分布</li>
</ul>
<h4 id="toc_77">feedAudioBuffer(byte[] micData, byte[] spkData)</h4>
<p>此接口用于传输录音数据到DuerOS。</p>
<ul>
<li>RecordType为<code>OUTSIDE_AEC_DUAL_CHANNEL</code>类型时使用</li>
<li>参数micData为Mic录音PCM的字节数组,长度必须为2560</li>
<li>参数spkData为Speaker参考信号的字节数组,长度必须为2560</li>
</ul>
<h2 id="toc_78">MIC设计建议</h2>
<p><a name="MIC设计建议" ></a>
该章节参考《Automotive Microphone Hardware_acoustics design guidelines - Baidu Speech V0.1》。</p>
<h3 id="toc_79">麦克风选型参考</h3>
<p>百度的MIC参考方案与市场主流的麦克风都是匹配的,以下两个类型的麦克风在市场上都很常见:</p>
<p>驻极体电容式麦克风(ECM):直径在4mm-6mm之间,高度在2mm-3mm(算上密封垫片或者防护罩,每项指标可能要增加1mm-2mm)</p>
<p>微型机电式传感器(MEMS):体型更小,广泛用于更薄的产品中,比如手机,平板电脑以及智能电视的语音遥控器等等。</p>
<p>总体上来说,前置的全向麦克风性能最为优越,其次是两极和单极麦克风。详细的指标如下:</p>
<p>性噪比:SNR>=60dB</p>
<p>频响范围:-4dB/+8dB(300Hz-8kHz)</p>
<p>灵敏度:模拟麦克风,灵敏度是-38dB(±3dB);数字麦克风,灵敏度是-26dB(±3dB)</p>
<h3 id="toc_80">麦克风位置和朝向参考</h3>
<p>百度语音引擎支持两种类型的麦克风输入模式:</p>
<p>1)单MIC,具体使用单指向MIC还是使用全指向MIC,要依具体项目情况而定;</p>
<p>2)双MIC阵列,我们有三点建议:</p>
<p>1)左右两个MIC的距离范围在50-80mm之间</p>
<p>2)MIC的安装朝向最好面朝用户,以确保更少的失真</p>
<p>3)推荐使用全指向MIC;</p>
<p>在设计麦克风安放位置时,需要尽量扩大产品内部噪音与麦克风之间的距离,远离干扰或震动。对于震动,一般采用硅胶套进行减震密封处理,对于硅胶软硬度,可根据实际情况进行匹配验证,一般要求尽可能软。</p>
<h3 id="toc_81">麦克风外壳要求参考</h3>
<p>一般来说,麦克风的外壳设计取决于所选的麦克风类型,全向麦克风安装最为简单,只需要一个开孔来接收环境音量即可;而双极和单极麦克风则要求每个麦克风两个开孔,每个开孔对应麦克风的纹路方向,这种机制将导致麦克风的闭环设计更加复杂。</p>
<h3 id="toc_82">功放增益设计参考</h3>
<p>喇叭和麦克风距离尽量远,喇叭到麦克风的声压不超过80分贝(在麦克风处测得),人声音量和喇叭音量强度信噪比不低于-15dB(人声到麦克风的声压约65分贝)。
建议调试步骤:</p>
<ul>
<li>在喇叭最大播音音量下,确保麦克录音不截幅;</li>
<li>在喇叭最大播音音量下,距离麦克60-100cm进行唤醒测试,如果不能正常唤醒,则需要调小功放增益,直到能正常唤醒为止。</li>
</ul>
<h1 id="toc_83">后视镜版本特殊说明</h1>
<p>针对后视镜的特点,DuerOS做了一些功能调整和UI适配。主要有</p>
<ul>
<li>行车记录仪栏目:需要DuerOS开发者通过该入口接入行车记录仪的功能。</li>
<li>电话栏目:需要DuerOS开发者通过该入口接入系统蓝牙电话。</li>
<li>设置栏目:需要DuerOS开发者通过该入口接入机器系统设置。</li>
</ul>
<h1 id="toc_84">云端语义服务</h1>
<h2 id="toc_85">概述</h2>
<p>云端语义服务包含语义解析和结果召回两个能力,合作伙伴直接将ASR识别后的文本通过接口提交到云端,即可以获取到包含召回结果的内容。</p>
<p>具体请参见<a href="#DuerOS%E5%8F%91%E5%B8%83%E5%8C%85%E5%8C%85%E5%90%AB%E4%BB%80%E4%B9%88%E5%86%85%E5%AE%B9">《百度DuerOS车载版云端API接入指南.docx》</a></p>
<h1 id="toc_86">第三方系统视觉规范</h1>
<p>具体请参见<a href="#DuerOS%E5%8F%91%E5%B8%83%E5%8C%85%E5%8C%85%E5%90%AB%E4%BB%80%E4%B9%88%E5%86%85%E5%AE%B9">《百度DuerOS车载版第三方视觉规范.pdf》</a></p>
<h1 id="toc_87">DuerOS测试验收流程</h1>
<p><a name="DuerOS测试验收流程" ></a></p>
<h2 id="toc_88">质量认证体系</h2>
<p>为保障百度DuerOS的质量及用户使用体验,我们制定了一系列测试验收流程,对DuerOS各个模块进行全面的质量检验,以决定其是否合格,是否达到量产标准。测试&验收主要包括四个环节:开发联调、全功能验收、合作方验收、量产验收(如下图所示),其中任何一轮测试不通过,需要相关负责人进行修复直至通过本轮测试才可开展后续测试。</p>
<p><img src="img/test_process.png" alt="DuerOS验收流程"></p>
<h3 id="toc_89">开发联调</h3>
<p>开发联调主要由双方研发人员负责,确保DuerOS各项核心功能在合作方设备上可以正常使用。</p>
<p>当开发联调完成(完成基本功能)后,合作方需要完成以下2项工作,才能进入全功能验收阶段:</p>
<ul>
<li>提供车机软、硬件环境。提供可安装DuerOS的车机、车机系统及使用DuerOS过程中的相关附属配件及系统配置说明文档。<strong>若车机系统版本有更新请及时通知百度DuerOS团队更新。车机最好为目标量产车机或者同系列车机。</strong></li>
<li>提供相关测试报告及文档。合作方完成联调开发后,需进行基本功能自测试,确保能达到全功能提测要求后,方可进入全功能验收流程,并且需提供以下文档和测试报告给百度,具体如下表。</li>
</ul>
<table>
<thead>
<tr>
<th style="text-align: left">编号</th>
<th style="text-align: left">名称</th>
<th style="text-align: left">形式</th>
<th style="text-align: left">介质</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">1</td>
<td style="text-align: left">基本功能测试报告</td>
<td style="text-align: left">文档</td>
<td style="text-align: left">电子/纸质</td>
</tr>
<tr>
<td style="text-align: left">2</td>
<td style="text-align: left">项目记录表--问题列表</td>
<td style="text-align: left">表格</td>
<td style="text-align: left">电子/纸质</td>
</tr>
</tbody>
</table>
<p>1) 基本功能测试报告。基本功能测试通过,具体参考<a href="#DuerOS%E5%8F%91%E5%B8%83%E5%8C%85%E5%8C%85%E5%90%AB%E4%BB%80%E4%B9%88%E5%86%85%E5%AE%B9">《百度DuerOS车载版基本功能测试Case.xlsx》</a></p>
<p>2) 问题记录表。合作方和百度共同维护此文档,在开发、测试、验收、回归过程中都以此文档为主,具体模板请参考 <a href="#DuerOS%E5%8F%91%E5%B8%83%E5%8C%85%E5%8C%85%E5%90%AB%E4%BB%80%E4%B9%88%E5%86%85%E5%AE%B9">《贵公司名称-DuerOS项目记录表.xlsx》</a>。</p>
<h3 id="toc_90">全功能验收</h3>
<p>全功能验收主要是指百度与合作方联调通过、达到全功能验收条件后,百度测试人员根据合作方提供的文档和报告进行一系列的全功能测试验收,全功能测试结束后百度将给出对应的测试报告及问题列表。</p>
<p>全功能验收阶段,百度侧进行以下两项工作,耗时2~3周: </p>
<ul>
<li> 进行一系列测试,包括DuerOS各个功能模块的功能测试、性能测试、稳定性测试等,测试完成后生成相应测试报告; </li>
<li> 记录验收过程中发现的问题,需把其录入到问题记录表并将结果同步给合作方共同跟进解决;</li>
</ul>
<p>关于测试过程中问题的解决机制:</p>
<ul>
<li>导致用户不能正常使用的问题,则必须解决;</li>
<li>针对偶现性问题,问题提出方需要进行复现,找到必现路径或者捕捉有效日志进行修复;</li>
<li>针对偶现率极低且对用户使用影响不大问题,建议降低优化级后续跟进处理。</li>
</ul>
<h3 id="toc_91">合作方验收</h3>
<p>全功能验收测试后,合作方可进行一系列系统测试、路测等测试手段发现问题,如属于百度问题,可写入问题记录表,邮件发送给百度方解决;如属于合作方问题,合作方需要对相应问题进行修复及测试验证,直到所有问题都已解决。</p>
<p>合作方产出项:</p>
<ul>
<li> 所有功能用例<a href="#DuerOS%E5%8F%91%E5%B8%83%E5%8C%85%E5%8C%85%E5%90%AB%E4%BB%80%E4%B9%88%E5%86%85%E5%AE%B9">《百度DuerOS车载版基本功能测试Case.xlsx》</a>测试结果;</li>
<li> 问题修复列表及验证结果,可通过问题记录表记录、维护</li>
<li> 若有遗留问题,请在问题列表中注明遗留原因。</li>
</ul>
<h3 id="toc_92">量产验收</h3>
<p>量产版本验收是百度使用合作方提供的量产车机,对DuerOS基本功能进行最终验证。验证结果为通过时,合作方才可进行量产,验收耗时1~2周。</p>
<p>合作方交付项:</p>
<ul>
<li> 量产车机,车机要搭载要量产的系统;</li>
<li> 功能测试及问题修复结果报告;</li>
<li> 遗留问题列表及原因;</li>
</ul>
<p>百度产出项:</p>
<ul>
<li>验收通过标准:
<ul>
<li>DuerOS所有功能模块正常运行,所有功能测试用例pass;</li>
<li>软件界面友好,易于交互,且符合车机端HMI设计规范;</li>
<li>车机系统使用带”DuerOS” 相关字样提示时,需提前与百度协商</li>
<li>无P0(严重),P1级(一般)级别以上BUG。</li>
</ul></li>
<li>量产验收结论:通过/不通过;</li>
</ul>
</article>
</div>
</div>
</body>
</html>
<script type="text/javascript" src="toc/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="toc/js/jquery.ztree.all-3.5.min.js"></script>
<script type="text/javascript" src="toc/js/ztree_toc.js"></script>
<SCRIPT type="text/javascript" >
<!--
$(document).ready(function(){
$('#tree').ztree_toc({
is_auto_number:true,
documment_selector:'.markdown-body',
ztreeStyle: {
width:'260px',
overflow: 'auto',
position: 'fixed',
'z-index': 2147483647,
border: '0px none',
left: '0px',
top: '0px'
}
});
});
//-->
</SCRIPT>
| {
"pile_set_name": "Github"
} |
<p align="center"><img src="https://github.com/gobuffalo/buffalo/blob/master/logo.svg" width="360"></p>
<p align="center">
<a href="https://godoc.org/github.com/gobuffalo/syncx"><img src="https://godoc.org/github.com/gobuffalo/syncx?status.svg" alt="GoDoc" /></a>
<a href="https://goreportcard.com/report/github.com/gobuffalo/syncx"><img src="https://goreportcard.com/badge/github.com/gobuffalo/syncx" alt="Go Report Card" /></a>
</p>
# github.com/gobuffalo/syncx
This package provides a set of types and tools for working in current environments.
See [https://godoc.org/github.com/gobuffalo/syncx](https://godoc.org/github.com/gobuffalo/syncx) for more details.
# Installation
```bash
$ go get github.com/gobuffalo/syncx
```
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2004, 2005, 2007 Nikolas Zimmermann <[email protected]>
* Copyright (C) 2004, 2005, 2007 Rob Buis <[email protected]>
* Copyright (C) 2007 Eric Seidel <[email protected]>
* Copyright (C) 2009 Google, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "RenderSVGViewportContainer.h"
#include "GraphicsContext.h"
#include "RenderView.h"
#include "SVGNames.h"
#include "SVGSVGElement.h"
namespace WebCore {
RenderSVGViewportContainer::RenderSVGViewportContainer(SVGSVGElement& element, RenderStyle&& style)
: RenderSVGContainer(element, WTFMove(style))
, m_didTransformToRootUpdate(false)
, m_isLayoutSizeChanged(false)
, m_needsTransformUpdate(true)
{
}
SVGSVGElement& RenderSVGViewportContainer::svgSVGElement() const
{
return downcast<SVGSVGElement>(RenderSVGContainer::element());
}
void RenderSVGViewportContainer::determineIfLayoutSizeChanged()
{
m_isLayoutSizeChanged = svgSVGElement().hasRelativeLengths() && selfNeedsLayout();
}
void RenderSVGViewportContainer::applyViewportClip(PaintInfo& paintInfo)
{
if (SVGRenderSupport::isOverflowHidden(*this))
paintInfo.context().clip(m_viewport);
}
void RenderSVGViewportContainer::calcViewport()
{
SVGSVGElement& element = svgSVGElement();
SVGLengthContext lengthContext(&element);
FloatRect newViewport(element.x().value(lengthContext), element.y().value(lengthContext), element.width().value(lengthContext), element.height().value(lengthContext));
if (m_viewport == newViewport)
return;
m_viewport = newViewport;
setNeedsBoundariesUpdate();
setNeedsTransformUpdate();
}
bool RenderSVGViewportContainer::calculateLocalTransform()
{
m_didTransformToRootUpdate = m_needsTransformUpdate || SVGRenderSupport::transformToRootChanged(parent());
if (!m_needsTransformUpdate)
return false;
m_localToParentTransform = AffineTransform::translation(m_viewport.x(), m_viewport.y()) * viewportTransform();
m_needsTransformUpdate = false;
return true;
}
AffineTransform RenderSVGViewportContainer::viewportTransform() const
{
return svgSVGElement().viewBoxToViewTransform(m_viewport.width(), m_viewport.height());
}
bool RenderSVGViewportContainer::pointIsInsideViewportClip(const FloatPoint& pointInParent)
{
// Respect the viewport clip (which is in parent coords)
if (!SVGRenderSupport::isOverflowHidden(*this))
return true;
return m_viewport.contains(pointInParent);
}
void RenderSVGViewportContainer::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
// An empty viewBox disables rendering.
if (svgSVGElement().hasEmptyViewBox())
return;
RenderSVGContainer::paint(paintInfo, paintOffset);
}
}
| {
"pile_set_name": "Github"
} |
// Copyright Aleksey Gurtovoy 2001-2004
// Copyright David Abrahams 2001-2002
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// *Preprocessed* version of the main "iter_fold_if_impl.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl { namespace aux {
template< typename Iterator, typename State >
struct iter_fold_if_null_step
{
typedef State state;
typedef Iterator iterator;
};
template< bool >
struct iter_fold_if_step_impl
{
template<
typename Iterator
, typename State
, typename StateOp
, typename IteratorOp
>
struct result_
{
typedef typename apply2< StateOp,State,Iterator >::type state;
typedef typename IteratorOp::type iterator;
};
};
template<>
struct iter_fold_if_step_impl<false>
{
template<
typename Iterator
, typename State
, typename StateOp
, typename IteratorOp
>
struct result_
{
typedef State state;
typedef Iterator iterator;
};
};
template<
typename Iterator
, typename State
, typename ForwardOp
, typename Predicate
>
struct iter_fold_if_forward_step
{
typedef typename apply2< Predicate,State,Iterator >::type not_last;
typedef typename iter_fold_if_step_impl<
BOOST_MPL_AUX_MSVC_VALUE_WKND(not_last)::value
>::template result_< Iterator,State,ForwardOp, mpl::next<Iterator> > impl_;
typedef typename impl_::state state;
typedef typename impl_::iterator iterator;
};
template<
typename Iterator
, typename State
, typename BackwardOp
, typename Predicate
>
struct iter_fold_if_backward_step
{
typedef typename apply2< Predicate,State,Iterator >::type not_last;
typedef typename iter_fold_if_step_impl<
BOOST_MPL_AUX_MSVC_VALUE_WKND(not_last)::value
>::template result_< Iterator,State,BackwardOp, identity<Iterator> > impl_;
typedef typename impl_::state state;
typedef typename impl_::iterator iterator;
};
template<
typename Iterator
, typename State
, typename ForwardOp
, typename ForwardPredicate
, typename BackwardOp
, typename BackwardPredicate
>
struct iter_fold_if_impl
{
private:
typedef iter_fold_if_null_step< Iterator,State > forward_step0;
typedef iter_fold_if_forward_step< typename forward_step0::iterator, typename forward_step0::state, ForwardOp, ForwardPredicate > forward_step1;
typedef iter_fold_if_forward_step< typename forward_step1::iterator, typename forward_step1::state, ForwardOp, ForwardPredicate > forward_step2;
typedef iter_fold_if_forward_step< typename forward_step2::iterator, typename forward_step2::state, ForwardOp, ForwardPredicate > forward_step3;
typedef iter_fold_if_forward_step< typename forward_step3::iterator, typename forward_step3::state, ForwardOp, ForwardPredicate > forward_step4;
typedef typename if_<
typename forward_step4::not_last
, iter_fold_if_impl<
typename forward_step4::iterator
, typename forward_step4::state
, ForwardOp
, ForwardPredicate
, BackwardOp
, BackwardPredicate
>
, iter_fold_if_null_step<
typename forward_step4::iterator
, typename forward_step4::state
>
>::type backward_step4;
typedef iter_fold_if_backward_step< typename forward_step3::iterator, typename backward_step4::state, BackwardOp, BackwardPredicate > backward_step3;
typedef iter_fold_if_backward_step< typename forward_step2::iterator, typename backward_step3::state, BackwardOp, BackwardPredicate > backward_step2;
typedef iter_fold_if_backward_step< typename forward_step1::iterator, typename backward_step2::state, BackwardOp, BackwardPredicate > backward_step1;
typedef iter_fold_if_backward_step< typename forward_step0::iterator, typename backward_step1::state, BackwardOp, BackwardPredicate > backward_step0;
public:
typedef typename backward_step0::state state;
typedef typename backward_step4::iterator iterator;
};
}}}
| {
"pile_set_name": "Github"
} |
/* This file was automatically generated by CasADi.
The CasADi copyright holders make no ownership claim of its contents. */
#ifdef __cplusplus
extern "C" {
#endif
/* How to prefix internal symbols */
#ifdef CODEGEN_PREFIX
#define NAMESPACE_CONCAT(NS, ID) _NAMESPACE_CONCAT(NS, ID)
#define _NAMESPACE_CONCAT(NS, ID) NS ## ID
#define CASADI_PREFIX(ID) NAMESPACE_CONCAT(CODEGEN_PREFIX, ID)
#else
#define CASADI_PREFIX(ID) ls_costN_nm10_ ## ID
#endif
#include <math.h>
#ifndef casadi_real
#define casadi_real double
#endif
#ifndef casadi_int
#define casadi_int int
#endif
/* Add prefix to internal symbols */
#define casadi_f0 CASADI_PREFIX(f0)
#define casadi_s0 CASADI_PREFIX(s0)
#define casadi_s1 CASADI_PREFIX(s1)
/* Symbol visibility in DLLs */
#ifndef CASADI_SYMBOL_EXPORT
#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
#if defined(STATIC_LINKED)
#define CASADI_SYMBOL_EXPORT
#else
#define CASADI_SYMBOL_EXPORT __declspec(dllexport)
#endif
#elif defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
#define CASADI_SYMBOL_EXPORT __attribute__ ((visibility ("default")))
#else
#define CASADI_SYMBOL_EXPORT
#endif
#endif
static const casadi_int casadi_s0[58] = {54, 1, 0, 54, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53};
static const casadi_int casadi_s1[111] = {54, 54, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53};
/* ls_costN_nm10:(i0[54])->(o0[54],o1[54x54,54nz]) */
static int casadi_f0(const casadi_real** arg, casadi_real** res, casadi_int* iw, casadi_real* w, void* mem) {
casadi_real a0;
a0=arg[0] ? arg[0][0] : 0;
if (res[0]!=0) res[0][0]=a0;
a0=arg[0] ? arg[0][1] : 0;
if (res[0]!=0) res[0][1]=a0;
a0=arg[0] ? arg[0][2] : 0;
if (res[0]!=0) res[0][2]=a0;
a0=arg[0] ? arg[0][3] : 0;
if (res[0]!=0) res[0][3]=a0;
a0=arg[0] ? arg[0][4] : 0;
if (res[0]!=0) res[0][4]=a0;
a0=arg[0] ? arg[0][5] : 0;
if (res[0]!=0) res[0][5]=a0;
a0=arg[0] ? arg[0][6] : 0;
if (res[0]!=0) res[0][6]=a0;
a0=arg[0] ? arg[0][7] : 0;
if (res[0]!=0) res[0][7]=a0;
a0=arg[0] ? arg[0][8] : 0;
if (res[0]!=0) res[0][8]=a0;
a0=arg[0] ? arg[0][9] : 0;
if (res[0]!=0) res[0][9]=a0;
a0=arg[0] ? arg[0][10] : 0;
if (res[0]!=0) res[0][10]=a0;
a0=arg[0] ? arg[0][11] : 0;
if (res[0]!=0) res[0][11]=a0;
a0=arg[0] ? arg[0][12] : 0;
if (res[0]!=0) res[0][12]=a0;
a0=arg[0] ? arg[0][13] : 0;
if (res[0]!=0) res[0][13]=a0;
a0=arg[0] ? arg[0][14] : 0;
if (res[0]!=0) res[0][14]=a0;
a0=arg[0] ? arg[0][15] : 0;
if (res[0]!=0) res[0][15]=a0;
a0=arg[0] ? arg[0][16] : 0;
if (res[0]!=0) res[0][16]=a0;
a0=arg[0] ? arg[0][17] : 0;
if (res[0]!=0) res[0][17]=a0;
a0=arg[0] ? arg[0][18] : 0;
if (res[0]!=0) res[0][18]=a0;
a0=arg[0] ? arg[0][19] : 0;
if (res[0]!=0) res[0][19]=a0;
a0=arg[0] ? arg[0][20] : 0;
if (res[0]!=0) res[0][20]=a0;
a0=arg[0] ? arg[0][21] : 0;
if (res[0]!=0) res[0][21]=a0;
a0=arg[0] ? arg[0][22] : 0;
if (res[0]!=0) res[0][22]=a0;
a0=arg[0] ? arg[0][23] : 0;
if (res[0]!=0) res[0][23]=a0;
a0=arg[0] ? arg[0][24] : 0;
if (res[0]!=0) res[0][24]=a0;
a0=arg[0] ? arg[0][25] : 0;
if (res[0]!=0) res[0][25]=a0;
a0=arg[0] ? arg[0][26] : 0;
if (res[0]!=0) res[0][26]=a0;
a0=arg[0] ? arg[0][27] : 0;
if (res[0]!=0) res[0][27]=a0;
a0=arg[0] ? arg[0][28] : 0;
if (res[0]!=0) res[0][28]=a0;
a0=arg[0] ? arg[0][29] : 0;
if (res[0]!=0) res[0][29]=a0;
a0=arg[0] ? arg[0][30] : 0;
if (res[0]!=0) res[0][30]=a0;
a0=arg[0] ? arg[0][31] : 0;
if (res[0]!=0) res[0][31]=a0;
a0=arg[0] ? arg[0][32] : 0;
if (res[0]!=0) res[0][32]=a0;
a0=arg[0] ? arg[0][33] : 0;
if (res[0]!=0) res[0][33]=a0;
a0=arg[0] ? arg[0][34] : 0;
if (res[0]!=0) res[0][34]=a0;
a0=arg[0] ? arg[0][35] : 0;
if (res[0]!=0) res[0][35]=a0;
a0=arg[0] ? arg[0][36] : 0;
if (res[0]!=0) res[0][36]=a0;
a0=arg[0] ? arg[0][37] : 0;
if (res[0]!=0) res[0][37]=a0;
a0=arg[0] ? arg[0][38] : 0;
if (res[0]!=0) res[0][38]=a0;
a0=arg[0] ? arg[0][39] : 0;
if (res[0]!=0) res[0][39]=a0;
a0=arg[0] ? arg[0][40] : 0;
if (res[0]!=0) res[0][40]=a0;
a0=arg[0] ? arg[0][41] : 0;
if (res[0]!=0) res[0][41]=a0;
a0=arg[0] ? arg[0][42] : 0;
if (res[0]!=0) res[0][42]=a0;
a0=arg[0] ? arg[0][43] : 0;
if (res[0]!=0) res[0][43]=a0;
a0=arg[0] ? arg[0][44] : 0;
if (res[0]!=0) res[0][44]=a0;
a0=arg[0] ? arg[0][45] : 0;
if (res[0]!=0) res[0][45]=a0;
a0=arg[0] ? arg[0][46] : 0;
if (res[0]!=0) res[0][46]=a0;
a0=arg[0] ? arg[0][47] : 0;
if (res[0]!=0) res[0][47]=a0;
a0=arg[0] ? arg[0][48] : 0;
if (res[0]!=0) res[0][48]=a0;
a0=arg[0] ? arg[0][49] : 0;
if (res[0]!=0) res[0][49]=a0;
a0=arg[0] ? arg[0][50] : 0;
if (res[0]!=0) res[0][50]=a0;
a0=arg[0] ? arg[0][51] : 0;
if (res[0]!=0) res[0][51]=a0;
a0=arg[0] ? arg[0][52] : 0;
if (res[0]!=0) res[0][52]=a0;
a0=arg[0] ? arg[0][53] : 0;
if (res[0]!=0) res[0][53]=a0;
a0=1.;
if (res[1]!=0) res[1][0]=a0;
if (res[1]!=0) res[1][1]=a0;
if (res[1]!=0) res[1][2]=a0;
if (res[1]!=0) res[1][3]=a0;
if (res[1]!=0) res[1][4]=a0;
if (res[1]!=0) res[1][5]=a0;
if (res[1]!=0) res[1][6]=a0;
if (res[1]!=0) res[1][7]=a0;
if (res[1]!=0) res[1][8]=a0;
if (res[1]!=0) res[1][9]=a0;
if (res[1]!=0) res[1][10]=a0;
if (res[1]!=0) res[1][11]=a0;
if (res[1]!=0) res[1][12]=a0;
if (res[1]!=0) res[1][13]=a0;
if (res[1]!=0) res[1][14]=a0;
if (res[1]!=0) res[1][15]=a0;
if (res[1]!=0) res[1][16]=a0;
if (res[1]!=0) res[1][17]=a0;
if (res[1]!=0) res[1][18]=a0;
if (res[1]!=0) res[1][19]=a0;
if (res[1]!=0) res[1][20]=a0;
if (res[1]!=0) res[1][21]=a0;
if (res[1]!=0) res[1][22]=a0;
if (res[1]!=0) res[1][23]=a0;
if (res[1]!=0) res[1][24]=a0;
if (res[1]!=0) res[1][25]=a0;
if (res[1]!=0) res[1][26]=a0;
if (res[1]!=0) res[1][27]=a0;
if (res[1]!=0) res[1][28]=a0;
if (res[1]!=0) res[1][29]=a0;
if (res[1]!=0) res[1][30]=a0;
if (res[1]!=0) res[1][31]=a0;
if (res[1]!=0) res[1][32]=a0;
if (res[1]!=0) res[1][33]=a0;
if (res[1]!=0) res[1][34]=a0;
if (res[1]!=0) res[1][35]=a0;
if (res[1]!=0) res[1][36]=a0;
if (res[1]!=0) res[1][37]=a0;
if (res[1]!=0) res[1][38]=a0;
if (res[1]!=0) res[1][39]=a0;
if (res[1]!=0) res[1][40]=a0;
if (res[1]!=0) res[1][41]=a0;
if (res[1]!=0) res[1][42]=a0;
if (res[1]!=0) res[1][43]=a0;
if (res[1]!=0) res[1][44]=a0;
if (res[1]!=0) res[1][45]=a0;
if (res[1]!=0) res[1][46]=a0;
if (res[1]!=0) res[1][47]=a0;
if (res[1]!=0) res[1][48]=a0;
if (res[1]!=0) res[1][49]=a0;
if (res[1]!=0) res[1][50]=a0;
if (res[1]!=0) res[1][51]=a0;
if (res[1]!=0) res[1][52]=a0;
if (res[1]!=0) res[1][53]=a0;
return 0;
}
CASADI_SYMBOL_EXPORT int ls_costN_nm10(const casadi_real** arg, casadi_real** res, casadi_int* iw, casadi_real* w, void* mem){
return casadi_f0(arg, res, iw, w, mem);
}
CASADI_SYMBOL_EXPORT void ls_costN_nm10_incref(void) {
}
CASADI_SYMBOL_EXPORT void ls_costN_nm10_decref(void) {
}
CASADI_SYMBOL_EXPORT casadi_int ls_costN_nm10_n_in(void) { return 1;}
CASADI_SYMBOL_EXPORT casadi_int ls_costN_nm10_n_out(void) { return 2;}
CASADI_SYMBOL_EXPORT const char* ls_costN_nm10_name_in(casadi_int i){
switch (i) {
case 0: return "i0";
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const char* ls_costN_nm10_name_out(casadi_int i){
switch (i) {
case 0: return "o0";
case 1: return "o1";
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const casadi_int* ls_costN_nm10_sparsity_in(casadi_int i) {
switch (i) {
case 0: return casadi_s0;
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const casadi_int* ls_costN_nm10_sparsity_out(casadi_int i) {
switch (i) {
case 0: return casadi_s0;
case 1: return casadi_s1;
default: return 0;
}
}
CASADI_SYMBOL_EXPORT int ls_costN_nm10_work(casadi_int *sz_arg, casadi_int* sz_res, casadi_int *sz_iw, casadi_int *sz_w) {
if (sz_arg) *sz_arg = 1;
if (sz_res) *sz_res = 2;
if (sz_iw) *sz_iw = 0;
if (sz_w) *sz_w = 0;
return 0;
}
#ifdef __cplusplus
} /* extern "C" */
#endif
| {
"pile_set_name": "Github"
} |
all: dns dns_all
clean:
rm -f *.o dns dns_all
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="iso-8859-1"?>
<!--
// Copyright (C) 2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: (GPL-2.0-or-later OR CC-BY-SA-4.0)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// -
//
// At your option, you can also redistribute and/or modify this file
// under a
// Creative Commons Attribution-ShareAlike 4.0 International License.
//
// You should have received a copy of the license along with this
// work. If not, see <http://creativecommons.org/licenses/by-sa/4.0/>.
-->
<shapes>
<poly id="blocker" type="building" color="1.00,0.00,0.00" fill="1" layer="4" shape="10,10 90,10 90,90 10,90 10,10"/>
</shapes>
| {
"pile_set_name": "Github"
} |
# Copyright 2019 Google LLC
#
# 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.
"""Constants that are meaningful to libFuzzer.
Should not have any dependancies.
Note that libFuzzers arguments take the form -flag=value. Thus any variables
defined in this function that end with the suffix "_FLAG" should contain
"-flag=". Any variable that ends with the suffix "_ARGUMENT" should contain
"-flag=value".
"""
# libFuzzer flags.
ARTIFACT_PREFIX_FLAG = '-artifact_prefix='
DATA_FLOW_TRACE_FLAG = '-data_flow_trace='
DICT_FLAG = '-dict='
FOCUS_FUNCTION_FLAG = '-focus_function='
FORK_FLAG = '-fork='
MAX_LEN_FLAG = '-max_len='
MAX_TOTAL_TIME_FLAG = '-max_total_time='
RSS_LIMIT_FLAG = '-rss_limit_mb='
RUNS_FLAG = '-runs='
TIMEOUT_FLAG = '-timeout='
EXACT_ARTIFACT_PATH_FLAG = '-exact_artifact_path='
# libFuzzer arguments.
ANALYZE_DICT_ARGUMENT = '-analyze_dict=1'
CLEANSE_CRASH_ARGUMENT = '-cleanse_crash=1'
ENTROPIC_ARGUMENT = '-entropic=1'
MERGE_ARGUMENT = '-merge=1'
MERGE_CONTROL_FILE_ARGUMENT = '-merge_control_file='
MINIMIZE_CRASH_ARGUMENT = '-minimize_crash=1'
PRINT_FINAL_STATS_ARGUMENT = '-print_final_stats=1'
TMP_ARTIFACT_PREFIX_ARGUMENT = '/tmp/'
VALUE_PROFILE_ARGUMENT = '-use_value_profile=1'
# Default value for rss_limit_mb flag to catch OOM.s
DEFAULT_RSS_LIMIT_MB = 2560
# Default value for timeout flag to catch timeouts.
DEFAULT_TIMEOUT_LIMIT = 25
# Buffer for processing crash reports.
REPORT_PROCESSING_TIME = 5
# libFuzzer's exit code if a bug occurred in libFuzzer.
LIBFUZZER_ERROR_EXITCODE = 1
# Defines value of runs argument when loading a testcase.
RUNS_TO_REPRODUCE = 100
# libFuzzer's exit code if a bug was found in the target code.
TARGET_ERROR_EXITCODE = 77
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2013, 2014 Megion Research and Development GmbH
*
* Licensed under the Microsoft Reference Source License (MS-RSL)
*
* This license governs use of the accompanying software. If you use the software, you accept this license.
* If you do not accept the license, do not use the software.
*
* 1. Definitions
* The terms "reproduce," "reproduction," and "distribution" have the same meaning here as under U.S. copyright law.
* "You" means the licensee of the software.
* "Your company" means the company you worked for when you downloaded the software.
* "Reference use" means use of the software within your company as a reference, in read only form, for the sole purposes
* of debugging your products, maintaining your products, or enhancing the interoperability of your products with the
* software, and specifically excludes the right to distribute the software outside of your company.
* "Licensed patents" means any Licensor patent claims which read directly on the software as distributed by the Licensor
* under this license.
*
* 2. Grant of Rights
* (A) Copyright Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive,
* worldwide, royalty-free copyright license to reproduce the software for reference use.
* (B) Patent Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive,
* worldwide, royalty-free patent license under licensed patents for reference use.
*
* 3. Limitations
* (A) No Trademark License- This license does not grant you any rights to use the Licensor’s name, logo, or trademarks.
* (B) If you begin patent litigation against the Licensor over patents that you think may apply to the software
* (including a cross-claim or counterclaim in a lawsuit), your license to the software ends automatically.
* (C) The software is licensed "as-is." You bear the risk of using it. The Licensor gives no express warranties,
* guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot
* change. To the extent permitted under your local laws, the Licensor excludes the implied warranties of merchantability,
* fitness for a particular purpose and non-infringement.
*/
package com.mycelium.wallet.activity.modern;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import com.mrd.bitlib.crypto.InMemoryPrivateKey;
import com.mrd.bitlib.model.Address;
import com.mycelium.wallet.MbwManager;
import com.mycelium.wallet.R;
import com.mycelium.wallet.Utils;
import com.mycelium.wallet.activity.MessageSigningActivity;
import com.mycelium.wallet.activity.util.AddressLabel;
import com.mycelium.wapi.wallet.AddressUtils;
import com.mycelium.wapi.wallet.AesKeyCipher;
import com.mycelium.wapi.wallet.GenericAddress;
import com.mycelium.wapi.wallet.KeyCipher;
import com.mycelium.wapi.wallet.btc.BtcAddress;
import com.mycelium.wapi.wallet.btc.bip44.HDAccount;
import java.util.List;
import java.util.UUID;
public class HDSigningActivity extends Activity {
private static final LinearLayout.LayoutParams WCWC = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
private SigningClickListener _signingClickListener;
private MbwManager _mbwManager;
private UUID _accountid;
@Override
public void onCreate(Bundle savedInstanceState) {
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.hd_signing_activity);
_signingClickListener = new SigningClickListener();
_mbwManager = MbwManager.getInstance(this.getApplication());
_accountid = (UUID) getIntent().getSerializableExtra("account");
updateUi();
}
private void updateUi() {
LinearLayout addressView = findViewById(R.id.listPrivateKeyAddresses);
HDAccount account = (HDAccount) _mbwManager.getWalletManager(false).getAccount(_accountid);
//sort addresses by alphabet for easier selection
List<Address> addresses = Utils.sortAddresses(account.getAllAddresses());
for (Address address : addresses) {
addressView.addView(getItemView(address));
}
}
private View getItemView(Address address) {
// Create vertical linear layout for address
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setLayoutParams(WCWC);
ll.setPadding(10, 10, 10, 10);
// Add address chunks
AddressLabel addressLabel = new AddressLabel(this);
addressLabel.setAddress(AddressUtils.fromAddress(address));
ll.addView(addressLabel);
//Make address clickable
addressLabel.setOnClickListener(_signingClickListener);
return ll;
}
private class SigningClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
AddressLabel addressLabel = (AddressLabel) v;
if (addressLabel.getAddress() == null) {
return;
}
HDAccount account = (HDAccount) _mbwManager.getWalletManager(false).getAccount(_accountid);
InMemoryPrivateKey key;
BtcAddress btcAddress = (BtcAddress)addressLabel.getAddress();
try {
key = account.getPrivateKeyForAddress(btcAddress.getAddress(), AesKeyCipher.defaultKeyCipher());
} catch (KeyCipher.InvalidKeyCipher invalidKeyCipher) {
throw new RuntimeException(invalidKeyCipher);
}
MessageSigningActivity.callMe(HDSigningActivity.this, key, btcAddress);
}
}
}
| {
"pile_set_name": "Github"
} |
# 構造化束縛を拡張して通常の変数宣言のように使用できるようにする
* cpp20[meta cpp]
## 概要
C++17で導入された構造化束縛宣言に指定しておけるのはCV修飾のみで、記憶域クラスや`constexpr`等を指定することは出来なかった。
このため、`thread_local`指定の変数や`constexpr`変数などの初期化のために構造化束縛を用いることが出来なかった。
C++20ではこの制限が少し緩和され、構造化束縛宣言に`static`および`thread_local`を指定することができるようになり、それらの効果は通常の変数と同様となるようになった。
すなわち、`static`指定では内部リンケージが与えられ、`thread_local`指定ではスレッドローカルストレージに配置されるようになり、どちらの場合もその構造化束縛宣言のなされているスコープに関わらず静的ストレージに配置される。
ただし、`inline`や`constexpr`、`constinit`等その他の指定は出来ず、指定された場合コンパイルエラーとなる。
また、C++17では構造化束縛宣言に指定した変数名をそのままラムダ式でキャプチャすることもできなかった。しかし、禁止しておく技術的な(コンパイラ実装上の)理由は無かったことから、この制限は撤廃された。
これによって、構造化束縛の変数を通常の変数とほぼ同じようにラムダ式でキャプチャできるようになる。ただし、ビットフィールドを参照キャプチャする場合は少し注意が必要である(詳しくは[構造化束縛したビットフィールドの参照キャプチャ](/lang/cpp20/reference_capture_of_structured_bindings.md.nolink)を参照のこと)。
## 例
### `static`と`thread_local`
```cpp example
#include <iostream>
#include <thread>
#include <random>
#include <utility>
//乱数エンジンを初期化し、最初の乱数値とともに返す
std::pair<std::mt19937, std::uint32_t> get_random() {
std::mt19937 engine(std::random_device{}());
auto first = engine();
return {std::move(engine), first};
}
//static指定構造化束縛宣言
static auto [engin_static, value_static] = get_random();
//thread_local指定構造化束縛宣言
thread_local auto [engin_tls, value_tls] = get_random();
int main()
{
std::cout << "---in main thread---" << std::endl;
std::cout << "static value = " << value_static << std::endl;
std::cout << "thread local value = " << value_tls << std::endl;
//エンジンのアドレスを出力
std::cout << "static engine = " << &engin_static << std::endl;
std::cout << "thread local engine = " << &engin_tls << std::endl;
std::thread th([]() {
std::cout << "\n---in another thread---" << std::endl;
std::cout << "static value = " << value_static << std::endl;
std::cout << "thread local value = " << value_tls << std::endl;
//エンジンのアドレスを出力
std::cout << "static engine = " << &engin_static << std::endl;
std::cout << "thread local engine = " << &engin_tls << std::endl;
});
th.join();
}
```
### 出力例
```
---in main thread---
static value = 3324737157
thread local value = 300715623
static engine = 0x6057a0
thread local engine = 0x7f01e57a2798
---in another thread---
static value = 3324737157
thread local value = 944600859
static engine = 0x6057a0
thread local engine = 0x7f01df50c358
```
シード値及びエンジンの配置アドレスは実行の度に変化するので、実行毎に異なる結果となる。
### ラムダ式によるキャプチャ
```cpp example
#include <iostream>
#include <tuple>
int main()
{
auto tuple = std::make_tuple(1.0, 2.0, 3.0);
auto& [a, b, c] = tuple;
//コピーキャプチャ
auto f_copy = [a, b, c]() {return a + b + c;};
//参照キャプチャ
auto f_ref = [&a, &b, &c]() {return a + b + c;};
std::cout << f_copy() << std::endl;
std::cout << f_ref() << std::endl;
a = 4.0;
std::cout << f_copy() << std::endl;
std::cout << f_ref() << std::endl;
}
```
### 出力
```
6
6
6
9
```
## 検討されたほかの選択肢
当初の提案では上記の3つだけではなく、リンケージ指定(`extern`)、`inline`指定、`constexpr`指定、`[[maybe_unused]]`属性指定、テンプレート、などもまとめて許可し、通常の変数との差異をほぼ完全に無くす予定であった。
しかし、`extern`による外部リンケージの指定は構造化束縛の仕様上意味が無く、それによって外部リンケージの有無で`inline`指定の可否の一貫性が無くなることから`inline`も許可されず、`constexpr`及びテンプレートについては変更範囲が広くなり詳細な検討が必要であることから見送られた。
その結果、ラムダキャプチャの許可と`static`と`thread_local`指定のみが残ることとなった。
ただ、今回見送られた残りのものも将来的には許可される可能性がある。
## 関連項目
- [C++17 構造化束縛](/lang/cpp17/structured_bindings.md)
- [C++20 構造化束縛したビットフィールドの参照キャプチャ](/lang/cpp20/reference_capture_of_structured_bindings.md.nolink)
## 参照
- [P1091R0 Extending structured bindings to be more like variable declarations](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1091r0.html)
- [P1091R1 Extending structured bindings to be more like variable declarations](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1091r1.html)
- [P1091R2 Extending structured bindings to be more like variable declarations](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1091r2.html)
- [P1091R3 Extending structured bindings to be more like variable declarations](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1091r3.html)
| {
"pile_set_name": "Github"
} |
* {
box-sizing: border-box;
}
html {
font-size: 16px;
}
body {
font-family: 'Open Sans', sans-serif;
}
.label {
border: 2px solid black;
width: 270px;
margin: 20px auto;
padding: 0 7px;
}
header h1 {
text-align: center;
margin: -4px 0;
letter-spacing: 0.15px;
}
p {
margin: 0;
}
.divider {
border-bottom: 1px solid #888989;
margin: 2px 0;
clear: both;
}
.bold {
font-weight: 800;
}
.right {
float: right;
}
.md, .lg {
background-color: black;
border: 0;
}
.md {
height: 5px;
}
.lg {
height: 10px;
}
.sm-text {
font-size: 0.85rem;
}
.calories-info h1 {
margin: -5px -2px;
overflow: hidden;
}
.calories-info span {
font-size: 1.2em;
margin-top: -7px;
}
.indent {
margin-left: 1em;
}
.dbl-indent {
margin-left: 2em;
}
.daily-value p:not(.no-divider) {
border-bottom: 1px solid #888989;
}
| {
"pile_set_name": "Github"
} |
// ***************************************************************************
// *
// * Copyright (C) 2010 International Business Machines
// * Corporation and others. All Rights Reserved.
// * Tool: com.ibm.icu.dev.tool.cldr.LDML2ICUConverter.java
// * Source File:<path>/icu-config.xml & build.xml
// *
// ***************************************************************************
/**
* validSubLocale of "de"
*/
de_LI{
/**
* so genrb doesn't issue warnings
*/
___{""}
}
| {
"pile_set_name": "Github"
} |
// ngc.h
//
// -------------------------------------------------
// Copyright 2015-2020 Dominic Ford
//
// This file is part of StarCharter.
//
// StarCharter is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// StarCharter 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with StarCharter. If not, see <http://www.gnu.org/licenses/>.
// -------------------------------------------------
#ifndef NGC_H
#define NGC_H 1
#include <stdlib.h>
#include <stdio.h>
#include "settings/chart_config.h"
#include "vectorGraphics/lineDraw.h"
#include "vectorGraphics/cairo_page.h"
void plot_ngc_objects(chart_config *s, cairo_page *page);
#endif
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.sample.showcase.client.content.widgets;
import com.google.gwt.i18n.client.Constants;
import com.google.gwt.sample.showcase.client.ContentWidget;
import com.google.gwt.sample.showcase.client.ShowcaseAnnotations.ShowcaseData;
import com.google.gwt.sample.showcase.client.ShowcaseAnnotations.ShowcaseSource;
import com.google.gwt.sample.showcase.client.ShowcaseAnnotations.ShowcaseStyle;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Example file.
*/
@ShowcaseStyle(".gwt-CheckBox")
public class CwCheckBox extends ContentWidget {
/**
* The constants used in this Content Widget.
*/
@ShowcaseSource
public static interface CwConstants extends Constants {
String cwCheckBoxCheckAll();
String[] cwCheckBoxDays();
String cwCheckBoxDescription();
String cwCheckBoxName();
}
/**
* An instance of the constants.
*/
@ShowcaseData
private final CwConstants constants;
/**
* Constructor.
*
* @param constants the constants
*/
public CwCheckBox(CwConstants constants) {
super(constants.cwCheckBoxName(), constants.cwCheckBoxDescription(), true);
this.constants = constants;
}
/**
* Initialize this example.
*/
@ShowcaseSource
@Override
public Widget onInitialize() {
// Create a vertical panel to align the check boxes
VerticalPanel vPanel = new VerticalPanel();
HTML label = new HTML(constants.cwCheckBoxCheckAll());
label.ensureDebugId("cwCheckBox-label");
vPanel.add(label);
// Add a checkbox for each day of the week
String[] daysOfWeek = constants.cwCheckBoxDays();
for (int i = 0; i < daysOfWeek.length; i++) {
String day = daysOfWeek[i];
CheckBox checkBox = new CheckBox(day);
checkBox.ensureDebugId("cwCheckBox-" + day);
// Disable the weekends
if (i >= 5) {
checkBox.setEnabled(false);
}
vPanel.add(checkBox);
}
// Return the panel of checkboxes
return vPanel;
}
@Override
protected void asyncOnInitialize(final AsyncCallback<Widget> callback) {
/*
* CheckBox is the first demo loaded, so go ahead and load it synchronously.
*/
callback.onSuccess(onInitialize());
}
}
| {
"pile_set_name": "Github"
} |
%% Kuramoto-Sivashinsky equation and chaos
nn = 511;
steps = 250;
dom = [-10 10]; x = chebfun('x',dom); tspan = linspace(0,50,steps+1);
S = spinop(dom, tspan);
S.lin = @(u) - diff(u,2) - diff(u,4);
S.nonlin = @(u) - 0.5*diff(u.^2); % spin cannot parse "u.*diff(u)"
% S.init = cos(x/16).*(1+sin(x/16));
S.init = -sin(pi*x/10);
u = spin(S,nn,1e-5);
usol = zeros(nn,steps+1);
for i = 1:steps+1
usol(:,i) = u{i}.values;
end
x = linspace(-10,10,nn+1);
usol = [usol;usol(1,:)];
t = tspan;
pcolor(t,x,usol); shading interp, axis tight, colormap(jet);
save('ks_simple.mat','t','x','usol')
| {
"pile_set_name": "Github"
} |
var assert = require('assert');
var st = require('../../../st.js');
var stringify = require('json-stable-stringify');
var compare = function(actual, expected){
assert.equal(stringify(actual), stringify(expected));
};
describe("TRANSFORM.run", function() {
describe('template edge cases', function(){
it('should be able to escape double curly braces', function(){
var template = "{{var jsobj = {func: function() { return 'foo'; } }; return jsobj.func();}}";
var data = {};
var actual = st.TRANSFORM.run(template,data);
compare(actual, "foo");
});
it("parses empty string correctly", function(){
var data = {
"text": ""
}
var template = {
"text": ""
}
var actual = st.TRANSFORM.transform(template, data);
compare(actual, template);
})
it("works when a template expression is used for both key and value", function(){
var data = {
"key": "this is key",
"value": "this is value"
}
var template = {
"{{key}}": "{{value}}"
}
var actual = st.TRANSFORM.transform(template, data);
compare(actual, {"this is key": "this is value"});
})
it('should correctly parse regular expression', function(){
var template = "{{price.amount.toFixed(2).replace(/(\\d)(?=(\\d{3})+\\.)/g, '$1,')}}";
var data = {"price": {"amount": 1000000}};
var actual = st.TRANSFORM.run(template,data);
compare(actual, "1,000,000.00");
});
describe("template is static json", function() {
it("boolean value should be preserved", function() {
var data = {
"what": "ever"
}
var template = {
bool: true
}
var actual = st.TRANSFORM.transform(template, data);
compare(actual, {bool: true});
});
it("static json should stay exactly the same", function() {
var data = {
$jason: {
head: {
title: "HI"
},
body: {
sections: [{
items: [{
type: "label",
text: "HI"
}]
}]
}
}
}
var template = {
$jason: {
head: {
title: "HI"
},
body: {
sections: [{
items: [{
type: "label",
text: "HI"
}]
}]
}
}
};
var actual = st.TRANSFORM.transform(template, data);
compare(actual, template);
});
it("null value should be preserved", function() {
var data = {
"what": "ever"
}
var template = {
bool: null
}
var actual = st.TRANSFORM.transform(template, data);
compare(actual, {bool: null});
});
})
});
});
describe('TRANSFORM.fillout', function() {
describe("string interpolation should work", function(){
it('should correctly parse when a template is used along with static string', function(){
var actual = st.TRANSFORM.fillout(
{"user": "tom"},
"This is {{user}}"
);
compare(actual, "This is tom");
});
});
describe("handling multiple templates in a string", function(){
it('should correctly parse multiple templates in a string', function(){
var actual = st.TRANSFORM.fillout(
{"users": ["tom", "jane", "obafe"]},
"This is an {{users[0]}} and {{users[1]}}"
);
compare(actual, "This is an tom and jane");
});
it('should correctly parse multiple templates in a string', function(){
var template = "{{$jason.title}} and {{$jason.description}}";
var data = {"$jason": {"title": "This is a title", "description": "This is a description"}};
var actual = st.TRANSFORM.fillout(data, template);
var expected = "This is a title and This is a description";
compare(actual, expected);
});
});
describe("Handling null/undefined cases", function(){
// Handling Exception cases
// When the parsed result is null, it could be an error.
// But also it could be that the current run is not meant to parse the template
// and may need to be parsed by another dataset, so we should keep the
// template as is
it('should not parse broken template', function(){
var template = {
"$frame": "NSRect: {{0, 0}, {375, 284}}",
"inline": "true",
"url": "https://vjs.zencdn.net/v/oceans.mp4"
};
var data = {"$cache": {}};
var actual = st.TRANSFORM.fillout(data, template);
compare(actual, template);
});
it('should return the template string when the result is null', function(){
var actual1 = st.TRANSFORM.fillout(
{"users": ["tom", "jane", "obafe"]},
"This is an {{users[0]}}"
);
var actual2 = st.TRANSFORM.fillout(
{"users": ["tom", "jane", "obafe"]},
"This is an {{items[0]}}"
);
compare(actual1, "This is an tom");
compare(actual2, "This is an {{items[0]}}");
});
});
describe("Handling objects and array results", function(){
it('should return an actual array if the result is an array', function(){
var actual = st.TRANSFORM.fillout( {"a": ['item1','item2']}, "{{a}}");
compare(actual, ['item1', 'item2']);
});
it('standalone this where this is object', function(){
var actual = st.TRANSFORM.fillout( {"a": {"key": 'item1'}}, "{{a}}");
compare(actual, {"key": "item1"});
});
});
describe("handling map", function(){
it('correctly runs map function', function(){
var data = {"items": {"0": {name: "kate", age: "23"}, "1": {name: "Lassie", age: "3"}}};
var actual = st.TRANSFORM.fillout(data, "{{Object.keys(items).map(function(key){return items[key].name;})}}");
compare(actual, ["kate", "Lassie"]);
});
it('correctly parses a map loop: *this* edition', function(){
var data = ["1", "2", "3"];
var template = "{{this.map(function(item){ return {db: item}; }) }}";
var actual = st.TRANSFORM.fillout(data, template);
compare(actual, [{"db": "1"}, {"db": "2"}, {"db": "3"}]);
});
it('correctly parses a map loop: $jason edition', function(){
var data = {"$jason": ["1", "2", "3"]};
var template = "{{$jason.map(function(item){return {db: item};})}}";
var actual = st.TRANSFORM.fillout(data, template);
compare(actual, [{"db": "1"}, {"db": "2"}, {"db": "3"}]);
});
it('correctly parses a local variable inside of a map loop', function(){
var data = {"$params": {"title": "title", "url": "url"}, "$jason": ["1", "2", "3"]};
var template = "{{$jason.map(function(item){return {db: item, title: $params.title, url: $params.url};})}}";
var actual = st.TRANSFORM.fillout(data, template);
compare(actual, [{"db": "1", "title": "title", "url": "url"}, {"db": "2", "title": "title", "url": "url"}, {"db": "3", "title": "title", "url": "url"}]);
});
});
describe("Handling 'this'", function(){
it('standalone this where this is array', function(){
var actual = st.TRANSFORM.fillout( ['item1','item2'], "This is an {{this}}");
compare(actual, "This is an item1,item2");
});
it('standalone this where this is string', function(){
var actual = st.TRANSFORM.fillout( "item1", "This is an {{this}}");
compare(actual, "This is an item1");
});
it('standalone this where this is object', function(){
var actual = st.TRANSFORM.fillout( {"key": 'item1'}, "This is an {{this}}");
compare(actual, "This is an [object Object]");
});
it('attributes for this', function(){
var actual = st.TRANSFORM.fillout(
{"item": "item1"},
"This is an {{this.item}}"
);
compare(actual, "This is an item1");
});
it('when this is an array', function(){
var actual = st.TRANSFORM.fillout(
['item1', 'item2', 'item3'],
"This is an {{this[1]}}"
);
compare(actual, "This is an item2");
});
});
describe("Handling 'fillout' exceptions", function(){
it('should handle try to wrap the expression in an immediately invoked function and try one more time', function(){
var actual1 = st.TRANSFORM.fillout(
{a: []},
"{{a.push(\"2\"); return a;}}"
);
compare(actual1, ["2"]);
var actual2 = st.TRANSFORM.fillout(
{a: ["1"]},
"{{a.push(\"2\"); return a;}}"
);
compare(actual2, ["1","2"]);
var actual3 = st.TRANSFORM.fillout(
{a: ["1"]},
"{{a.push(\"2\"); return a}}"
);
compare(actual3, ["1","2"]);
});
it('should handle try to wrap the expression in an immediately invoked function and try one more time, for even more complex expressions', function(){
var actual = st.TRANSFORM.fillout(
{created_at: 1475369605422},
"{{var d = new Date(created_at); var day = d.getUTCDay(); var daymap = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; var realDay = daymap[parseInt(day)]; var h = d.getUTCHours(); var m = d.getUTCMinutes(); var suffix = (h > 11 ? 'pm' : 'am'); var hh = (h > 12 ? h - 12 : h); var mm = (m > 9 ? m : '0'+m); return realDay + ' ' + hh + ':' + mm + ' ' + suffix;}}"
);
compare(actual, "Sunday 0:53 am");
});
it('should return a blank space when the evaluated value is null or false', function(){
var actual = st.TRANSFORM.fillout(
{a: false},
"This is a [{{a}}]"
);
compare(actual, "This is a []");
var actual2 = st.TRANSFORM.fillout(
{a: null},
"This is a [{{a}}]"
);
compare(actual2, "This is a []");
});
it('should return blank space when an evaluatable expression is passed in and evaluates to false or null' , function(){
var actual = st.TRANSFORM.fillout(
['item1', 'item2', 'item3', null, false],
"This is an [{{this[3]}}]"
);
compare(actual, "This is an []");
var actual2 = st.TRANSFORM.fillout(
['item1', 'item2', 'item3', null, false],
"This is a [{{this[4]}}]"
);
compare(actual2, "This is a []");
});
it('should not fill in the template if a null or false primitive is explicitly passed in', function(){
var actual = st.TRANSFORM.fillout(
null,
"This is a {{this}}"
);
compare(actual, "This is a {{this}}");
var actual2 = st.TRANSFORM.fillout(
false,
"This is a {{this}}"
);
compare(actual2, "This is a {{this}}");
});
it('should return the template when an evaluatable expression is passed in but cannot be evaluated (undefined)' , function(){
var actual = st.TRANSFORM.fillout(
['item1', 'item2', 'item3'],
"This is an {{unexisting_variable[4]}}"
);
compare(actual, "This is an {{unexisting_variable[4]}}");
var actual2 = st.TRANSFORM.fillout(
['item1', 'item2', 'item3'],
"This is an {{this[4]}}"
);
compare(actual2, "This is an {{this[4]}}");
});
});
});
describe('TRANSFORM.transform (JSON.transform)', function(){
it('complex expression', function(){
var template = "{{var uri = $jason.data_uri; var b64 = uri.split(',').pop(); return b64;}}";
var data = {
"$jason": {
"data_uri": "data://abc,def"
}
};
var actual = st.TRANSFORM.transform(template, data);
var expect = "def";
compare(actual, expect);
});
it('should handle return correctly even with $root', function(){
var template = {
"{{#each items}}": {
"item": "{{var a=1; return $root.$get.name; }}"
}
}
var data = {
"$get": {
"name": "E"
},
"items": ["a", "b"]
};
var actual = st.TRANSFORM.transform(template, data);
var expect = [{
"item": "E"
}, {
"item": "E"
}];
compare(actual, expect);
});
describe('pass args as string', function(){
it("should correctly handle string only templates", function(){
var template = "{{$jason}}";
var data = JSON.stringify({
"$jason": "Val"
});
var actual = st.TRANSFORM.transform(template, data, null, true);
var expect = JSON.stringify("Val");
compare(actual, expect);
});
it("should correctly handle string only templates", function(){
var template = "{{$jason}}";
var data = JSON.stringify({
"$jason": {
"title": "Title",
"description": "Description"
}
});
var actual = st.TRANSFORM.transform(template, data, null, true);
var expect = JSON.stringify({
"title": "Title",
"description": "Description"
});
compare(actual, expect);
});
});
it("should correctly handle string only templates", function(){
var template = "{{$jason}}";
var data = {
"$jason": "Val"
};
var actual = st.TRANSFORM.transform(template, data);
var expect = "Val";
compare(actual, expect);
});
it("should correctly handle string only templates", function(){
var template = "{{$jason}}";
var data = {
"$jason": {
"title": "Title",
"description": "Description"
}
};
var actual = st.TRANSFORM.transform(template, data);
var expect = {
"title": "Title",
"description": "Description"
};
compare(actual, expect);
});
describe('closure', function(){
it('$get inside $get', function(){
var data = {"$get": {
"urls": [ "url1", "url2" ],
"item": "item"
}};
var template = {
"{{#each $get.urls}}": {
"text": "{{$root.$get.item}}"
}
};
var actual = st.TRANSFORM.transform(template, data);
var expect = [{"text": "item"}, {"text": "item"}];
compare(actual, expect);
});
it('should correctly handle closure', function(){
var template = {"sections": [{
"items": {
"{{#each $jason.items}}": {
"type": "vertical",
"components": [{
"type": "label",
"text": "{{name}}"
}, {
"type": "label",
"text": "{{$root.$get.common}}"
}]
}
}
}]};
var data = {
"$jason": {
"items": [{
"name": "John"
}, {
"name": "Kat"
}, {
"name": "Sherry"
}]
},
"$get": {
"common": "people"
}
};
var actual = st.TRANSFORM.transform(template, data);
var expect = {"sections": [{
"items": [{
"type": "vertical",
"components": [{
"type": "label",
"text": "John"
}, {
"type": "label",
"text": "people"
}]
}, {
"type": "vertical",
"components": [{
"type": "label",
"text": "Kat"
}, {
"type": "label",
"text": "people"
}]
}, {
"type": "vertical",
"components": [{
"type": "label",
"text": "Sherry"
}, {
"type": "label",
"text": "people"
}]
}]
}]};
compare(actual, expect);
});
});
describe('real world tests', function(){
it('test1', function(){
var template = {"result" : {
"head": {
"title": "{{title}}",
"description": "{{description}}"
},
"body": {
"sections": {
"{{#each posts}}": {
"header": {
"type": "label",
"text": "[App] {{name}}"
},
"cards": {
"{{#each makers}}": {
"type": "vertical",
"items": [
{
"type": "label",
"text": "{{name}}"
}, {
"type": "label",
"text": "by {{username}}"
}, {
"type": "label",
"text": "{{headline}}"
}
]
}
}
}
}
}
}
};
var data = {
"title": "Product Hunt",
"description": "Website to post products",
"posts": [{
"name": "ethan",
"makers": [{
"name": "Ethan",
"username": "gliechtenstein",
"headline": "I built Ethan, RubCam, TextCast, Jason"
}]
}, {
"name": "Robin",
"makers": [{
"name": "Justin",
"username": "jcrandall",
"headline": "co-founder, Robin"
}]
}]
};
var actual = st.TRANSFORM.transform(template, data);
var expect = {"result": {
"head": {
"title": "Product Hunt",
"description": "Website to post products"
},
"body": {
"sections": [{
"header": {
"type": "label",
"text": "[App] ethan"
},
"cards": [{
"type": "vertical",
"items": [{
"type": "label",
"text": "Ethan"
}, {
"type": "label",
"text": "by gliechtenstein"
}, {
"type": "label",
"text": "I built Ethan, RubCam, TextCast, Jason"
}]
}]
}, {
"header": {
"type": "label",
"text": "[App] Robin"
},
"cards": [{
"type": "vertical",
"items": [{
"type": "label",
"text": "Justin"
}, {
"type": "label",
"text": "by jcrandall"
}, {
"type": "label",
"text": "co-founder, Robin"
}]
}]
}]
}
}};
compare(actual, expect);
});
it('should correctly get rid of an array item if its null', function(){
var template = [
{
"cards": []
},
[{
"{{#if highlights.length>0}}": {
"header": {
"type": "label",
"text": "Permissions",
"style": {
"padding": "10",
"font": "HelveticaNeue-CondensedBold",
"color": "#000000",
"size": "11"
}
}
}
}],
{
"cards": ["a","b"]
}
];
var data = {"highlights": []};
var actual = st.TRANSFORM.transform(template, data);
compare(actual, [ { cards: [] }, { cards: [ 'a', 'b' ] } ]);
});
it("should correctly access 'this' attribute for each item in an array", function(){
var template = {
"{{#each $jason}}": {
"type": "label",
"text": "{{this}}"
}
};
var data = {"$jason": ["tom", "jerry"]};
var actual = st.TRANSFORM.transform(template, data);
var expected = [{
"type": "label",
"text": "tom"
}, {
"type": "label",
"text": "jerry"
}];
compare(actual, expected);
});
it('should correctly process multiple template expressions in one string', function(){
var template = {
"type": "label",
"text": "{{$jason.title}} and {{$jason.description}}"
};
var data = {"$jason": {"title": "This is a title", "description": "This is a description"}};
var actual = st.TRANSFORM.transform(template, data);
var expected = {
"type": "label",
"text": "This is a title and This is a description"
};
compare(actual, expected);
});
it('should be able to process complex expression as long as it doesnt evaluate to exception', function(){
var template = [
{
"{{#if $cache && ('tweets' in $cache) && $cache.tweets && Array.isArray($cache.tweets) && $cache.tweets.length > 0}}": {
"options": {
"data": {
"$jason": "{{$cache}}"
}
},
"type": "$render"
}
},
{
"{{#else}}": {
"trigger": "fetch"
}
}
];
var data = {"$cache": {}};
var actual = st.TRANSFORM.transform(template, data);
compare(actual, {"trigger": "fetch"});
});
it('should not try to parse when theres a broken template', function(){
var template = {
"$frame": "NSRect: {{0, 0}, {375, 284}}",
"inline": "true",
"url": "https://vjs.zencdn.net/v/oceans.mp4"
};
var data = {"$cache": {}};
var actual = st.TRANSFORM.transform(template, data);
compare(actual, template);
});
});
describe("Handling objects and array results", function(){
it('should return an actual array if the result is an array', function(){
var actual = st.TRANSFORM.transform( "{{a}}", {"a": ['item1','item2']});
compare(actual, ['item1', 'item2']);
});
it('standalone this where this is object', function(){
var actual = st.TRANSFORM.transform( "{{a}}", {"a": {"key": 'item1'}});
compare(actual, {"key": "item1"});
});
});
});
| {
"pile_set_name": "Github"
} |
---
layout: base
title: 'Statistics of ccomp in UD_Kurmanji'
udver: '2'
---
## Treebank Statistics: UD_Kurmanji: Relations: `ccomp`
This relation is universal.
138 nodes (1%) are attached to their parents as `ccomp`.
137 instances of `ccomp` (99%) are left-to-right (parent precedes child).
Average distance between parent and child is 5.16666666666667.
The following 15 pairs of parts of speech are connected with `ccomp`: <tt><a href="kmr-pos-VERB.html">VERB</a></tt>-<tt><a href="kmr-pos-VERB.html">VERB</a></tt> (79; 57% instances), <tt><a href="kmr-pos-VERB.html">VERB</a></tt>-<tt><a href="kmr-pos-NOUN.html">NOUN</a></tt> (19; 14% instances), <tt><a href="kmr-pos-VERB.html">VERB</a></tt>-<tt><a href="kmr-pos-AUX.html">AUX</a></tt> (13; 9% instances), <tt><a href="kmr-pos-VERB.html">VERB</a></tt>-<tt><a href="kmr-pos-ADJ.html">ADJ</a></tt> (6; 4% instances), <tt><a href="kmr-pos-NOUN.html">NOUN</a></tt>-<tt><a href="kmr-pos-VERB.html">VERB</a></tt> (4; 3% instances), <tt><a href="kmr-pos-ADJ.html">ADJ</a></tt>-<tt><a href="kmr-pos-VERB.html">VERB</a></tt> (3; 2% instances), <tt><a href="kmr-pos-AUX.html">AUX</a></tt>-<tt><a href="kmr-pos-VERB.html">VERB</a></tt> (3; 2% instances), <tt><a href="kmr-pos-AUX.html">AUX</a></tt>-<tt><a href="kmr-pos-NOUN.html">NOUN</a></tt> (2; 1% instances), <tt><a href="kmr-pos-NOUN.html">NOUN</a></tt>-<tt><a href="kmr-pos-NOUN.html">NOUN</a></tt> (2; 1% instances), <tt><a href="kmr-pos-VERB.html">VERB</a></tt>-<tt><a href="kmr-pos-PRON.html">PRON</a></tt> (2; 1% instances), <tt><a href="kmr-pos-ADJ.html">ADJ</a></tt>-<tt><a href="kmr-pos-AUX.html">AUX</a></tt> (1; 1% instances), <tt><a href="kmr-pos-AUX.html">AUX</a></tt>-<tt><a href="kmr-pos-ADJ.html">ADJ</a></tt> (1; 1% instances), <tt><a href="kmr-pos-PRON.html">PRON</a></tt>-<tt><a href="kmr-pos-AUX.html">AUX</a></tt> (1; 1% instances), <tt><a href="kmr-pos-PRON.html">PRON</a></tt>-<tt><a href="kmr-pos-VERB.html">VERB</a></tt> (1; 1% instances), <tt><a href="kmr-pos-VERB.html">VERB</a></tt>-<tt><a href="kmr-pos-PROPN.html">PROPN</a></tt> (1; 1% instances).
~~~ conllu
# visual-style 4 bgColor:blue
# visual-style 4 fgColor:white
# visual-style 1 bgColor:blue
# visual-style 1 fgColor:white
# visual-style 1 4 ccomp color:blue
1 Diviya bû divêtin VERB vblex Mood=Ind|Number=Sing|Person=3|Tense=Pqp|VerbForm=Fin 0 root _ _
2 tiştekî tişt NOUN n Case=Con|Gender=Masc|Number=Sing|PronType=Ind 4 nsubj _ _
3 mihim mihim ADJ adj Degree=Pos 2 amod _ _
4 qewimî qewimin VERB vblex Tense=Past|VerbForm=Part 1 ccomp _ _
5 biwa bûn AUX vaux Evident=Nfh|Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin 4 aux _ SpaceAfter=No
6 . . PUNCT sent _ 1 punct _ _
~~~
~~~ conllu
# visual-style 7 bgColor:blue
# visual-style 7 fgColor:white
# visual-style 3 bgColor:blue
# visual-style 3 fgColor:white
# visual-style 3 7 ccomp color:blue
1 Holmes Holmes PROPN np Case=Obl|Gender=Masc|Number=Sing 3 nsubj _ SpaceAfter=No
2 , , PUNCT cm _ 3 punct _ _
3 gote gotin VERB vblex Evident=Nfh|Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin 0 root _ _
4 min ez PRON prn Case=Obl|Gender=Fem,Masc|Number=Sing|Person=1|PronType=Prs 3 nmod:dat _ SpaceAfter=No
5 : : PUNCT sent _ 7 punct _ _
6 Çi çi DET prn PronType=Int 7 det _ _
7 mirovekî mirov NOUN n Case=Con|Gender=Masc|Number=Sing|PronType=Ind 3 ccomp _ _
8 zirav zirav NOUN n Case=Nom|Definite=Def|Gender=Masc|Number=Sing 7 nmod:poss _ _
9 e bûn AUX vbcop Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin 7 cop _ SpaceAfter=No
10 . . PUNCT sent _ 3 punct _ _
~~~
~~~ conllu
# visual-style 6 bgColor:blue
# visual-style 6 fgColor:white
# visual-style 5 bgColor:blue
# visual-style 5 fgColor:white
# visual-style 5 6 ccomp color:blue
1 Lê lê CCONJ cnjcoo _ 5 cc _ _
2 ez ez PRON prn Case=Nom|Gender=Fem,Masc|Number=Sing|Person=1|PronType=Prs 5 nsubj _ _
3 ji ji ADP pr AdpType=Prep 4 case _ _
4 kû ku PRON prn Gender=Fem,Masc|Number=Plur,Sing|PronType=Rel 5 nmod _ _
5 zanim zanîn VERB vblex Mood=Ind|Number=Sing|Person=1|Tense=Past|VerbForm=Fin 0 root _ _
6 heye hebûn AUX vbhaver Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin 5 ccomp _ _
7 ko ku SCONJ cnjsub _ 14 mark _ _
8 ji ji ADP pr AdpType=Prep 10 case _ _
9 ber ber ADP pr AdpType=Prep 8 fixed _ _
10 ba ba NOUN n Case=Nom|Definite=Def|Gender=Masc|Number=Sing 14 nmod _ _
11 û û CCONJ cnjcoo _ 12 cc _ _
12 firtinê firtina NOUN n Case=Obl|Definite=Def|Gender=Fem|Number=Sing 10 conj _ _
13 ez ez PRON prn Case=Nom|Gender=Fem,Masc|Number=Sing|Person=1|PronType=Prs 14 nsubj _ _
14 şaş şaş ADJ adj Degree=Pos 6 ccomp _ _
15 im bûn AUX vbcop Mood=Ind|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin 14 cop _ SpaceAfter=No
16 . . PUNCT sent _ 5 punct _ _
~~~
| {
"pile_set_name": "Github"
} |
/***************************************************************************/
/* */
/* gxvalid.h */
/* */
/* TrueTypeGX/AAT table validation (specification only). */
/* */
/* Copyright 2005-2018 by */
/* suzuki toshiya, Masatake YAMATO, Red Hat K.K., */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
/***************************************************************************/
/* */
/* gxvalid is derived from both gxlayout module and otvalid module. */
/* Development of gxlayout is supported by the Information-technology */
/* Promotion Agency(IPA), Japan. */
/* */
/***************************************************************************/
#ifndef GXVALID_H_
#define GXVALID_H_
#include <ft2build.h>
#include FT_FREETYPE_H
#include "gxverror.h" /* must come before FT_INTERNAL_VALIDATE_H */
#include FT_INTERNAL_VALIDATE_H
#include FT_INTERNAL_STREAM_H
FT_BEGIN_HEADER
FT_LOCAL( void )
gxv_feat_validate( FT_Bytes table,
FT_Face face,
FT_Validator valid );
FT_LOCAL( void )
gxv_bsln_validate( FT_Bytes table,
FT_Face face,
FT_Validator valid );
FT_LOCAL( void )
gxv_trak_validate( FT_Bytes table,
FT_Face face,
FT_Validator valid );
FT_LOCAL( void )
gxv_just_validate( FT_Bytes table,
FT_Face face,
FT_Validator valid );
FT_LOCAL( void )
gxv_mort_validate( FT_Bytes table,
FT_Face face,
FT_Validator valid );
FT_LOCAL( void )
gxv_morx_validate( FT_Bytes table,
FT_Face face,
FT_Validator valid );
FT_LOCAL( void )
gxv_kern_validate( FT_Bytes table,
FT_Face face,
FT_Validator valid );
FT_LOCAL( void )
gxv_kern_validate_classic( FT_Bytes table,
FT_Face face,
FT_Int dialect_flags,
FT_Validator valid );
FT_LOCAL( void )
gxv_opbd_validate( FT_Bytes table,
FT_Face face,
FT_Validator valid );
FT_LOCAL( void )
gxv_prop_validate( FT_Bytes table,
FT_Face face,
FT_Validator valid );
FT_LOCAL( void )
gxv_lcar_validate( FT_Bytes table,
FT_Face face,
FT_Validator valid );
FT_END_HEADER
#endif /* GXVALID_H_ */
/* END */
| {
"pile_set_name": "Github"
} |
{
"config": {"null_handling": "null_string_as_null"},
"columns": [
{"name": "id", "type": "int"},
{"name": "person_id", "type": "int"},
{"name": "name", "type": "string"},
{"name": "imdb_index", "type": "string", "nullable": true},
{"name": "name_pcode_cf", "type": "string", "nullable": true},
{"name": "name_pcode_nf", "type": "string", "nullable": true},
{"name": "surname_pcode", "type": "string", "nullable": true},
{"name": "md5sum", "type": "string", "nullable": true}
]
}
| {
"pile_set_name": "Github"
} |
package wix
import (
"encoding/xml"
"fmt"
"io"
"strings"
"github.com/pkg/errors"
"github.com/serenize/snaker"
)
// http://wixtoolset.org/documentation/manual/v3/xsd/wix/serviceinstall.html
// http://wixtoolset.org/documentation/manual/v3/xsd/wix/servicecontrol.html
// https://helgeklein.com/blog/2014/09/real-world-example-wix-msi-application-installer/
type YesNoType string
const (
Yes YesNoType = "yes"
No = "no"
)
type ErrorControlType string
const (
ErrorControlIgnore ErrorControlType = "ignore"
ErrorControlNormal = "normal"
ErrorControlCritical = "critical"
)
type StartType string
const (
StartAuto StartType = "auto"
StartDemand = "demand"
StartDisabled = "disabled"
StartBoot = "boot"
StartSystem = "system"
StartNone = ""
)
type InstallUninstallType string
const (
InstallUninstallInstall InstallUninstallType = "install"
InstallUninstallUninstall = "uninstall"
InstallUninstallBoth = "both"
)
// ServiceInstall implements http://wixtoolset.org/documentation/manual/v3/xsd/wix/serviceinstall.html
type ServiceInstall struct {
Account string `xml:",attr,omitempty"`
Arguments string `xml:",attr,omitempty"`
Description string `xml:",attr,omitempty"`
DisplayName string `xml:",attr,omitempty"`
EraseDescription bool `xml:",attr,omitempty"`
ErrorControl ErrorControlType `xml:",attr,omitempty"`
Id string `xml:",attr,omitempty"`
Interactive YesNoType `xml:",attr,omitempty"`
LoadOrderGroup string `xml:",attr,omitempty"`
Name string `xml:",attr,omitempty"`
Password string `xml:",attr,omitempty"`
Start StartType `xml:",attr,omitempty"`
Type string `xml:",attr,omitempty"`
Vital YesNoType `xml:",attr,omitempty"` // The overall install should fail if this service fails to install
UtilServiceConfig *UtilServiceConfig `xml:",omitempty"`
ServiceConfig *ServiceConfig `xml:",omitempty"`
}
// ServiceControl implements
// http://wixtoolset.org/documentation/manual/v3/xsd/wix/servicecontrol.html
type ServiceControl struct {
Name string `xml:",attr,omitempty"`
Id string `xml:",attr,omitempty"`
Remove InstallUninstallType `xml:",attr,omitempty"`
Start InstallUninstallType `xml:",attr,omitempty"`
Stop InstallUninstallType `xml:",attr,omitempty"`
Wait YesNoType `xml:",attr,omitempty"`
}
// ServiceConfig implements
// https://wixtoolset.org/documentation/manual/v3/xsd/wix/serviceconfig.html
// This is used needed to set DelayedAutoStart
type ServiceConfig struct {
// TODO: this should need a namespace, and yet. See https://github.com/golang/go/issues/36813
XMLName xml.Name `xml:"http://schemas.microsoft.com/wix/2006/wi ServiceConfig"`
DelayedAutoStart YesNoType `xml:",attr,omitempty"`
OnInstall YesNoType `xml:",attr,omitempty"`
OnReinstall YesNoType `xml:",attr,omitempty"`
OnUninstall YesNoType `xml:",attr,omitempty"`
}
// UtilServiceConfig implements
// http://wixtoolset.org/documentation/manual/v3/xsd/util/serviceconfig.html
// This is used to set FailureActions. There are some
// limitations. Notably, reset period is in days here, though the
// underlying `sc.exe` command supports seconds. (See
// https://github.com/wixtoolset/issues/issues/5963)
//
// Docs are a bit confusing. This schema is supported, and should
// work. The non-util ServiceConfig generates unsupported CNDL1150
// errors.
type UtilServiceConfig struct {
XMLName xml.Name `xml:"http://schemas.microsoft.com/wix/UtilExtension ServiceConfig"`
FirstFailureActionType string `xml:",attr,omitempty"`
SecondFailureActionType string `xml:",attr,omitempty"`
ThirdFailureActionType string `xml:",attr,omitempty"`
RestartServiceDelayInSeconds int `xml:",attr,omitempty"`
ResetPeriodInDays int `xml:",attr,omitempty"`
}
// Service represents a wix service. It provides an interface to both
// ServiceInstall and ServiceControl.
type Service struct {
matchString string
count int // number of times we've seen this. Used for error handling
expectedCount int
serviceInstall *ServiceInstall
serviceControl *ServiceControl
}
type ServiceOpt func(*Service)
func ServiceName(name string) ServiceOpt {
return func(s *Service) {
s.serviceControl.Id = cleanServiceName(name)
s.serviceControl.Name = cleanServiceName(name)
s.serviceInstall.Id = cleanServiceName(name)
s.serviceInstall.Name = cleanServiceName(name)
}
}
func ServiceDescription(desc string) ServiceOpt {
return func(s *Service) {
s.serviceInstall.Description = desc
}
}
func WithDelayedStart() ServiceOpt {
return func(s *Service) {
s.serviceInstall.ServiceConfig.DelayedAutoStart = Yes
}
}
func WithDisabledService() ServiceOpt {
return func(s *Service) {
s.serviceInstall.Start = StartDisabled
// If this is not explicitly set to none, the installer hangs trying to start the
// disabled service.
s.serviceControl.Start = StartNone
}
}
// ServiceArgs takes an array of args, wraps them in spaces, then
// joins them into a string. Handling spaces in the arguments is a bit
// gnarly. Some parts of windows use ` as an escape character, but
// that doesn't seem to work here. However, we can use double quotes
// to wrap the whole string. But, in xml quotes are _always_
// transmitted as html entities -- " or ". Luckily, wix seems
// fine with that. It converts them back to double quotes when it
// makes the service
func ServiceArgs(args []string) ServiceOpt {
return func(s *Service) {
quotedArgs := make([]string, len(args))
for i, arg := range args {
if strings.ContainsAny(arg, " ") {
quotedArgs[i] = fmt.Sprintf(`"%s"`, arg)
} else {
quotedArgs[i] = arg
}
}
s.serviceInstall.Arguments = strings.Join(quotedArgs, " ")
}
}
// New returns a service
func NewService(matchString string, opts ...ServiceOpt) *Service {
// Set some defaults. It's not clear we can reset in under a
// day. See https://github.com/wixtoolset/issues/issues/5963
utilServiceConfig := &UtilServiceConfig{
FirstFailureActionType: "restart",
SecondFailureActionType: "restart",
ThirdFailureActionType: "restart",
ResetPeriodInDays: 1,
RestartServiceDelayInSeconds: 5,
}
serviceConfig := &ServiceConfig{
OnInstall: Yes,
OnReinstall: Yes,
}
// If a service name is not specified, replace the .exe with a svc,
// and CamelCase it. (eg: daemon.exe becomes DaemonSvc). It is
// probably better to specific a ServiceName, but this might be an
// okay default.
defaultName := cleanServiceName(strings.TrimSuffix(matchString, ".exe") + ".svc")
si := &ServiceInstall{
Name: defaultName,
Id: defaultName,
Account: `[SERVICEACCOUNT]`, // Wix resolves this to `LocalSystem`
Start: StartAuto,
Type: "ownProcess",
ErrorControl: ErrorControlNormal,
Vital: Yes,
UtilServiceConfig: utilServiceConfig,
ServiceConfig: serviceConfig,
}
sc := &ServiceControl{
Name: defaultName,
Id: defaultName,
Stop: InstallUninstallBoth,
Start: InstallUninstallInstall,
Remove: InstallUninstallUninstall,
Wait: No,
}
s := &Service{
matchString: matchString,
expectedCount: 1,
count: 0,
serviceInstall: si,
serviceControl: sc,
}
for _, opt := range opts {
opt(s)
}
return s
}
// Match returns a bool if there's a match, and throws an error if we
// have too many matches. This is to ensure the configured regex isn't
// broader than expected.
func (s *Service) Match(line string) (bool, error) {
isMatch := strings.Contains(line, s.matchString)
if isMatch {
s.count += 1
}
if s.count > s.expectedCount {
return isMatch, errors.Errorf("Too many matches. Have %d, expected %d. (on %s)", s.count, s.expectedCount, s.matchString)
}
return isMatch, nil
}
// Xml converts a Service resource to Xml suitable for embedding
func (s *Service) Xml(w io.Writer) error {
enc := xml.NewEncoder(w)
enc.Indent(" ", " ")
if err := enc.Encode(s.serviceInstall); err != nil {
return err
}
if err := enc.Encode(s.serviceControl); err != nil {
return err
}
if _, err := io.WriteString(w, "\n"); err != nil {
return err
}
return nil
}
// cleanServiceName removes characters windows doesn't like in
// services names, and converts everything to camel case. Right now,
// it only removes likely bad characters. It is not as complete as an
// allowlist.
func cleanServiceName(in string) string {
r := strings.NewReplacer(
"-", "_",
" ", "_",
".", "_",
"/", "_",
"\\", "_",
)
return snaker.SnakeToCamel(r.Replace(in))
}
| {
"pile_set_name": "Github"
} |
/******************************************************************************
* Copyright (c) 2004, 2008 IBM Corporation
* All rights reserved.
* This program and the accompanying materials
* are made available under the terms of the BSD License
* which accompanies this distribution, and is available at
* http://www.opensource.org/licenses/bsd-license.php
*
* Contributors:
* IBM Corporation - initial implementation
*****************************************************************************/
#include <string.h>
#include <ctype.h>
int
strcasecmp(const char *s1, const char *s2)
{
while (*s1 != 0 && *s2 != 0) {
if (toupper(*s1) != toupper(*s2))
break;
++s1;
++s2;
}
return *s1 - *s2;
}
| {
"pile_set_name": "Github"
} |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>gae</artifactId>
<version>2.0.3-SNAPSHOT</version>
</parent>
<artifactId>fr.opensagres.xdocreport.itext.extension-gae</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>unpack</id>
<phase>generate-sources</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.itext.extension</artifactId>
<version>${project.version}</version>
<type>jar</type>
<classifier>sources</classifier>
<outputDirectory>${unpackDir}</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> | {
"pile_set_name": "Github"
} |
echo hello-a >$3
| {
"pile_set_name": "Github"
} |
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera 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.
*****************************************************************************/
/*****************************************************************************
sc_fxcast_switch.cpp -
Original Author: Martin Janssen, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date: Gene Bushuyev, Synopsys, Inc.
Description of Modification: - fix explicit instantiation syntax.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
// $Log: sc_fxcast_switch.cpp,v $
// Revision 1.1.1.1 2006/12/15 20:20:04 acg
// SystemC 2.3
//
// Revision 1.3 2006/01/13 18:53:57 acg
// Andy Goodrich: added $Log command so that CVS comments are reproduced in
// the source.
//
#include "sysc/datatypes/fx/sc_fxcast_switch.h"
namespace sc_dt
{
// ----------------------------------------------------------------------------
// CLASS : sc_fxcast_switch
//
// Fixed-point cast switch class.
// ----------------------------------------------------------------------------
const std::string
sc_fxcast_switch::to_string() const
{
return sc_dt::to_string( m_sw );
}
void
sc_fxcast_switch::print( ::std::ostream& os ) const
{
os << sc_dt::to_string( m_sw );
}
void
sc_fxcast_switch::dump( ::std::ostream& os ) const
{
os << "sc_fxcast_switch" << ::std::endl;
os << "(" << ::std::endl;
os << "sw = " << sc_dt::to_string( m_sw ) << ::std::endl;
os << ")" << ::std::endl;
}
} // namespace sc_dt
// Taf!
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<_PropertySheetDisplayName>Libsodium Import Settings</_PropertySheetDisplayName>
</PropertyGroup>
<!-- User Interface -->
<ItemGroup Label="BuildOptionsExtension">
<PropertyPageSchema Include="$(MSBuildThisFileDirectory)libsodium.import.xml" />
</ItemGroup>
<!-- Linkage -->
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(ProjectDir)..\..\..\..\..\libsodium\src\libsodium\include;$(ProjectDir)..\..\..\..\..\libsodium\src\libsodium\include\sodium\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions Condition="'$(Linkage-libsodium)' == 'static' Or '$(Linkage-libsodium)' == 'ltcg'">SODIUM_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<AdditionalDependencies Condition="'$(Linkage-libsodium)' != ''">advapi32.lib;libsodium.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories Condition="$(Configuration.IndexOf('Debug')) != -1">$(ProjectDir)..\..\..\..\..\libsodium\bin\$(PlatformName)\Debug\$(PlatformToolset)\$(Linkage-libsodium)\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories Condition="$(Configuration.IndexOf('Release')) != -1">$(ProjectDir)..\..\..\..\..\libsodium\bin\$(PlatformName)\Release\$(PlatformToolset)\$(Linkage-libsodium)\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<!-- Copy -->
<Target Name="Linkage-libsodium-dynamic" AfterTargets="AfterBuild" Condition="'$(Linkage-libsodium)' == 'dynamic'">
<Copy Condition="$(Configuration.IndexOf('Debug')) != -1"
SourceFiles="$(ProjectDir)..\..\..\..\..\libsodium\bin\$(PlatformName)\Debug\$(PlatformToolset)\dynamic\libsodium.dll"
DestinationFiles="$(TargetDir)libsodium.dll"
SkipUnchangedFiles="true" />
<Copy Condition="$(Configuration.IndexOf('Debug')) != -1"
SourceFiles="$(ProjectDir)..\..\..\..\..\libsodium\bin\$(PlatformName)\Debug\$(PlatformToolset)\dynamic\libsodium.pdb"
DestinationFiles="$(TargetDir)libsodium.pdb"
SkipUnchangedFiles="true" />
<Copy Condition="$(Configuration.IndexOf('Release')) != -1"
SourceFiles="$(ProjectDir)..\..\..\..\..\libsodium\bin\$(PlatformName)\Release\$(PlatformToolset)\dynamic\libsodium.dll"
DestinationFiles="$(TargetDir)libsodium.dll"
SkipUnchangedFiles="true" />
</Target>
<!-- Messages -->
<Target Name="libsodium-info" BeforeTargets="AfterBuild" Condition="'$(Linkage-libsodium)' == 'dynamic'">
<Message Text="Copying libsodium.dll -> $(TargetDir)libsodium.dll" Importance="high"/>
<Message Text="Copying libsodium.pdb -> $(TargetDir)libsodium.pdb" Importance="high" Condition="$(Configuration.IndexOf('Debug')) != -1" />
</Target>
</Project> | {
"pile_set_name": "Github"
} |
var baseTimes = require('./_baseTimes'),
castFunction = require('./_castFunction'),
toInteger = require('./toInteger');
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Invokes the iteratee `n` times, returning an array of the results of
* each invocation. The iteratee is invoked with one argument; (index).
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of results.
* @example
*
* _.times(3, String);
* // => ['0', '1', '2']
*
* _.times(4, _.constant(0));
* // => [0, 0, 0, 0]
*/
function times(n, iteratee) {
n = toInteger(n);
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = MAX_ARRAY_LENGTH,
length = nativeMin(n, MAX_ARRAY_LENGTH);
iteratee = castFunction(iteratee);
n -= MAX_ARRAY_LENGTH;
var result = baseTimes(length, iteratee);
while (++index < n) {
iteratee(index);
}
return result;
}
module.exports = times;
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of web2py Web Framework (Copyrighted, 2007-2014).
Developed by Massimo Di Pierro <[email protected]>.
License: LGPL v3
Login will be done via Web2py's CAS application, instead of web2py's
login form.
Include in your model (eg db.py)::
auth.define_tables(username=True)
from gluon.contrib.login_methods.saml2_auth import Saml2Auth
import os
auth.settings.login_form=Saml2Auth(
config_file = os.path.join(request.folder,'private','sp_conf'),
maps=dict(
username=lambda v: v['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn'][0],
email=lambda v: v['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn'][0],
user_id=lambda v: v['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn'][0]))
you must have private/sp_conf.py, the pysaml2 sp configuration file. For example:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from saml2 import BINDING_HTTP_POST, BINDING_HTTP_REDIRECT
import os.path
import requests
import tempfile
BASEDIR = os.path.abspath(os.path.dirname(__file__))
# Web2py SP url and application name
HOST = 'http://127.0.0.1:8000'
APP = 'sp'
# To load the IDP metadata...
IDP_METADATA = 'http://127.0.0.1:8088/metadata'
def full_path(local_file):
return os.path.join(BASEDIR, local_file)
CONFIG = {
# your entity id, usually your subdomain plus the url to the metadata view.
'entityid': '%s/%s/default/metadata' % (HOST, APP),
'service': {
'sp' : {
'name': 'MYSP',
'endpoints': {
'assertion_consumer_service': [
('%s/%s/default/user/login' % (HOST, APP), BINDING_HTTP_REDIRECT),
('%s/%s/default/user/login' % (HOST, APP), BINDING_HTTP_POST),
],
},
},
},
# Your private and public key.
'key_file': full_path('pki/mykey.pem'),
'cert_file': full_path('pki/mycert.pem'),
# where the remote metadata is stored
'metadata': {
"remote": [{
"url": IDP_METADATA,
"cert":full_path('pki/mycert.pem')
}]
},
}
"""
from saml2 import BINDING_HTTP_REDIRECT, BINDING_HTTP_POST
from saml2.client import Saml2Client
from gluon.utils import web2py_uuid
from gluon import current, redirect, URL
import os, types
def obj2dict(obj, processed=None):
"""
converts any object into a dict, recursively
"""
processed = processed if not processed is None else set()
if obj is None:
return None
if isinstance(obj,(int,long,str,unicode,float,bool)):
return obj
if id(obj) in processed:
return '<reference>'
processed.add(id(obj))
if isinstance(obj,(list,tuple)):
return [obj2dict(item,processed) for item in obj]
if not isinstance(obj, dict) and hasattr(obj,'__dict__'):
obj = obj.__dict__
else:
return repr(obj)
return dict((key,obj2dict(value,processed)) for key,value in obj.items()
if not key.startswith('_') and
not type(value) in (types.FunctionType,
types.LambdaType,
types.BuiltinFunctionType,
types.BuiltinMethodType))
def saml2_handler(session, request, config_filename = None, entityid = None):
config_filename = config_filename or os.path.join(request.folder,'private','sp_conf')
client = Saml2Client(config_file = config_filename)
if not entityid:
idps = client.metadata.with_descriptor("idpsso")
entityid = list(idps.keys())[0]
bindings = [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST]
binding, destination = client.pick_binding(
"single_sign_on_service", bindings, "idpsso", entity_id=entityid)
if request.env.request_method == 'GET':
binding = BINDING_HTTP_REDIRECT
elif request.env.request_method == 'POST':
binding = BINDING_HTTP_POST
if not request.vars.SAMLResponse:
req_id, req = client.create_authn_request(destination, binding=BINDING_HTTP_POST)
relay_state = web2py_uuid().replace('-','')
session.saml_outstanding_queries = {req_id: request.url}
session.saml_req_id = req_id
http_args = client.apply_binding(binding, str(req), destination,
relay_state=relay_state)
return {'url':dict(http_args["headers"])['Location']}
else:
relay_state = request.vars.RelayState
req_id = session.saml_req_id
unquoted_response = request.vars.SAMLResponse
res = {}
try:
data = client.parse_authn_request_response(
unquoted_response, binding, session.saml_outstanding_queries)
res['response'] = data if data else {}
except Exception as e:
import traceback
res['error'] = traceback.format_exc()
return res
class Saml2Auth(object):
def __init__(self, config_file=None, maps=dict(
username=lambda v:v['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn'][0],
email=lambda v:v['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn'][0],
user_id=lambda v:v['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn'][0],
), logout_url=None, change_password_url=None, entityid=None):
self.config_file = config_file
self.maps = maps
# URL for redirecting users to when they sign out
self.saml_logout_url = logout_url
# URL to let users change their password in the IDP system
self.saml_change_password_url = change_password_url
# URL to specify an IDP if using federation metadata or an MDQ
self.entityid = entityid
def login_url(self, next="/"):
d = saml2_handler(current.session, current.request, entityid=self.entityid)
if 'url' in d:
redirect(d['url'])
elif 'error' in d:
current.session.flash = d['error']
redirect(URL('default','index'))
elif 'response' in d:
# a['assertions'][0]['attribute_statement'][0]['attribute']
# is list of
# {'name': 'http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname', 'name_format': None, 'text': None, 'friendly_name': None, 'attribute_value': [{'text': 'CAA\\dev-mdp', 'extension_attributes': "{'{http://www.w3.org/2001/XMLSchema-instance}type': 'xs:string'}", 'extension_elements': []}], 'extension_elements': [], 'extension_attributes': '{}'}
try:
attributes = d['response'].assertions[0].attribute_statement[0].attribute
except:
attributes = d['response'].assertion.attribute_statement[0].attribute
current.session.saml2_info = dict(
(a.name, [i.text for i in a.attribute_value]) for a in attributes)
return next
def logout_url(self, next="/"):
current.session.saml2_info = None
current.session.auth = None
self._SAML_logout()
return next
def change_password_url(self, next="/"):
self._SAML_change_password()
return next
def get_user(self):
user = current.session.saml2_info
if user:
d = {'source': 'web2py saml2'}
for key in self.maps:
d[key] = self.maps[key](user)
return d
return None
def _SAML_logout(self):
"""
exposed SAML.logout()
redirects to the SAML logout page
"""
redirect(self.saml_logout_url)
def _SAML_change_password(self):
redirect(self.saml_change_password_url)
| {
"pile_set_name": "Github"
} |
/*
Styles for older IE versions (previous to IE9).
*/
body {
background-color: #e6e6e6;
}
body.custom-background-empty {
background-color: #fff;
}
body.custom-background-empty .site,
body.custom-background-white .site {
box-shadow: none;
margin-bottom: 0;
margin-top: 0;
padding: 0;
}
.assistive-text,
.site .screen-reader-text {
clip: rect(1px 1px 1px 1px); /* IE7 */
}
.full-width .site-content {
float: none;
width: 100%;
}
img.size-full,
img.size-large,
img.header-image,
img.wp-post-image,
img[class*="align"],
img[class*="wp-image-"],
img[class*="attachment-"] {
width: auto; /* Prevent stretching of full-size and large-size images with height and width attributes in IE8 */
}
.author-avatar {
float: left;
margin-top: 8px;
margin-top: 0.571428571rem;
}
.author-description {
float: right;
width: 80%;
}
.site {
box-shadow: 0 2px 6px rgba(100, 100, 100, 0.3);
margin: 48px auto;
max-width: 960px;
overflow: hidden;
padding: 0 40px;
}
.site-content {
float: left;
width: 65.104166667%;
}
body.template-front-page .site-content,
body.single-attachment .site-content,
body.full-width .site-content {
width: 100%;
}
.widget-area {
float: right;
width: 26.041666667%;
}
.site-header h1,
.site-header h2 {
text-align: left;
}
.site-header h1 {
font-size: 26px;
line-height: 1.846153846;
}
.main-navigation ul.nav-menu,
.main-navigation div.nav-menu > ul {
border-bottom: 1px solid #ededed;
border-top: 1px solid #ededed;
display: inline-block !important;
text-align: left;
width: 100%;
}
.main-navigation ul {
margin: 0;
text-indent: 0;
}
.main-navigation li a,
.main-navigation li {
display: inline-block;
text-decoration: none;
}
.ie7 .main-navigation li a,
.ie7 .main-navigation li {
display: inline;
}
.main-navigation li a {
border-bottom: 0;
color: #6a6a6a;
line-height: 3.692307692;
text-transform: uppercase;
}
.main-navigation li a:hover {
color: #000;
}
.main-navigation li {
margin: 0 40px 0 0;
position: relative;
}
.main-navigation li ul {
display: none;
margin: 0;
padding: 0;
position: absolute;
top: 100%;
z-index: 1;
}
.ie7 .main-navigation li ul {
left: 0;
}
.main-navigation li ul ul,
.ie7 .main-navigation li ul ul {
top: 0;
left: 100%;
}
.main-navigation ul li:hover > ul {
border-left: 0;
display: block;
}
.main-navigation li ul li a {
background: #efefef;
border-bottom: 1px solid #ededed;
display: block;
font-size: 11px;
line-height: 2.181818182;
padding: 8px 10px;
width: 180px;
}
.main-navigation li ul li a:hover {
background: #e3e3e3;
color: #444;
}
.main-navigation .current-menu-item > a,
.main-navigation .current-menu-ancestor > a,
.main-navigation .current_page_item > a,
.main-navigation .current_page_ancestor > a {
color: #636363;
font-weight: bold;
}
.menu-toggle {
display: none;
}
.entry-header .entry-title {
font-size: 22px;
}
#respond form input[type="text"] {
width: 46.333333333%;
}
#respond form textarea.blog-textarea {
width: 79.666666667%;
}
.template-front-page .site-content,
.template-front-page article {
overflow: hidden;
}
.template-front-page.has-post-thumbnail article {
float: left;
width: 47.916666667%;
}
.entry-page-image {
float: right;
margin-bottom: 0;
width: 47.916666667%;
}
.template-front-page .widget-area .widget,
.template-front-page.two-sidebars .widget-area .front-widgets {
float: left;
margin-bottom: 24px;
width: 51.875%;
}
.template-front-page .widget-area .widget:nth-child(odd) {
clear: right;
}
.template-front-page .widget-area .widget:nth-child(even),
.template-front-page.two-sidebars .widget-area .front-widgets + .front-widgets {
float: right;
margin: 0 0 24px;
width: 39.0625%;
}
.template-front-page.two-sidebars .widget,
.template-front-page.two-sidebars .widget:nth-child(even) {
float: none;
width: auto;
}
/* =RTL overrides for IE7 and IE8
-------------------------------------------------------------- */
.rtl .site-header h1,
.rtl .site-header h2 {
text-align: right;
}
.rtl .widget-area,
.rtl .author-description {
float: left;
}
.rtl .author-avatar,
.rtl .site-content {
float: right;
}
.rtl .main-navigation ul.nav-menu,
.rtl .main-navigation div.nav-menu > ul {
text-align: right;
}
.rtl .main-navigation ul li ul li,
.rtl .main-navigation ul li ul li ul li {
margin-left: 40px;
margin-right: auto;
}
.rtl .main-navigation li ul ul {
position: absolute;
bottom: 0;
right: 100%;
z-index: 1;
}
.ie7 .rtl .main-navigation li ul ul {
position: absolute;
bottom: 0;
right: 100%;
z-index: 1;
}
.ie7 .rtl .main-navigation ul li {
z-index: 99;
}
.ie7 .rtl .main-navigation li ul {
position: absolute;
bottom: 100%;
right: 0;
z-index: 1;
}
.ie7 .rtl .main-navigation li {
margin-right: auto;
margin-left: 40px;
}
.ie7 .rtl .main-navigation li ul ul ul {
position: relative;
z-index: 1;
} | {
"pile_set_name": "Github"
} |
from __future__ import absolute_import
from tornado import web
from ..views import BaseHandler
from ..models import WorkersModel, WorkerModel
class WorkersView(BaseHandler):
@web.authenticated
def get(self):
app = self.application
workers = WorkersModel.get_latest(app).workers
broker = app.celery_app.connection().as_uri()
self.render("workers.html", workers=workers, broker=broker)
class WorkerView(BaseHandler):
@web.authenticated
def get(self, workername):
app = self.application
worker = WorkerModel.get_worker(app, workername)
if worker is None:
raise web.HTTPError(404, "Unknown worker '%s'" % workername)
self.render("worker.html", worker=worker)
| {
"pile_set_name": "Github"
} |
<script>
import Button from "components/Button";
import Icon from "components/Icon";
import Code from "docs/Code.svelte";
import PropsTable from "docs/PropsTable.svelte";
import buttons from "examples/buttons.txt";
</script>
<blockquote
class="pl-8 mt-2 mb-10 border-l-8 border-primary-300 text-lg"
cite="https://material.io/components/buttons/">
<p>Buttons allow users to take actions, and make choices, with a single tap.</p>
</blockquote>
<h6 class="mb-3 mt-6">Basic</h6>
<div class="py-2">
<Button>Button</Button>
</div>
<h6 class="mb-3 mt-6">Light</h6>
<div class="py-2">
<Button
light
>Button</Button>
</div>
<h6 class="mb-3 mt-6">Dark</h6>
<div class="py-2">
<Button dark>Button</Button>
</div>
<h6 class="mb-3 mt-6">Block</h6>
<div class="py-2">
<Button color="alert" dark block>Button</Button>
</div>
<PropsTable
data={[
{ prop: "value", description: "Bound boolean value", type: "Boolean", default: "false" },
{ prop: "color", description: "Color variant, accepts any of the main colors described in Tailwind config", type: "String", default: "primary" },
{ prop: "outlined", description: "Outlined variant", type: "Boolean", default: "false" },
{ prop: "text", description: "Text button variant (transparent background)", type: "Boolean", default: "false" },
{ prop: "block", description: "Full block width button", type: "Boolean", default: "false" },
{ prop: "disabled", description: "Disabled state", type: "Boolean", default: "false" },
{ prop: "icon", description: "Icon button variant", type: "String", default: "null" },
{ prop: "small", description: "Smaller size", type: "Boolean", default: "false" },
{ prop: "light", description: "Lighter variant", type: "Boolean", default: "false" },
{ prop: "dark", description: "Darker variant", type: "Boolean", default: "false" },
{ prop: "flat", description: "Flat variant", type: "Boolean", default: "false" },
{ prop: "iconClass", description: "List of classes to pass down to icon", type: "String", default: "empty string" },
{ prop: "href", description: "Link URL", type: "String", default: "null" },
{ prop: "add", description: "List of classes to add to the component", type: "String", default: "empty string" },
{ prop: "remove", description: "List of classes to remove from the component", type: "String", default: "empty string" },
{ prop: "replace", description: "List of classes to replace in the component", type: "Object", default: "{}" },
]}
/>
<h6 class="mb-3 mt-6">Outlined</h6>
<div class="py-2">
<Button color="secondary" light block outlined>Button</Button>
</div>
<h6 class="mb-3 mt-6">As anchor</h6>
<div class="py-2">
<Button
color="secondary"
light
block
outlined
>Button</Button>
</div>
<h6 class="mb-3 mt-6">Text</h6>
<div class="py-2">
<Button text>Button</Button>
</div>
<h6 class="mb-3 mt-6">Disabled</h6>
<div class="py-2">
<Button block disabled>Button</Button>
</div>
<h6 class="mb-3 mt-6">FAB <a class="a" href="https://material.io/components/buttons-floating-action-button/">(Floating action button)</a></h6>
<div class="py-2">
<Button color="alert" icon="change_history" />
</div>
<h6 class="mb-3 mt-6">Fab flat</h6>
<div class="py-2">
<Button color="error" icon="change_history" text light flat />
</div>
<Code code={buttons} /> | {
"pile_set_name": "Github"
} |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//build/config/android/config.gni")
import("//build/config/arm.gni")
import("//build/config/ui.gni")
import("//media/media_options.gni")
# These should compile on non-android platforms too.
source_set("anywhere") {
sources = [
"media_codec_bridge.cc",
"media_codec_bridge.h",
"media_codec_direction.h",
"media_codec_loop.cc",
"media_codec_loop.h",
]
configs += [
"//media:media_config",
"//media:media_implementation",
]
deps = [
"//media:media_features",
"//media:shared_memory_support",
"//ui/gl",
"//url",
]
}
# These should compile on non-android platforms too.
source_set("anywhere_unit_tests") {
testonly = true
sources = [
"media_codec_loop_unittest.cc",
"mock_media_codec_bridge.cc",
"mock_media_codec_bridge.h",
]
configs += [
"//media:media_config",
"//media:media_implementation",
]
deps = [
":anywhere",
"//media/base:test_support",
"//testing/gmock",
"//testing/gtest",
]
}
if (is_android) {
import("//build/config/android/rules.gni")
source_set("android") {
sources = [
"android_cdm_factory.cc",
"android_cdm_factory.h",
"media_client_android.cc",
"media_client_android.h",
"media_codec_util.cc",
"media_codec_util.h",
"media_drm_bridge.cc",
"media_drm_bridge.h",
"media_drm_bridge_cdm_context.cc",
"media_drm_bridge_cdm_context.h",
"media_drm_bridge_delegate.cc",
"media_drm_bridge_delegate.h",
"media_jni_registrar.cc",
"media_jni_registrar.h",
"media_player_android.cc",
"media_player_android.h",
"media_player_bridge.cc",
"media_player_bridge.h",
"media_player_listener.cc",
"media_player_listener.h",
"media_player_manager.h",
"media_resource_getter.cc",
"media_resource_getter.h",
"media_server_crash_listener.cc",
"media_server_crash_listener.h",
"media_service_throttler.cc",
"media_service_throttler.h",
"media_url_interceptor.h",
"sdk_media_codec_bridge.cc",
"sdk_media_codec_bridge.h",
"stream_texture_wrapper.h",
]
configs += [
"//media:media_config",
"//media:media_implementation",
]
deps = [
":media_jni_headers",
"//media:media_features",
"//media:shared_memory_support",
"//third_party/widevine/cdm:headers",
"//ui/gl",
"//url",
]
public_deps = [
":anywhere",
]
}
source_set("unit_tests") {
testonly = true
sources = [
"media_drm_bridge_unittest.cc",
"media_player_bridge_unittest.cc",
"media_service_throttler_unittest.cc",
"sdk_media_codec_bridge_unittest.cc",
]
deps = [
":android",
"//media/base:test_support",
"//testing/gmock",
"//testing/gtest",
"//third_party/widevine/cdm:headers",
]
configs += [ "//media:media_config" ]
}
generate_jni("media_jni_headers") {
sources = [
"java/src/org/chromium/media/AudioManagerAndroid.java",
"java/src/org/chromium/media/AudioRecordInput.java",
"java/src/org/chromium/media/MediaCodecBridge.java",
"java/src/org/chromium/media/MediaCodecUtil.java",
"java/src/org/chromium/media/MediaDrmBridge.java",
"java/src/org/chromium/media/MediaPlayerBridge.java",
"java/src/org/chromium/media/MediaPlayerListener.java",
"java/src/org/chromium/media/MediaServerCrashListener.java",
]
jni_package = "media"
}
android_library("media_java") {
deps = [
"//base:base_java",
"//content/public/android:content_java_resources",
]
java_files = [
"java/src/org/chromium/media/AudioManagerAndroid.java",
"java/src/org/chromium/media/AudioRecordInput.java",
"java/src/org/chromium/media/MediaCodecBridge.java",
"java/src/org/chromium/media/MediaCodecUtil.java",
"java/src/org/chromium/media/MediaDrmBridge.java",
"java/src/org/chromium/media/MediaPlayerBridge.java",
"java/src/org/chromium/media/MediaPlayerListener.java",
"java/src/org/chromium/media/MediaServerCrashListener.java",
]
}
}
| {
"pile_set_name": "Github"
} |
sp_api::decl_runtime_apis! {
pub trait Api {
fn test(data: u64);
}
pub trait Api2 {
fn test(data: u64);
}
}
struct MockApi;
struct MockApi2;
sp_api::mock_impl_runtime_apis! {
impl Api<Block> for MockApi {
fn test(data: u64) {}
}
impl Api2<Block> for MockApi2 {
fn test(data: u64) {}
}
}
fn main() {}
| {
"pile_set_name": "Github"
} |
/**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.brp.brpreview.data.kern;
import org.springframework.roo.addon.dbre.RooDbManaged;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
@RooJavaBean
@RooToString
@RooJpaActiveRecord(versionField = "", table = "categoriepersonen", schema = "kern")
@RooDbManaged(automaticallyDelete = true)
public class Categoriepersonen {
}
| {
"pile_set_name": "Github"
} |
% RES = reconSFpyr(PYR, INDICES, LEVS, BANDS, TWIDTH)
%
% Reconstruct image from its steerable pyramid representation, in the Fourier
% domain, as created by buildSFpyr.
%
% PYR is a vector containing the N pyramid subbands, ordered from fine
% to coarse. INDICES is an Nx2 matrix containing the sizes of
% each subband. This is compatible with the MatLab Wavelet toolbox.
%
% LEVS (optional) should be a list of levels to include, or the string
% 'all' (default). 0 corresonds to the residual highpass subband.
% 1 corresponds to the finest oriented scale. The lowpass band
% corresponds to number spyrHt(INDICES)+1.
%
% BANDS (optional) should be a list of bands to include, or the string
% 'all' (default). 1 = vertical, rest proceeding anti-clockwise.
%
% TWIDTH is the width of the transition region of the radial lowpass
% function, in octaves (default = 1, which gives a raised cosine for
% the bandpass filters).
%%% MODIFIED VERSION, 7/04, uses different lookup table for radial frequency!
% Eero Simoncelli, 5/97.
function res = reconSFpyr(pyr, pind, levs, bands, twidth)
%%------------------------------------------------------------
%% DEFAULTS:
if (exist('levs') ~= 1)
levs = 'all';
end
if (exist('bands') ~= 1)
bands = 'all';
end
if (exist('twidth') ~= 1)
twidth = 1;
elseif (twidth <= 0)
fprintf(1,'Warning: TWIDTH must be positive. Setting to 1.\n');
twidth = 1;
end
%%------------------------------------------------------------
nbands = spyrNumBands(pind);
maxLev = 1+spyrHt(pind);
if strcmp(levs,'all')
levs = [0:maxLev]';
else
if (any(levs > maxLev) | any(levs < 0))
error(sprintf('Level numbers must be in the range [0, %d].', maxLev));
end
levs = levs(:);
end
if strcmp(bands,'all')
bands = [1:nbands]';
else
if (any(bands < 1) | any(bands > nbands))
error(sprintf('Band numbers must be in the range [1,3].', nbands));
end
bands = bands(:);
end
%----------------------------------------------------------------------
dims = pind(1,:);
ctr = ceil((dims+0.5)/2);
[xramp,yramp] = meshgrid( ([1:dims(2)]-ctr(2))./(dims(2)/2), ...
([1:dims(1)]-ctr(1))./(dims(1)/2) );
angle = atan2(yramp,xramp);
log_rad = sqrt(xramp.^2 + yramp.^2);
log_rad(ctr(1),ctr(2)) = log_rad(ctr(1),ctr(2)-1);
log_rad = log2(log_rad);
%% Radial transition function (a raised cosine in log-frequency):
[Xrcos,Yrcos] = rcosFn(twidth,(-twidth/2),[0 1]);
Yrcos = sqrt(Yrcos);
YIrcos = sqrt(abs(1.0 - Yrcos.^2));
if (size(pind,1) == 2)
if (any(levs==1))
resdft = fftshift(fft2(pyrBand(pyr,pind,2)));
else
resdft = zeros(pind(2,:));
end
else
resdft = reconSFpyrLevs(pyr(1+prod(pind(1,:)):size(pyr,1)), ...
pind(2:size(pind,1),:), ...
log_rad, Xrcos, Yrcos, angle, nbands, levs, bands);
end
lo0mask = pointOp(log_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0);
resdft = resdft .* lo0mask;
%% residual highpass subband
if any(levs == 0)
hi0mask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0);
hidft = fftshift(fft2(subMtx(pyr, pind(1,:))));
resdft = resdft + hidft .* hi0mask;
end
res = real(ifft2(ifftshift(resdft)));
| {
"pile_set_name": "Github"
} |
r"""HTTP/1.1 client library
<intro stuff goes here>
<other stuff, too>
HTTPConnection goes through a number of "states", which define when a client
may legally make another request or fetch the response for a particular
request. This diagram details these state transitions:
(null)
|
| HTTPConnection()
v
Idle
|
| putrequest()
v
Request-started
|
| ( putheader() )* endheaders()
v
Request-sent
|\_____________________________
| | getresponse() raises
| response = getresponse() | ConnectionError
v v
Unread-response Idle
[Response-headers-read]
|\____________________
| |
| response.read() | putrequest()
v v
Idle Req-started-unread-response
______/|
/ |
response.read() | | ( putheader() )* endheaders()
v v
Request-started Req-sent-unread-response
|
| response.read()
v
Request-sent
This diagram presents the following rules:
-- a second request may not be started until {response-headers-read}
-- a response [object] cannot be retrieved until {request-sent}
-- there is no differentiation between an unread response body and a
partially read response body
Note: this enforcement is applied by the HTTPConnection class. The
HTTPResponse class does not enforce this state machine, which
implies sophisticated clients may accelerate the request/response
pipeline. Caution should be taken, though: accelerating the states
beyond the above pattern may imply knowledge of the server's
connection-close behavior for certain requests. For example, it
is impossible to tell whether the server will close the connection
UNTIL the response headers have been read; this means that further
requests cannot be placed into the pipeline until it is known that
the server will NOT be closing the connection.
Logical State __state __response
------------- ------- ----------
Idle _CS_IDLE None
Request-started _CS_REQ_STARTED None
Request-sent _CS_REQ_SENT None
Unread-response _CS_IDLE <response_class>
Req-started-unread-response _CS_REQ_STARTED <response_class>
Req-sent-unread-response _CS_REQ_SENT <response_class>
"""
import email.parser
import email.message
import http
import io
import re
import socket
import collections.abc
from urllib.parse import urlsplit
# HTTPMessage, parse_headers(), and the HTTP status code constants are
# intentionally omitted for simplicity
__all__ = ["HTTPResponse", "HTTPConnection",
"HTTPException", "NotConnected", "UnknownProtocol",
"UnknownTransferEncoding", "UnimplementedFileMode",
"IncompleteRead", "InvalidURL", "ImproperConnectionState",
"CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
"BadStatusLine", "LineTooLong", "RemoteDisconnected", "error",
"responses"]
HTTP_PORT = 80
HTTPS_PORT = 443
_UNKNOWN = 'UNKNOWN'
# connection states
_CS_IDLE = 'Idle'
_CS_REQ_STARTED = 'Request-started'
_CS_REQ_SENT = 'Request-sent'
# hack to maintain backwards compatibility
globals().update(http.HTTPStatus.__members__)
# another hack to maintain backwards compatibility
# Mapping status codes to official W3C names
responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()}
# maximal line length when calling readline().
_MAXLINE = 65536
_MAXHEADERS = 100
# Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2)
#
# VCHAR = %x21-7E
# obs-text = %x80-FF
# header-field = field-name ":" OWS field-value OWS
# field-name = token
# field-value = *( field-content / obs-fold )
# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
# field-vchar = VCHAR / obs-text
#
# obs-fold = CRLF 1*( SP / HTAB )
# ; obsolete line folding
# ; see Section 3.2.4
# token = 1*tchar
#
# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
# / DIGIT / ALPHA
# ; any VCHAR, except delimiters
#
# VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1
# the patterns for both name and value are more lenient than RFC
# definitions to allow for backwards compatibility
_is_legal_header_name = re.compile(rb'[^:\s][^:\r\n]*').fullmatch
_is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
# These characters are not allowed within HTTP URL paths.
# See https://tools.ietf.org/html/rfc3986#section-3.3 and the
# https://tools.ietf.org/html/rfc3986#appendix-A pchar definition.
# Prevents CVE-2019-9740. Includes control characters such as \r\n.
# We don't restrict chars above \x7f as putrequest() limits us to ASCII.
_contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]')
# Arguably only these _should_ allowed:
# _is_allowed_url_pchars_re = re.compile(r"^[/!$&'()*+,;=:@%a-zA-Z0-9._~-]+$")
# We are more lenient for assumed real world compatibility purposes.
# We always set the Content-Length header for these methods because some
# servers will otherwise respond with a 411
_METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
def _encode(data, name='data'):
"""Call data.encode("latin-1") but show a better error message."""
try:
return data.encode("latin-1")
except UnicodeEncodeError as err:
raise UnicodeEncodeError(
err.encoding,
err.object,
err.start,
err.end,
"%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') "
"if you want to send it encoded in UTF-8." %
(name.title(), data[err.start:err.end], name)) from None
class HTTPMessage(email.message.Message):
# XXX The only usage of this method is in
# http.server.CGIHTTPRequestHandler. Maybe move the code there so
# that it doesn't need to be part of the public API. The API has
# never been defined so this could cause backwards compatibility
# issues.
def getallmatchingheaders(self, name):
"""Find all header lines matching a given header name.
Look through the list of headers and find all lines matching a given
header name (and their continuation lines). A list of the lines is
returned, without interpretation. If the header does not occur, an
empty list is returned. If the header occurs multiple times, all
occurrences are returned. Case is not important in the header name.
"""
name = name.lower() + ':'
n = len(name)
lst = []
hit = 0
for line in self.keys():
if line[:n].lower() == name:
hit = 1
elif not line[:1].isspace():
hit = 0
if hit:
lst.append(line)
return lst
def parse_headers(fp, _class=HTTPMessage):
"""Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
from the stream, bytes which we later need to read as bytes.
So we read the correct bytes here, as bytes, for email Parser
to parse.
"""
headers = []
while True:
line = fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("header line")
headers.append(line)
if len(headers) > _MAXHEADERS:
raise HTTPException("got more than %d headers" % _MAXHEADERS)
if line in (b'\r\n', b'\n', b''):
break
hstring = b''.join(headers).decode('iso-8859-1')
return email.parser.Parser(_class=_class).parsestr(hstring)
class HTTPResponse(io.BufferedIOBase):
# See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
# The bytes from the socket object are iso-8859-1 strings.
# See RFC 2616 sec 2.2 which notes an exception for MIME-encoded
# text following RFC 2047. The basic status line parsing only
# accepts iso-8859-1.
def __init__(self, sock, debuglevel=0, method=None, url=None):
# If the response includes a content-length header, we need to
# make sure that the client doesn't read more than the
# specified number of bytes. If it does, it will block until
# the server times out and closes the connection. This will
# happen if a self.fp.read() is done (without a size) whether
# self.fp is buffered or not. So, no self.fp.read() by
# clients unless they know what they are doing.
self.fp = sock.makefile("rb")
self.debuglevel = debuglevel
self._method = method
# The HTTPResponse object is returned via urllib. The clients
# of http and urllib expect different attributes for the
# headers. headers is used here and supports urllib. msg is
# provided as a backwards compatibility layer for http
# clients.
self.headers = self.msg = None
# from the Status-Line of the response
self.version = _UNKNOWN # HTTP-Version
self.status = _UNKNOWN # Status-Code
self.reason = _UNKNOWN # Reason-Phrase
self.chunked = _UNKNOWN # is "chunked" being used?
self.chunk_left = _UNKNOWN # bytes left to read in current chunk
self.length = _UNKNOWN # number of bytes left in response
self.will_close = _UNKNOWN # conn will close at end of response
def _read_status(self):
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
if len(line) > _MAXLINE:
raise LineTooLong("status line")
if self.debuglevel > 0:
print("reply:", repr(line))
if not line:
# Presumably, the server closed the connection before
# sending a valid response.
raise RemoteDisconnected("Remote end closed connection without"
" response")
try:
version, status, reason = line.split(None, 2)
except ValueError:
try:
version, status = line.split(None, 1)
reason = ""
except ValueError:
# empty version will cause next test to fail.
version = ""
if not version.startswith("HTTP/"):
self._close_conn()
raise BadStatusLine(line)
# The status code is a three-digit number
try:
status = int(status)
if status < 100 or status > 999:
raise BadStatusLine(line)
except ValueError:
raise BadStatusLine(line)
return version, status, reason
def begin(self):
if self.headers is not None:
# we've already started reading the response
return
# read until we get a non-100 response
while True:
version, status, reason = self._read_status()
if status != CONTINUE:
break
# skip the header from the 100 response
while True:
skip = self.fp.readline(_MAXLINE + 1)
if len(skip) > _MAXLINE:
raise LineTooLong("header line")
skip = skip.strip()
if not skip:
break
if self.debuglevel > 0:
print("header:", skip)
self.code = self.status = status
self.reason = reason.strip()
if version in ("HTTP/1.0", "HTTP/0.9"):
# Some servers might still return "0.9", treat it as 1.0 anyway
self.version = 10
elif version.startswith("HTTP/1."):
self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
else:
raise UnknownProtocol(version)
self.headers = self.msg = parse_headers(self.fp)
if self.debuglevel > 0:
for hdr, val in self.headers.items():
print("header:", hdr + ":", val)
# are we using the chunked-style of transfer encoding?
tr_enc = self.headers.get("transfer-encoding")
if tr_enc and tr_enc.lower() == "chunked":
self.chunked = True
self.chunk_left = None
else:
self.chunked = False
# will the connection close at the end of the response?
self.will_close = self._check_close()
# do we have a Content-Length?
# NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
self.length = None
length = self.headers.get("content-length")
# are we using the chunked-style of transfer encoding?
tr_enc = self.headers.get("transfer-encoding")
if length and not self.chunked:
try:
self.length = int(length)
except ValueError:
self.length = None
else:
if self.length < 0: # ignore nonsensical negative lengths
self.length = None
else:
self.length = None
# does the body have a fixed length? (of zero)
if (status == NO_CONTENT or status == NOT_MODIFIED or
100 <= status < 200 or # 1xx codes
self._method == "HEAD"):
self.length = 0
# if the connection remains open, and we aren't using chunked, and
# a content-length was not provided, then assume that the connection
# WILL close.
if (not self.will_close and
not self.chunked and
self.length is None):
self.will_close = True
def _check_close(self):
conn = self.headers.get("connection")
if self.version == 11:
# An HTTP/1.1 proxy is assumed to stay open unless
# explicitly closed.
if conn and "close" in conn.lower():
return True
return False
# Some HTTP/1.0 implementations have support for persistent
# connections, using rules different than HTTP/1.1.
# For older HTTP, Keep-Alive indicates persistent connection.
if self.headers.get("keep-alive"):
return False
# At least Akamai returns a "Connection: Keep-Alive" header,
# which was supposed to be sent by the client.
if conn and "keep-alive" in conn.lower():
return False
# Proxy-Connection is a netscape hack.
pconn = self.headers.get("proxy-connection")
if pconn and "keep-alive" in pconn.lower():
return False
# otherwise, assume it will close
return True
def _close_conn(self):
fp = self.fp
self.fp = None
fp.close()
def close(self):
try:
super().close() # set "closed" flag
finally:
if self.fp:
self._close_conn()
# These implementations are for the benefit of io.BufferedReader.
# XXX This class should probably be revised to act more like
# the "raw stream" that BufferedReader expects.
def flush(self):
super().flush()
if self.fp:
self.fp.flush()
def readable(self):
"""Always returns True"""
return True
# End of "raw stream" methods
def isclosed(self):
"""True if the connection is closed."""
# NOTE: it is possible that we will not ever call self.close(). This
# case occurs when will_close is TRUE, length is None, and we
# read up to the last byte, but NOT past it.
#
# IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
# called, meaning self.isclosed() is meaningful.
return self.fp is None
def read(self, amt=None):
if self.fp is None:
return b""
if self._method == "HEAD":
self._close_conn()
return b""
if amt is not None:
# Amount is given, implement using readinto
b = bytearray(amt)
n = self.readinto(b)
return memoryview(b)[:n].tobytes()
else:
# Amount is not given (unbounded read) so we must check self.length
# and self.chunked
if self.chunked:
return self._readall_chunked()
if self.length is None:
s = self.fp.read()
else:
try:
s = self._safe_read(self.length)
except IncompleteRead:
self._close_conn()
raise
self.length = 0
self._close_conn() # we read everything
return s
def readinto(self, b):
"""Read up to len(b) bytes into bytearray b and return the number
of bytes read.
"""
if self.fp is None:
return 0
if self._method == "HEAD":
self._close_conn()
return 0
if self.chunked:
return self._readinto_chunked(b)
if self.length is not None:
if len(b) > self.length:
# clip the read to the "end of response"
b = memoryview(b)[0:self.length]
# we do not use _safe_read() here because this may be a .will_close
# connection, and the user is reading more bytes than will be provided
# (for example, reading in 1k chunks)
n = self.fp.readinto(b)
if not n and b:
# Ideally, we would raise IncompleteRead if the content-length
# wasn't satisfied, but it might break compatibility.
self._close_conn()
elif self.length is not None:
self.length -= n
if not self.length:
self._close_conn()
return n
def _read_next_chunk_size(self):
# Read the next chunk size from the file
line = self.fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("chunk size")
i = line.find(b";")
if i >= 0:
line = line[:i] # strip chunk-extensions
try:
return int(line, 16)
except ValueError:
# close the connection as protocol synchronisation is
# probably lost
self._close_conn()
raise
def _read_and_discard_trailer(self):
# read and discard trailer up to the CRLF terminator
### note: we shouldn't have any trailers!
while True:
line = self.fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("trailer line")
if not line:
# a vanishingly small number of sites EOF without
# sending the trailer
break
if line in (b'\r\n', b'\n', b''):
break
def _get_chunk_left(self):
# return self.chunk_left, reading a new chunk if necessary.
# chunk_left == 0: at the end of the current chunk, need to close it
# chunk_left == None: No current chunk, should read next.
# This function returns non-zero or None if the last chunk has
# been read.
chunk_left = self.chunk_left
if not chunk_left: # Can be 0 or None
if chunk_left is not None:
# We are at the end of chunk, discard chunk end
self._safe_read(2) # toss the CRLF at the end of the chunk
try:
chunk_left = self._read_next_chunk_size()
except ValueError:
raise IncompleteRead(b'')
if chunk_left == 0:
# last chunk: 1*("0") [ chunk-extension ] CRLF
self._read_and_discard_trailer()
# we read everything; close the "file"
self._close_conn()
chunk_left = None
self.chunk_left = chunk_left
return chunk_left
def _readall_chunked(self):
assert self.chunked != _UNKNOWN
value = []
try:
while True:
chunk_left = self._get_chunk_left()
if chunk_left is None:
break
value.append(self._safe_read(chunk_left))
self.chunk_left = 0
return b''.join(value)
except IncompleteRead:
raise IncompleteRead(b''.join(value))
def _readinto_chunked(self, b):
assert self.chunked != _UNKNOWN
total_bytes = 0
mvb = memoryview(b)
try:
while True:
chunk_left = self._get_chunk_left()
if chunk_left is None:
return total_bytes
if len(mvb) <= chunk_left:
n = self._safe_readinto(mvb)
self.chunk_left = chunk_left - n
return total_bytes + n
temp_mvb = mvb[:chunk_left]
n = self._safe_readinto(temp_mvb)
mvb = mvb[n:]
total_bytes += n
self.chunk_left = 0
except IncompleteRead:
raise IncompleteRead(bytes(b[0:total_bytes]))
def _safe_read(self, amt):
"""Read the number of bytes requested.
This function should be used when <amt> bytes "should" be present for
reading. If the bytes are truly not available (due to EOF), then the
IncompleteRead exception can be used to detect the problem.
"""
data = self.fp.read(amt)
if len(data) < amt:
raise IncompleteRead(data, amt-len(data))
return data
def _safe_readinto(self, b):
"""Same as _safe_read, but for reading into a buffer."""
amt = len(b)
n = self.fp.readinto(b)
if n < amt:
raise IncompleteRead(bytes(b[:n]), amt-n)
return n
def read1(self, n=-1):
"""Read with at most one underlying system call. If at least one
byte is buffered, return that instead.
"""
if self.fp is None or self._method == "HEAD":
return b""
if self.chunked:
return self._read1_chunked(n)
if self.length is not None and (n < 0 or n > self.length):
n = self.length
result = self.fp.read1(n)
if not result and n:
self._close_conn()
elif self.length is not None:
self.length -= len(result)
return result
def peek(self, n=-1):
# Having this enables IOBase.readline() to read more than one
# byte at a time
if self.fp is None or self._method == "HEAD":
return b""
if self.chunked:
return self._peek_chunked(n)
return self.fp.peek(n)
def readline(self, limit=-1):
if self.fp is None or self._method == "HEAD":
return b""
if self.chunked:
# Fallback to IOBase readline which uses peek() and read()
return super().readline(limit)
if self.length is not None and (limit < 0 or limit > self.length):
limit = self.length
result = self.fp.readline(limit)
if not result and limit:
self._close_conn()
elif self.length is not None:
self.length -= len(result)
return result
def _read1_chunked(self, n):
# Strictly speaking, _get_chunk_left() may cause more than one read,
# but that is ok, since that is to satisfy the chunked protocol.
chunk_left = self._get_chunk_left()
if chunk_left is None or n == 0:
return b''
if not (0 <= n <= chunk_left):
n = chunk_left # if n is negative or larger than chunk_left
read = self.fp.read1(n)
self.chunk_left -= len(read)
if not read:
raise IncompleteRead(b"")
return read
def _peek_chunked(self, n):
# Strictly speaking, _get_chunk_left() may cause more than one read,
# but that is ok, since that is to satisfy the chunked protocol.
try:
chunk_left = self._get_chunk_left()
except IncompleteRead:
return b'' # peek doesn't worry about protocol
if chunk_left is None:
return b'' # eof
# peek is allowed to return more than requested. Just request the
# entire chunk, and truncate what we get.
return self.fp.peek(chunk_left)[:chunk_left]
def fileno(self):
return self.fp.fileno()
def getheader(self, name, default=None):
'''Returns the value of the header matching *name*.
If there are multiple matching headers, the values are
combined into a single string separated by commas and spaces.
If no matching header is found, returns *default* or None if
the *default* is not specified.
If the headers are unknown, raises http.client.ResponseNotReady.
'''
if self.headers is None:
raise ResponseNotReady()
headers = self.headers.get_all(name) or default
if isinstance(headers, str) or not hasattr(headers, '__iter__'):
return headers
else:
return ', '.join(headers)
def getheaders(self):
"""Return list of (header, value) tuples."""
if self.headers is None:
raise ResponseNotReady()
return list(self.headers.items())
# We override IOBase.__iter__ so that it doesn't check for closed-ness
def __iter__(self):
return self
# For compatibility with old-style urllib responses.
def info(self):
'''Returns an instance of the class mimetools.Message containing
meta-information associated with the URL.
When the method is HTTP, these headers are those returned by
the server at the head of the retrieved HTML page (including
Content-Length and Content-Type).
When the method is FTP, a Content-Length header will be
present if (as is now usual) the server passed back a file
length in response to the FTP retrieval request. A
Content-Type header will be present if the MIME type can be
guessed.
When the method is local-file, returned headers will include
a Date representing the file's last-modified time, a
Content-Length giving file size, and a Content-Type
containing a guess at the file's type. See also the
description of the mimetools module.
'''
return self.headers
def geturl(self):
'''Return the real URL of the page.
In some cases, the HTTP server redirects a client to another
URL. The urlopen() function handles this transparently, but in
some cases the caller needs to know which URL the client was
redirected to. The geturl() method can be used to get at this
redirected URL.
'''
return self.url
def getcode(self):
'''Return the HTTP status code that was sent with the response,
or None if the URL is not an HTTP URL.
'''
return self.status
class HTTPConnection:
_http_vsn = 11
_http_vsn_str = 'HTTP/1.1'
response_class = HTTPResponse
default_port = HTTP_PORT
auto_open = 1
debuglevel = 0
@staticmethod
def _is_textIO(stream):
"""Test whether a file-like object is a text or a binary stream.
"""
return isinstance(stream, io.TextIOBase)
@staticmethod
def _get_content_length(body, method):
"""Get the content-length based on the body.
If the body is None, we set Content-Length: 0 for methods that expect
a body (RFC 7230, Section 3.3.2). We also set the Content-Length for
any method if the body is a str or bytes-like object and not a file.
"""
if body is None:
# do an explicit check for not None here to distinguish
# between unset and set but empty
if method.upper() in _METHODS_EXPECTING_BODY:
return 0
else:
return None
if hasattr(body, 'read'):
# file-like object.
return None
try:
# does it implement the buffer protocol (bytes, bytearray, array)?
mv = memoryview(body)
return mv.nbytes
except TypeError:
pass
if isinstance(body, str):
return len(body)
return None
def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, blocksize=8192):
self.timeout = timeout
self.source_address = source_address
self.blocksize = blocksize
self.sock = None
self._buffer = []
self.__response = None
self.__state = _CS_IDLE
self._method = None
self._tunnel_host = None
self._tunnel_port = None
self._tunnel_headers = {}
(self.host, self.port) = self._get_hostport(host, port)
# This is stored as an instance variable to allow unit
# tests to replace it with a suitable mockup
self._create_connection = socket.create_connection
def set_tunnel(self, host, port=None, headers=None):
"""Set up host and port for HTTP CONNECT tunnelling.
In a connection that uses HTTP CONNECT tunneling, the host passed to the
constructor is used as a proxy server that relays all communication to
the endpoint passed to `set_tunnel`. This done by sending an HTTP
CONNECT request to the proxy server when the connection is established.
This method must be called before the HTML connection has been
established.
The headers argument should be a mapping of extra HTTP headers to send
with the CONNECT request.
"""
if self.sock:
raise RuntimeError("Can't set up tunnel for established connection")
self._tunnel_host, self._tunnel_port = self._get_hostport(host, port)
if headers:
self._tunnel_headers = headers
else:
self._tunnel_headers.clear()
def _get_hostport(self, host, port):
if port is None:
i = host.rfind(':')
j = host.rfind(']') # ipv6 addresses have [...]
if i > j:
try:
port = int(host[i+1:])
except ValueError:
if host[i+1:] == "": # http://foo.com:/ == http://foo.com/
port = self.default_port
else:
raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
host = host[:i]
else:
port = self.default_port
if host and host[0] == '[' and host[-1] == ']':
host = host[1:-1]
return (host, port)
def set_debuglevel(self, level):
self.debuglevel = level
def _tunnel(self):
connect_str = "CONNECT %s:%d HTTP/1.0\r\n" % (self._tunnel_host,
self._tunnel_port)
connect_bytes = connect_str.encode("ascii")
self.send(connect_bytes)
for header, value in self._tunnel_headers.items():
header_str = "%s: %s\r\n" % (header, value)
header_bytes = header_str.encode("latin-1")
self.send(header_bytes)
self.send(b'\r\n')
response = self.response_class(self.sock, method=self._method)
(version, code, message) = response._read_status()
if code != http.HTTPStatus.OK:
self.close()
raise OSError("Tunnel connection failed: %d %s" % (code,
message.strip()))
while True:
line = response.fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("header line")
if not line:
# for sites which EOF without sending a trailer
break
if line in (b'\r\n', b'\n', b''):
break
if self.debuglevel > 0:
print('header:', line.decode())
def connect(self):
"""Connect to the host and port specified in __init__."""
self.sock = self._create_connection(
(self.host,self.port), self.timeout, self.source_address)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if self._tunnel_host:
self._tunnel()
def close(self):
"""Close the connection to the HTTP server."""
self.__state = _CS_IDLE
try:
sock = self.sock
if sock:
self.sock = None
sock.close() # close it manually... there may be other refs
finally:
response = self.__response
if response:
self.__response = None
response.close()
def send(self, data):
"""Send `data' to the server.
``data`` can be a string object, a bytes object, an array object, a
file-like object that supports a .read() method, or an iterable object.
"""
if self.sock is None:
if self.auto_open:
self.connect()
else:
raise NotConnected()
if self.debuglevel > 0:
print("send:", repr(data))
if hasattr(data, "read") :
if self.debuglevel > 0:
print("sendIng a read()able")
encode = self._is_textIO(data)
if encode and self.debuglevel > 0:
print("encoding file using iso-8859-1")
while 1:
datablock = data.read(self.blocksize)
if not datablock:
break
if encode:
datablock = datablock.encode("iso-8859-1")
self.sock.sendall(datablock)
return
try:
self.sock.sendall(data)
except TypeError:
if isinstance(data, collections.abc.Iterable):
for d in data:
self.sock.sendall(d)
else:
raise TypeError("data should be a bytes-like object "
"or an iterable, got %r" % type(data))
def _output(self, s):
"""Add a line of output to the current request buffer.
Assumes that the line does *not* end with \\r\\n.
"""
self._buffer.append(s)
def _read_readable(self, readable):
if self.debuglevel > 0:
print("sendIng a read()able")
encode = self._is_textIO(readable)
if encode and self.debuglevel > 0:
print("encoding file using iso-8859-1")
while True:
datablock = readable.read(self.blocksize)
if not datablock:
break
if encode:
datablock = datablock.encode("iso-8859-1")
yield datablock
def _send_output(self, message_body=None, encode_chunked=False):
"""Send the currently buffered request and clear the buffer.
Appends an extra \\r\\n to the buffer.
A message_body may be specified, to be appended to the request.
"""
self._buffer.extend((b"", b""))
msg = b"\r\n".join(self._buffer)
del self._buffer[:]
self.send(msg)
if message_body is not None:
# create a consistent interface to message_body
if hasattr(message_body, 'read'):
# Let file-like take precedence over byte-like. This
# is needed to allow the current position of mmap'ed
# files to be taken into account.
chunks = self._read_readable(message_body)
else:
try:
# this is solely to check to see if message_body
# implements the buffer API. it /would/ be easier
# to capture if PyObject_CheckBuffer was exposed
# to Python.
memoryview(message_body)
except TypeError:
try:
chunks = iter(message_body)
except TypeError:
raise TypeError("message_body should be a bytes-like "
"object or an iterable, got %r"
% type(message_body))
else:
# the object implements the buffer interface and
# can be passed directly into socket methods
chunks = (message_body,)
for chunk in chunks:
if not chunk:
if self.debuglevel > 0:
print('Zero length chunk ignored')
continue
if encode_chunked and self._http_vsn == 11:
# chunked encoding
chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
+ b'\r\n'
self.send(chunk)
if encode_chunked and self._http_vsn == 11:
# end chunked transfer
self.send(b'0\r\n\r\n')
def putrequest(self, method, url, skip_host=False,
skip_accept_encoding=False):
"""Send a request to the server.
`method' specifies an HTTP request method, e.g. 'GET'.
`url' specifies the object being requested, e.g. '/index.html'.
`skip_host' if True does not add automatically a 'Host:' header
`skip_accept_encoding' if True does not add automatically an
'Accept-Encoding:' header
"""
# if a prior response has been completed, then forget about it.
if self.__response and self.__response.isclosed():
self.__response = None
# in certain cases, we cannot issue another request on this connection.
# this occurs when:
# 1) we are in the process of sending a request. (_CS_REQ_STARTED)
# 2) a response to a previous request has signalled that it is going
# to close the connection upon completion.
# 3) the headers for the previous response have not been read, thus
# we cannot determine whether point (2) is true. (_CS_REQ_SENT)
#
# if there is no prior response, then we can request at will.
#
# if point (2) is true, then we will have passed the socket to the
# response (effectively meaning, "there is no prior response"), and
# will open a new one when a new request is made.
#
# Note: if a prior response exists, then we *can* start a new request.
# We are not allowed to begin fetching the response to this new
# request, however, until that prior response is complete.
#
if self.__state == _CS_IDLE:
self.__state = _CS_REQ_STARTED
else:
raise CannotSendRequest(self.__state)
# Save the method for use later in the response phase
self._method = method
url = url or '/'
self._validate_path(url)
request = '%s %s %s' % (method, url, self._http_vsn_str)
self._output(self._encode_request(request))
if self._http_vsn == 11:
# Issue some standard headers for better HTTP/1.1 compliance
if not skip_host:
# this header is issued *only* for HTTP/1.1
# connections. more specifically, this means it is
# only issued when the client uses the new
# HTTPConnection() class. backwards-compat clients
# will be using HTTP/1.0 and those clients may be
# issuing this header themselves. we should NOT issue
# it twice; some web servers (such as Apache) barf
# when they see two Host: headers
# If we need a non-standard port,include it in the
# header. If the request is going through a proxy,
# but the host of the actual URL, not the host of the
# proxy.
netloc = ''
if url.startswith('http'):
nil, netloc, nil, nil, nil = urlsplit(url)
if netloc:
try:
netloc_enc = netloc.encode("ascii")
except UnicodeEncodeError:
netloc_enc = netloc.encode("idna")
self.putheader('Host', netloc_enc)
else:
if self._tunnel_host:
host = self._tunnel_host
port = self._tunnel_port
else:
host = self.host
port = self.port
try:
host_enc = host.encode("ascii")
except UnicodeEncodeError:
host_enc = host.encode("idna")
# As per RFC 273, IPv6 address should be wrapped with []
# when used as Host header
if host.find(':') >= 0:
host_enc = b'[' + host_enc + b']'
if port == self.default_port:
self.putheader('Host', host_enc)
else:
host_enc = host_enc.decode("ascii")
self.putheader('Host', "%s:%s" % (host_enc, port))
# note: we are assuming that clients will not attempt to set these
# headers since *this* library must deal with the
# consequences. this also means that when the supporting
# libraries are updated to recognize other forms, then this
# code should be changed (removed or updated).
# we only want a Content-Encoding of "identity" since we don't
# support encodings such as x-gzip or x-deflate.
if not skip_accept_encoding:
self.putheader('Accept-Encoding', 'identity')
# we can accept "chunked" Transfer-Encodings, but no others
# NOTE: no TE header implies *only* "chunked"
#self.putheader('TE', 'chunked')
# if TE is supplied in the header, then it must appear in a
# Connection header.
#self.putheader('Connection', 'TE')
else:
# For HTTP/1.0, the server will assume "not chunked"
pass
def _encode_request(self, request):
# ASCII also helps prevent CVE-2019-9740.
return request.encode('ascii')
def _validate_path(self, url):
"""Validate a url for putrequest."""
# Prevent CVE-2019-9740.
match = _contains_disallowed_url_pchar_re.search(url)
if match:
raise InvalidURL(f"URL can't contain control characters. {url!r} "
f"(found at least {match.group()!r})")
def putheader(self, header, *values):
"""Send a request header line to the server.
For example: h.putheader('Accept', 'text/html')
"""
if self.__state != _CS_REQ_STARTED:
raise CannotSendHeader()
if hasattr(header, 'encode'):
header = header.encode('ascii')
if not _is_legal_header_name(header):
raise ValueError('Invalid header name %r' % (header,))
values = list(values)
for i, one_value in enumerate(values):
if hasattr(one_value, 'encode'):
values[i] = one_value.encode('latin-1')
elif isinstance(one_value, int):
values[i] = str(one_value).encode('ascii')
if _is_illegal_header_value(values[i]):
raise ValueError('Invalid header value %r' % (values[i],))
value = b'\r\n\t'.join(values)
header = header + b': ' + value
self._output(header)
def endheaders(self, message_body=None, *, encode_chunked=False):
"""Indicate that the last header line has been sent to the server.
This method sends the request to the server. The optional message_body
argument can be used to pass a message body associated with the
request.
"""
if self.__state == _CS_REQ_STARTED:
self.__state = _CS_REQ_SENT
else:
raise CannotSendHeader()
self._send_output(message_body, encode_chunked=encode_chunked)
def request(self, method, url, body=None, headers={}, *,
encode_chunked=False):
"""Send a complete request to the server."""
self._send_request(method, url, body, headers, encode_chunked)
def _send_request(self, method, url, body, headers, encode_chunked):
# Honor explicitly requested Host: and Accept-Encoding: headers.
header_names = frozenset(k.lower() for k in headers)
skips = {}
if 'host' in header_names:
skips['skip_host'] = 1
if 'accept-encoding' in header_names:
skips['skip_accept_encoding'] = 1
self.putrequest(method, url, **skips)
# chunked encoding will happen if HTTP/1.1 is used and either
# the caller passes encode_chunked=True or the following
# conditions hold:
# 1. content-length has not been explicitly set
# 2. the body is a file or iterable, but not a str or bytes-like
# 3. Transfer-Encoding has NOT been explicitly set by the caller
if 'content-length' not in header_names:
# only chunk body if not explicitly set for backwards
# compatibility, assuming the client code is already handling the
# chunking
if 'transfer-encoding' not in header_names:
# if content-length cannot be automatically determined, fall
# back to chunked encoding
encode_chunked = False
content_length = self._get_content_length(body, method)
if content_length is None:
if body is not None:
if self.debuglevel > 0:
print('Unable to determine size of %r' % body)
encode_chunked = True
self.putheader('Transfer-Encoding', 'chunked')
else:
self.putheader('Content-Length', str(content_length))
else:
encode_chunked = False
for hdr, value in headers.items():
self.putheader(hdr, value)
if isinstance(body, str):
# RFC 2616 Section 3.7.1 says that text default has a
# default charset of iso-8859-1.
body = _encode(body, 'body')
self.endheaders(body, encode_chunked=encode_chunked)
def getresponse(self):
"""Get the response from the server.
If the HTTPConnection is in the correct state, returns an
instance of HTTPResponse or of whatever object is returned by
the response_class variable.
If a request has not been sent or if a previous response has
not be handled, ResponseNotReady is raised. If the HTTP
response indicates that the connection should be closed, then
it will be closed before the response is returned. When the
connection is closed, the underlying socket is closed.
"""
# if a prior response has been completed, then forget about it.
if self.__response and self.__response.isclosed():
self.__response = None
# if a prior response exists, then it must be completed (otherwise, we
# cannot read this response's header to determine the connection-close
# behavior)
#
# note: if a prior response existed, but was connection-close, then the
# socket and response were made independent of this HTTPConnection
# object since a new request requires that we open a whole new
# connection
#
# this means the prior response had one of two states:
# 1) will_close: this connection was reset and the prior socket and
# response operate independently
# 2) persistent: the response was retained and we await its
# isclosed() status to become true.
#
if self.__state != _CS_REQ_SENT or self.__response:
raise ResponseNotReady(self.__state)
if self.debuglevel > 0:
response = self.response_class(self.sock, self.debuglevel,
method=self._method)
else:
response = self.response_class(self.sock, method=self._method)
try:
try:
response.begin()
except ConnectionError:
self.close()
raise
assert response.will_close != _UNKNOWN
self.__state = _CS_IDLE
if response.will_close:
# this effectively passes the connection to the response
self.close()
else:
# remember this, so we can tell when it is complete
self.__response = response
return response
except:
response.close()
raise
try:
import ssl
except ImportError:
pass
else:
class HTTPSConnection(HTTPConnection):
"This class allows communication via SSL."
default_port = HTTPS_PORT
# XXX Should key_file and cert_file be deprecated in favour of context?
def __init__(self, host, port=None, key_file=None, cert_file=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, *, context=None,
check_hostname=None, blocksize=8192):
super(HTTPSConnection, self).__init__(host, port, timeout,
source_address,
blocksize=blocksize)
if (key_file is not None or cert_file is not None or
check_hostname is not None):
import warnings
warnings.warn("key_file, cert_file and check_hostname are "
"deprecated, use a custom context instead.",
DeprecationWarning, 2)
self.key_file = key_file
self.cert_file = cert_file
if context is None:
context = ssl._create_default_https_context()
# enable PHA for TLS 1.3 connections if available
if context.post_handshake_auth is not None:
context.post_handshake_auth = True
will_verify = context.verify_mode != ssl.CERT_NONE
if check_hostname is None:
check_hostname = context.check_hostname
if check_hostname and not will_verify:
raise ValueError("check_hostname needs a SSL context with "
"either CERT_OPTIONAL or CERT_REQUIRED")
if key_file or cert_file:
context.load_cert_chain(cert_file, key_file)
# cert and key file means the user wants to authenticate.
# enable TLS 1.3 PHA implicitly even for custom contexts.
if context.post_handshake_auth is not None:
context.post_handshake_auth = True
self._context = context
if check_hostname is not None:
self._context.check_hostname = check_hostname
def connect(self):
"Connect to a host on a given (SSL) port."
super().connect()
if self._tunnel_host:
server_hostname = self._tunnel_host
else:
server_hostname = self.host
self.sock = self._context.wrap_socket(self.sock,
server_hostname=server_hostname)
__all__.append("HTTPSConnection")
class HTTPException(Exception):
# Subclasses that define an __init__ must call Exception.__init__
# or define self.args. Otherwise, str() will fail.
pass
class NotConnected(HTTPException):
pass
class InvalidURL(HTTPException):
pass
class UnknownProtocol(HTTPException):
def __init__(self, version):
self.args = version,
self.version = version
class UnknownTransferEncoding(HTTPException):
pass
class UnimplementedFileMode(HTTPException):
pass
class IncompleteRead(HTTPException):
def __init__(self, partial, expected=None):
self.args = partial,
self.partial = partial
self.expected = expected
def __repr__(self):
if self.expected is not None:
e = ', %i more expected' % self.expected
else:
e = ''
return '%s(%i bytes read%s)' % (self.__class__.__name__,
len(self.partial), e)
__str__ = object.__str__
class ImproperConnectionState(HTTPException):
pass
class CannotSendRequest(ImproperConnectionState):
pass
class CannotSendHeader(ImproperConnectionState):
pass
class ResponseNotReady(ImproperConnectionState):
pass
class BadStatusLine(HTTPException):
def __init__(self, line):
if not line:
line = repr(line)
self.args = line,
self.line = line
class LineTooLong(HTTPException):
def __init__(self, line_type):
HTTPException.__init__(self, "got more than %d bytes when reading %s"
% (_MAXLINE, line_type))
class RemoteDisconnected(ConnectionResetError, BadStatusLine):
def __init__(self, *pos, **kw):
BadStatusLine.__init__(self, "")
ConnectionResetError.__init__(self, *pos, **kw)
# for backwards compatibility
error = HTTPException
| {
"pile_set_name": "Github"
} |
StartChar: racute
Encoding: 341 341 256
GlifName: racute
Width: 1024
VWidth: 0
Flags: W
HStem: 0 21G<256 384> 920 120<559.204 893.328> 1004 20G<256 384> 1152 256
VStem: 256 128<0 724.349 865 1024> 488 304
LayerCount: 5
Back
Fore
Refer: 294 769 N 1 0 0 1 0 -128 2
Refer: 18 114 N 1 0 0 1 0 0 3
Validated: 1
Layer: 2
Layer: 3
Layer: 4
EndChar
| {
"pile_set_name": "Github"
} |
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2019 F4EXB //
// written by Edouard Griffiths //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program 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 General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef SDRBASE_AUDIO_AUDIORESAMPLER_H_
#define SDRBASE_AUDIO_AUDIORESAMPLER_H_
#include "dsp/dsptypes.h"
#include "audiofilter.h"
class SDRBASE_API AudioResampler
{
public:
AudioResampler();
~AudioResampler();
void setDecimation(uint32_t decimation);
uint32_t getDecimation() const { return m_decimation; }
void setAudioFilters(int srHigh, int srLow, int fcLow, int fcHigh, float gain=1.0f);
bool downSample(qint16 sampleIn, qint16& sampleOut);
bool upSample(qint16 sampleIn, qint16& sampleOut);
private:
AudioFilter m_audioFilter;
uint32_t m_decimation;
uint32_t m_decimationCount;
};
#endif /* SDRBASE_AUDIO_AUDIORESAMPLER_H_ */
| {
"pile_set_name": "Github"
} |
--- jabberd/jabberd.h.orig
+++ jabberd/jabberd.h
@@ -103,10 +103,10 @@
#include <jabberdlib.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
+#include <gnutls/openpgp.h>
#ifdef HAVE_GNUTLS_EXTRA
# include <gnutls/extra.h>
-# include <gnutls/openpgp.h>
#endif
/** Packet types */
| {
"pile_set_name": "Github"
} |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from torch import nn
from nemo.core.classes import Loss, typecheck
from nemo.core.neural_types import ChannelType, LogitsType, LossType, NeuralType
__all__ = ['SpanningLoss']
class SpanningLoss(Loss):
"""
implements start and end loss of a span e.g. for Question Answering.
"""
@property
def input_types(self):
"""Returns definitions of module input ports.
"""
return {
"logits": NeuralType(('B', 'T', 'D'), LogitsType()),
"start_positions": NeuralType(tuple('B'), ChannelType()),
"end_positions": NeuralType(tuple('B'), ChannelType()),
}
@property
def output_types(self):
"""Returns definitions of module output ports.
"""
return {
"loss": NeuralType(elements_type=LossType()),
"start_logits": NeuralType(('B', 'T'), LogitsType()),
"end_logits": NeuralType(('B', 'T'), LogitsType()),
}
def __init__(self,):
super().__init__()
@typecheck()
def forward(self, logits, start_positions, end_positions):
"""
Args:
logits: Output of question answering head, which is a token classfier.
start_positions: Ground truth start positions of the answer w.r.t.
input sequence. If question is unanswerable, this will be
pointing to start token, e.g. [CLS], of the input sequence.
end_positions: Ground truth end positions of the answer w.r.t.
input sequence. If question is unanswerable, this will be
pointing to start token, e.g. [CLS], of the input sequence.
"""
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1)
end_logits = end_logits.squeeze(-1)
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
end_positions = end_positions.squeeze(-1)
ignored_index = start_logits.size(1)
start_positions.clamp_(0, ignored_index)
end_positions.clamp_(0, ignored_index)
loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
return total_loss, start_logits, end_logits
| {
"pile_set_name": "Github"
} |
<% cache "base_inline_styles_#{@story_show}_#{@article_index}_#{@home_page}_#{@article_show}_#{view_class}_#{@notifications_index}_#{@tags_index}_#{@reading_list_items_index}_#{@history_index}_#{ApplicationConfig['RELEASE_FOOTPRINT']}_#{user_signed_in?}_#{@shell}", expires_in: 8.hours do %>
<% if @shell %>
<style>
<% Rails.application.config.assets.compile = true %>
<%= Rails.application.assets["crayons.css"].to_s.html_safe %>
<%= Rails.application.assets["minimal.css"].to_s.html_safe %>
</style>
<% elsif @story_show %>
<style>
<% Rails.application.config.assets.compile = true %>
<%= Rails.application.assets["crayons.css"].to_s.html_safe %>
<%= Rails.application.assets["scaffolds.css"].to_s.html_safe %>
<% if @article_show %>
<%= Rails.application.assets["comments.css"].to_s.html_safe %>
<%= Rails.application.assets["ltags/LiquidTags.css"].to_s.html_safe %>
<% else %>
<%= Rails.application.assets["podcast-episodes-show.css"].to_s.html_safe %>
<%= Rails.application.assets["comments.css"].to_s.html_safe %>
<% end %>
</style>
<% elsif @article_index %>
<style>
<% Rails.application.config.assets.compile = true %>
<%= Rails.application.assets["crayons.css"].to_s.html_safe %>
<%= Rails.application.assets["scaffolds.css"].to_s.html_safe %>
<%= Rails.application.assets["articles.css"].to_s.html_safe %>
<%= Rails.application.assets["buttons.css"].to_s.html_safe %>
<%= Rails.application.assets["widgets.css"].to_s.html_safe %>
<%= Rails.application.assets["preact/sidebar-widget.css"].to_s.html_safe %>
<% unless @home_page %>
<%= Rails.application.assets["user-profile-header.css"].to_s.html_safe %>
<%= Rails.application.assets["sidebar-data.css"].to_s.html_safe %>
<%= Rails.application.assets["index-comments.css"].to_s.html_safe %>
<% end %>
</style>
<% elsif @notifications_index || @reading_list_items_index || @history_index %>
<style>
<% Rails.application.config.assets.compile = true %>
<%= Rails.application.assets["crayons.css"].to_s.html_safe %>
<%= Rails.application.assets["scaffolds.css"].to_s.html_safe %>
<%= Rails.application.assets["readinglist.css"].to_s.html_safe %>
<%= Rails.application.assets["articles.css"].to_s.html_safe %>
<%= Rails.application.assets["buttons.css"].to_s.html_safe %>
<%= Rails.application.assets["widgets.css"].to_s.html_safe %>
<%= Rails.application.assets["comments.css"].to_s.html_safe %>
<%= Rails.application.assets["notifications.css"].to_s.html_safe %>
<%= Rails.application.assets["user-profile-header.css"].to_s.html_safe %>
<%= Rails.application.assets["ltags/LiquidTags.css"].to_s.html_safe %>
</style>
<% elsif view_class.start_with? "comments" %>
<style>
<%= Rails.application.assets["crayons.css"].to_s.html_safe %>
<%= Rails.application.assets["scaffolds.css"].to_s.html_safe %>
<%= Rails.application.assets["comments.css"].to_s.html_safe %>
<%= Rails.application.assets["ltags/LiquidTags.css"].to_s.html_safe %>
<% if view_class.include? "comments-settings" %>
<% end %>
</style>
<% elsif view_class.include?("registrations") || @new_article_not_logged_in %>
<style>
<%= Rails.application.assets["crayons.css"].to_s.html_safe %>
<%= Rails.application.assets["scaffolds.css"].to_s.html_safe %>
</style>
<% elsif view_class.include? "listings-" %>
<style>
<%= Rails.application.assets["crayons.css"].to_s.html_safe %>
<%= Rails.application.assets["scaffolds.css"].to_s.html_safe %>
<%= Rails.application.assets["listings.css"].to_s.html_safe %>
</style>
<% elsif view_class.include? "credits-" %>
<style>
<%= Rails.application.assets["crayons.css"].to_s.html_safe %>
<%= Rails.application.assets["scaffolds.css"].to_s.html_safe %>
<%= Rails.application.assets["credits.css"].to_s.html_safe %>
</style>
<% elsif view_class.include? "videos-index" %>
<style>
<%= Rails.application.assets["crayons.css"].to_s.html_safe %>
<%= Rails.application.assets["scaffolds.css"].to_s.html_safe %>
<%= Rails.application.assets["video-collection.css"].to_s.html_safe %>
</style>
<% elsif view_class.include? "badges-index" %>
<%= stylesheet_link_tag "crayons", media: "all" %>
<%= stylesheet_link_tag "minimal", media: "all" %>
<style>
<%= Rails.application.assets["badges.css"].to_s.html_safe %>
</style>
<% else %>
<%= stylesheet_link_tag "crayons", media: "all" %>
<%= stylesheet_link_tag "minimal", media: "all" %>
<% end %>
<% end %>
| {
"pile_set_name": "Github"
} |
/*
* Warewolf - Once bitten, there's no going back
* Copyright 2019 by Warewolf Ltd <[email protected]>
* Licensed under GNU Affero General Public License 3.0 or later.
* Some rights reserved.
* Visit our website for more information <http://warewolf.io/>
* AUTHORS <http://warewolf.io/authors.php> , CONTRIBUTORS <http://warewolf.io/contributors.php>
* @license GNU Affero General Public License <http://www.gnu.org/licenses/agpl-3.0.html>
*/
using Dev2.Data.Interfaces;
namespace Dev2.PathOperations {
/// <summary>
/// PBI : 1172
/// Status : New
/// Purpose : To provide the UnZip operation its args
/// </summary>
public class Dev2UnZipOperationTO : IDev2UnZipOperationTO
{
public Dev2UnZipOperationTO(string passwd, bool overwrite) {
ArchivePassword = passwd;
Overwrite = overwrite;
}
public string ArchivePassword {
get;
set;
}
public bool Overwrite
{
get;
set;
}
}
}
| {
"pile_set_name": "Github"
} |
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 Source Code 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "sys/platform.h"
#include "framework/Common.h"
#include "idlib/Heap.h"
#ifndef USE_LIBC_MALLOC
#define USE_LIBC_MALLOC 0
#endif
#ifndef CRASH_ON_STATIC_ALLOCATION
// #define CRASH_ON_STATIC_ALLOCATION
#endif
//===============================================================
//
// idHeap
//
//===============================================================
#define SMALL_HEADER_SIZE ( (intptr_t) ( sizeof( byte ) + sizeof( byte ) ) )
#define MEDIUM_HEADER_SIZE ( (intptr_t) ( sizeof( mediumHeapEntry_s ) + sizeof( byte ) ) )
#define LARGE_HEADER_SIZE ( (intptr_t) ( sizeof( dword * ) + sizeof( byte ) ) )
#define ALIGN_SIZE( bytes ) ( ( (bytes) + ALIGN - 1 ) & ~(ALIGN - 1) )
#define SMALL_ALIGN( bytes ) ( ALIGN_SIZE( (bytes) + SMALL_HEADER_SIZE ) - SMALL_HEADER_SIZE )
#define MEDIUM_SMALLEST_SIZE ( ALIGN_SIZE( 256 ) + ALIGN_SIZE( MEDIUM_HEADER_SIZE ) )
class idHeap {
public:
idHeap( void );
~idHeap( void ); // frees all associated data
void Init( void ); // initialize
void * Allocate( const dword bytes ); // allocate memory
void Free( void *p ); // free memory
void * Allocate16( const dword bytes );// allocate 16 byte aligned memory
void Free16( void *p ); // free 16 byte aligned memory
dword Msize( void *p ); // return size of data block
void Dump( void );
void AllocDefragBlock( void ); // hack for huge renderbumps
private:
enum {
ALIGN = 8 // memory alignment in bytes
};
enum {
INVALID_ALLOC = 0xdd,
SMALL_ALLOC = 0xaa, // small allocation
MEDIUM_ALLOC = 0xbb, // medium allocaction
LARGE_ALLOC = 0xcc // large allocaction
};
struct page_s { // allocation page
void * data; // data pointer to allocated memory
dword dataSize; // number of bytes of memory 'data' points to
page_s * next; // next free page in same page manager
page_s * prev; // used only when allocated
dword largestFree; // this data used by the medium-size heap manager
void * firstFree; // pointer to first free entry
};
struct mediumHeapEntry_s {
page_s * page; // pointer to page
dword size; // size of block
mediumHeapEntry_s * prev; // previous block
mediumHeapEntry_s * next; // next block
mediumHeapEntry_s * prevFree; // previous free block
mediumHeapEntry_s * nextFree; // next free block
dword freeBlock; // non-zero if free block
};
// variables
void * smallFirstFree[256/ALIGN+1]; // small heap allocator lists (for allocs of 1-255 bytes)
page_s * smallCurPage; // current page for small allocations
dword smallCurPageOffset; // byte offset in current page
page_s * smallFirstUsedPage; // first used page of the small heap manager
page_s * mediumFirstFreePage; // first partially free page
page_s * mediumLastFreePage; // last partially free page
page_s * mediumFirstUsedPage; // completely used page
page_s * largeFirstUsedPage; // first page used by the large heap manager
page_s * swapPage;
dword pagesAllocated; // number of pages currently allocated
dword pageSize; // size of one alloc page in bytes
dword pageRequests; // page requests
dword OSAllocs; // number of allocs made to the OS
int c_heapAllocRunningCount;
void *defragBlock; // a single huge block that can be allocated
// at startup, then freed when needed
// methods
page_s * AllocatePage( dword bytes ); // allocate page from the OS
void FreePage( idHeap::page_s *p ); // free an OS allocated page
void * SmallAllocate( dword bytes ); // allocate memory (1-255 bytes) from small heap manager
void SmallFree( void *ptr ); // free memory allocated by small heap manager
void * MediumAllocateFromPage( idHeap::page_s *p, dword sizeNeeded );
void * MediumAllocate( dword bytes ); // allocate memory (256-32768 bytes) from medium heap manager
void MediumFree( void *ptr ); // free memory allocated by medium heap manager
void * LargeAllocate( dword bytes ); // allocate large block from OS directly
void LargeFree( void *ptr ); // free memory allocated by large heap manager
void ReleaseSwappedPages( void );
void FreePageReal( idHeap::page_s *p );
};
/*
================
idHeap::Init
================
*/
void idHeap::Init () {
OSAllocs = 0;
pageRequests = 0;
pageSize = 65536 - sizeof( idHeap::page_s );
pagesAllocated = 0; // reset page allocation counter
largeFirstUsedPage = NULL; // init large heap manager
swapPage = NULL;
memset( smallFirstFree, 0, sizeof(smallFirstFree) ); // init small heap manager
smallFirstUsedPage = NULL;
smallCurPage = AllocatePage( pageSize );
assert( smallCurPage );
smallCurPageOffset = SMALL_ALIGN( 0 );
defragBlock = NULL;
mediumFirstFreePage = NULL; // init medium heap manager
mediumLastFreePage = NULL;
mediumFirstUsedPage = NULL;
c_heapAllocRunningCount = 0;
}
/*
================
idHeap::idHeap
================
*/
idHeap::idHeap( void ) {
Init();
}
/*
================
idHeap::~idHeap
returns all allocated memory back to OS
================
*/
idHeap::~idHeap( void ) {
idHeap::page_s *p;
if ( smallCurPage ) {
FreePage( smallCurPage ); // free small-heap current allocation page
}
p = smallFirstUsedPage; // free small-heap allocated pages
while( p ) {
idHeap::page_s *next = p->next;
FreePage( p );
p= next;
}
p = largeFirstUsedPage; // free large-heap allocated pages
while( p ) {
idHeap::page_s *next = p->next;
FreePage( p );
p = next;
}
p = mediumFirstFreePage; // free medium-heap allocated pages
while( p ) {
idHeap::page_s *next = p->next;
FreePage( p );
p = next;
}
p = mediumFirstUsedPage; // free medium-heap allocated completely used pages
while( p ) {
idHeap::page_s *next = p->next;
FreePage( p );
p = next;
}
ReleaseSwappedPages();
if ( defragBlock ) {
free( defragBlock );
}
assert( pagesAllocated == 0 );
}
/*
================
idHeap::AllocDefragBlock
================
*/
void idHeap::AllocDefragBlock( void ) {
int size = 0x40000000;
if ( defragBlock ) {
return;
}
while( 1 ) {
defragBlock = malloc( size );
if ( defragBlock ) {
break;
}
size >>= 1;
}
idLib::common->Printf( "Allocated a %i mb defrag block\n", size / (1024*1024) );
}
/*
================
idHeap::Allocate
================
*/
void *idHeap::Allocate( const dword bytes ) {
if ( !bytes ) {
return NULL;
}
c_heapAllocRunningCount++;
#if USE_LIBC_MALLOC
return malloc( bytes );
#else
if ( !(bytes & ~255) ) {
return SmallAllocate( bytes );
}
if ( !(bytes & ~32767) ) {
return MediumAllocate( bytes );
}
return LargeAllocate( bytes );
#endif
}
/*
================
idHeap::Free
================
*/
void idHeap::Free( void *p ) {
if ( !p ) {
return;
}
c_heapAllocRunningCount--;
#if USE_LIBC_MALLOC
free( p );
#else
switch( ((byte *)(p))[-1] ) {
case SMALL_ALLOC: {
SmallFree( p );
break;
}
case MEDIUM_ALLOC: {
MediumFree( p );
break;
}
case LARGE_ALLOC: {
LargeFree( p );
break;
}
default: {
idLib::common->FatalError( "idHeap::Free: invalid memory block" );
break;
}
}
#endif
}
/*
================
idHeap::Allocate16
================
*/
void *idHeap::Allocate16( const dword bytes ) {
byte *ptr, *alignedPtr;
ptr = (byte *) malloc( bytes + 16 + sizeof(intptr_t) );
if ( !ptr ) {
if ( defragBlock ) {
idLib::common->Printf( "Freeing defragBlock on alloc of %i.\n", bytes );
free( defragBlock );
defragBlock = NULL;
ptr = (byte *) malloc( bytes + 16 + sizeof(intptr_t) );
AllocDefragBlock();
}
if ( !ptr ) {
common->FatalError( "malloc failure for %i", bytes );
}
}
alignedPtr = (byte *) ( ( ( (intptr_t) ptr ) + 15) & ~15 );
if ( alignedPtr - ptr < sizeof(intptr_t) ) {
alignedPtr += 16;
}
*((intptr_t *)(alignedPtr - sizeof(intptr_t))) = (intptr_t) ptr;
return (void *) alignedPtr;
}
/*
================
idHeap::Free16
================
*/
void idHeap::Free16( void *p ) {
free( (void *) *((intptr_t *) (( (byte *) p ) - sizeof(intptr_t))) );
}
/*
================
idHeap::Msize
returns size of allocated memory block
p = pointer to memory block
Notes: size may not be the same as the size in the original
allocation request (due to block alignment reasons).
================
*/
dword idHeap::Msize( void *p ) {
if ( !p ) {
return 0;
}
#if USE_LIBC_MALLOC
#ifdef _WIN32
return _msize( p );
#else
return 0;
#endif
#else
switch( ((byte *)(p))[-1] ) {
case SMALL_ALLOC: {
return SMALL_ALIGN( ((byte *)(p))[-SMALL_HEADER_SIZE] * ALIGN );
}
case MEDIUM_ALLOC: {
return ((mediumHeapEntry_s *)(((byte *)(p)) - ALIGN_SIZE( MEDIUM_HEADER_SIZE )))->size - ALIGN_SIZE( MEDIUM_HEADER_SIZE );
}
case LARGE_ALLOC: {
return ((idHeap::page_s*)(*((intptr_t *)(((byte *)p) - ALIGN_SIZE( LARGE_HEADER_SIZE )))))->dataSize - ALIGN_SIZE( LARGE_HEADER_SIZE );
}
default: {
idLib::common->FatalError( "idHeap::Msize: invalid memory block" );
return 0;
}
}
#endif
}
/*
================
idHeap::Dump
dump contents of the heap
================
*/
void idHeap::Dump( void ) {
idHeap::page_s *pg;
for ( pg = smallFirstUsedPage; pg; pg = pg->next ) {
idLib::common->Printf( "%p bytes %-8d (in use by small heap)\n", pg->data, pg->dataSize);
}
if ( smallCurPage ) {
pg = smallCurPage;
idLib::common->Printf( "%p bytes %-8d (small heap active page)\n", pg->data, pg->dataSize );
}
for ( pg = mediumFirstUsedPage; pg; pg = pg->next ) {
idLib::common->Printf( "%p bytes %-8d (completely used by medium heap)\n", pg->data, pg->dataSize );
}
for ( pg = mediumFirstFreePage; pg; pg = pg->next ) {
idLib::common->Printf( "%p bytes %-8d (partially used by medium heap)\n", pg->data, pg->dataSize );
}
for ( pg = largeFirstUsedPage; pg; pg = pg->next ) {
idLib::common->Printf( "%p bytes %-8d (fully used by large heap)\n", pg->data, pg->dataSize );
}
idLib::common->Printf( "pages allocated : %d\n", pagesAllocated );
}
/*
================
idHeap::FreePageReal
frees page to be used by the OS
p = page to free
================
*/
void idHeap::FreePageReal( idHeap::page_s *p ) {
assert( p );
::free( p );
}
/*
================
idHeap::ReleaseSwappedPages
releases the swap page to OS
================
*/
void idHeap::ReleaseSwappedPages () {
if ( swapPage ) {
FreePageReal( swapPage );
}
swapPage = NULL;
}
/*
================
idHeap::AllocatePage
allocates memory from the OS
bytes = page size in bytes
returns pointer to page
================
*/
idHeap::page_s* idHeap::AllocatePage( dword bytes ) {
idHeap::page_s* p;
pageRequests++;
if ( swapPage && swapPage->dataSize == bytes ) { // if we've got a swap page somewhere
p = swapPage;
swapPage = NULL;
}
else {
dword size;
size = bytes + sizeof(idHeap::page_s);
p = (idHeap::page_s *) ::malloc( size + ALIGN - 1 );
if ( !p ) {
if ( defragBlock ) {
idLib::common->Printf( "Freeing defragBlock on alloc of %i.\n", size + ALIGN - 1 );
free( defragBlock );
defragBlock = NULL;
p = (idHeap::page_s *) ::malloc( size + ALIGN - 1 );
AllocDefragBlock();
}
if ( !p ) {
common->FatalError( "malloc failure for %i", bytes );
}
}
p->data = (void *) ALIGN_SIZE( (intptr_t)((byte *)(p)) + sizeof( idHeap::page_s ) );
p->dataSize = size - sizeof(idHeap::page_s);
p->firstFree = NULL;
p->largestFree = 0;
OSAllocs++;
}
p->prev = NULL;
p->next = NULL;
pagesAllocated++;
return p;
}
/*
================
idHeap::FreePage
frees a page back to the operating system
p = pointer to page
================
*/
void idHeap::FreePage( idHeap::page_s *p ) {
assert( p );
if ( p->dataSize == pageSize && !swapPage ) { // add to swap list?
swapPage = p;
}
else {
FreePageReal( p );
}
pagesAllocated--;
}
//===============================================================
//
// small heap code
//
//===============================================================
/*
================
idHeap::SmallAllocate
allocate memory (1-255 bytes) from the small heap manager
bytes = number of bytes to allocate
returns pointer to allocated memory
================
*/
void *idHeap::SmallAllocate( dword bytes ) {
// we need the at least sizeof( dword ) bytes for the free list
if ( bytes < sizeof( intptr_t ) ) {
bytes = sizeof( intptr_t );
}
// increase the number of bytes if necessary to make sure the next small allocation is aligned
bytes = SMALL_ALIGN( bytes );
byte *smallBlock = (byte *)(smallFirstFree[bytes / ALIGN]);
if ( smallBlock ) {
intptr_t *link = (intptr_t *)(smallBlock + SMALL_HEADER_SIZE);
smallBlock[1] = SMALL_ALLOC; // allocation identifier
smallFirstFree[bytes / ALIGN] = (void *)(*link);
return (void *)(link);
}
dword bytesLeft = (size_t)(pageSize) - smallCurPageOffset;
// if we need to allocate a new page
if ( bytes >= bytesLeft ) {
smallCurPage->next = smallFirstUsedPage;
smallFirstUsedPage = smallCurPage;
smallCurPage = AllocatePage( pageSize );
if ( !smallCurPage ) {
return NULL;
}
// make sure the first allocation is aligned
smallCurPageOffset = SMALL_ALIGN( 0 );
}
smallBlock = ((byte *)smallCurPage->data) + smallCurPageOffset;
smallBlock[0] = (byte)(bytes / ALIGN); // write # of bytes/ALIGN
smallBlock[1] = SMALL_ALLOC; // allocation identifier
smallCurPageOffset += bytes + SMALL_HEADER_SIZE; // increase the offset on the current page
return ( smallBlock + SMALL_HEADER_SIZE ); // skip the first two bytes
}
/*
================
idHeap::SmallFree
frees a block of memory allocated by SmallAllocate() call
data = pointer to block of memory
================
*/
void idHeap::SmallFree( void *ptr ) {
((byte *)(ptr))[-1] = INVALID_ALLOC;
byte *d = ( (byte *)ptr ) - SMALL_HEADER_SIZE;
intptr_t *link = (intptr_t *)ptr;
// index into the table with free small memory blocks
dword ix = *d;
// check if the index is correct
if ( ix > (256 / ALIGN) ) {
idLib::common->FatalError( "SmallFree: invalid memory block" );
}
*link = (intptr_t)smallFirstFree[ix]; // write next index
smallFirstFree[ix] = (void *)d; // link
}
//===============================================================
//
// medium heap code
//
// Medium-heap allocated pages not returned to OS until heap destructor
// called (re-used instead on subsequent medium-size malloc requests).
//
//===============================================================
/*
================
idHeap::MediumAllocateFromPage
performs allocation using the medium heap manager from a given page
p = page
sizeNeeded = # of bytes needed
returns pointer to allocated memory
================
*/
void *idHeap::MediumAllocateFromPage( idHeap::page_s *p, dword sizeNeeded ) {
mediumHeapEntry_s *best,*nw = NULL;
byte *ret;
best = (mediumHeapEntry_s *)(p->firstFree); // first block is largest
assert( best );
assert( best->size == p->largestFree );
assert( best->size >= sizeNeeded );
// if we can allocate another block from this page after allocating sizeNeeded bytes
if ( best->size >= (dword)( sizeNeeded + MEDIUM_SMALLEST_SIZE ) ) {
nw = (mediumHeapEntry_s *)((byte *)best + best->size - sizeNeeded);
nw->page = p;
nw->prev = best;
nw->next = best->next;
nw->prevFree = NULL;
nw->nextFree = NULL;
nw->size = sizeNeeded;
nw->freeBlock = 0; // used block
if ( best->next ) {
best->next->prev = nw;
}
best->next = nw;
best->size -= sizeNeeded;
p->largestFree = best->size;
}
else {
if ( best->prevFree ) {
best->prevFree->nextFree = best->nextFree;
}
else {
p->firstFree = (void *)best->nextFree;
}
if ( best->nextFree ) {
best->nextFree->prevFree = best->prevFree;
}
best->prevFree = NULL;
best->nextFree = NULL;
best->freeBlock = 0; // used block
nw = best;
p->largestFree = 0;
}
ret = (byte *)(nw) + ALIGN_SIZE( MEDIUM_HEADER_SIZE );
ret[-1] = MEDIUM_ALLOC; // allocation identifier
return (void *)(ret);
}
/*
================
idHeap::MediumAllocate
allocate memory (256-32768 bytes) from medium heap manager
bytes = number of bytes to allocate
returns pointer to allocated memory
================
*/
void *idHeap::MediumAllocate( dword bytes ) {
idHeap::page_s *p;
void *data;
dword sizeNeeded = ALIGN_SIZE( bytes ) + ALIGN_SIZE( MEDIUM_HEADER_SIZE );
// find first page with enough space
for ( p = mediumFirstFreePage; p; p = p->next ) {
if ( p->largestFree >= sizeNeeded ) {
break;
}
}
if ( !p ) { // need to allocate new page?
p = AllocatePage( pageSize );
if ( !p ) {
return NULL; // malloc failure!
}
p->prev = NULL;
p->next = mediumFirstFreePage;
if (p->next) {
p->next->prev = p;
}
else {
mediumLastFreePage = p;
}
mediumFirstFreePage = p;
p->largestFree = pageSize;
p->firstFree = (void *)p->data;
mediumHeapEntry_s *e;
e = (mediumHeapEntry_s *)(p->firstFree);
e->page = p;
// make sure ((byte *)e + e->size) is aligned
e->size = pageSize & ~(ALIGN - 1);
e->prev = NULL;
e->next = NULL;
e->prevFree = NULL;
e->nextFree = NULL;
e->freeBlock = 1;
}
data = MediumAllocateFromPage( p, sizeNeeded ); // allocate data from page
// if the page can no longer serve memory, move it away from free list
// (so that it won't slow down the later alloc queries)
// this modification speeds up the pageWalk from O(N) to O(sqrt(N))
// a call to free may swap this page back to the free list
if ( p->largestFree < MEDIUM_SMALLEST_SIZE ) {
if ( p == mediumLastFreePage ) {
mediumLastFreePage = p->prev;
}
if ( p == mediumFirstFreePage ) {
mediumFirstFreePage = p->next;
}
if ( p->prev ) {
p->prev->next = p->next;
}
if ( p->next ) {
p->next->prev = p->prev;
}
// link to "completely used" list
p->prev = NULL;
p->next = mediumFirstUsedPage;
if ( p->next ) {
p->next->prev = p;
}
mediumFirstUsedPage = p;
return data;
}
// re-order linked list (so that next malloc query starts from current
// matching block) -- this speeds up both the page walks and block walks
if ( p != mediumFirstFreePage ) {
assert( mediumLastFreePage );
assert( mediumFirstFreePage );
assert( p->prev);
mediumLastFreePage->next = mediumFirstFreePage;
mediumFirstFreePage->prev = mediumLastFreePage;
mediumLastFreePage = p->prev;
p->prev->next = NULL;
p->prev = NULL;
mediumFirstFreePage = p;
}
return data;
}
/*
================
idHeap::MediumFree
frees a block allocated by the medium heap manager
ptr = pointer to data block
================
*/
void idHeap::MediumFree( void *ptr ) {
((byte *)(ptr))[-1] = INVALID_ALLOC;
mediumHeapEntry_s *e = (mediumHeapEntry_s *)((byte *)ptr - ALIGN_SIZE( MEDIUM_HEADER_SIZE ));
idHeap::page_s *p = e->page;
bool isInFreeList;
isInFreeList = p->largestFree >= MEDIUM_SMALLEST_SIZE;
assert( e->size );
assert( e->freeBlock == 0 );
mediumHeapEntry_s *prev = e->prev;
// if the previous block is free we can merge
if ( prev && prev->freeBlock ) {
prev->size += e->size;
prev->next = e->next;
if ( e->next ) {
e->next->prev = prev;
}
e = prev;
}
else {
e->prevFree = NULL; // link to beginning of free list
e->nextFree = (mediumHeapEntry_s *)p->firstFree;
if ( e->nextFree ) {
assert( !(e->nextFree->prevFree) );
e->nextFree->prevFree = e;
}
p->firstFree = e;
p->largestFree = e->size;
e->freeBlock = 1; // mark block as free
}
mediumHeapEntry_s *next = e->next;
// if the next block is free we can merge
if ( next && next->freeBlock ) {
e->size += next->size;
e->next = next->next;
if ( next->next ) {
next->next->prev = e;
}
if ( next->prevFree ) {
next->prevFree->nextFree = next->nextFree;
}
else {
assert( next == p->firstFree );
p->firstFree = next->nextFree;
}
if ( next->nextFree ) {
next->nextFree->prevFree = next->prevFree;
}
}
if ( p->firstFree ) {
p->largestFree = ((mediumHeapEntry_s *)(p->firstFree))->size;
}
else {
p->largestFree = 0;
}
// did e become the largest block of the page ?
if ( e->size > p->largestFree ) {
assert( e != p->firstFree );
p->largestFree = e->size;
if ( e->prevFree ) {
e->prevFree->nextFree = e->nextFree;
}
if ( e->nextFree ) {
e->nextFree->prevFree = e->prevFree;
}
e->nextFree = (mediumHeapEntry_s *)p->firstFree;
e->prevFree = NULL;
if ( e->nextFree ) {
e->nextFree->prevFree = e;
}
p->firstFree = e;
}
// if page wasn't in free list (because it was near-full), move it back there
if ( !isInFreeList ) {
// remove from "completely used" list
if ( p->prev ) {
p->prev->next = p->next;
}
if ( p->next ) {
p->next->prev = p->prev;
}
if ( p == mediumFirstUsedPage ) {
mediumFirstUsedPage = p->next;
}
p->next = NULL;
p->prev = mediumLastFreePage;
if ( mediumLastFreePage ) {
mediumLastFreePage->next = p;
}
mediumLastFreePage = p;
if ( !mediumFirstFreePage ) {
mediumFirstFreePage = p;
}
}
}
//===============================================================
//
// large heap code
//
//===============================================================
/*
================
idHeap::LargeAllocate
allocates a block of memory from the operating system
bytes = number of bytes to allocate
returns pointer to allocated memory
================
*/
void *idHeap::LargeAllocate( dword bytes ) {
idHeap::page_s *p = AllocatePage( bytes + ALIGN_SIZE( LARGE_HEADER_SIZE ) );
assert( p );
if ( !p ) {
return NULL;
}
byte * d = (byte*)(p->data) + ALIGN_SIZE( LARGE_HEADER_SIZE );
intptr_t * dw = (intptr_t*)(d - ALIGN_SIZE( LARGE_HEADER_SIZE ));
dw[0] = (intptr_t)p; // write pointer back to page table
d[-1] = LARGE_ALLOC; // allocation identifier
// link to 'large used page list'
p->prev = NULL;
p->next = largeFirstUsedPage;
if ( p->next ) {
p->next->prev = p;
}
largeFirstUsedPage = p;
return (void *)(d);
}
/*
================
idHeap::LargeFree
frees a block of memory allocated by the 'large memory allocator'
p = pointer to allocated memory
================
*/
void idHeap::LargeFree( void *ptr) {
idHeap::page_s* pg;
((byte *)(ptr))[-1] = INVALID_ALLOC;
// get page pointer
pg = (idHeap::page_s *)(*((intptr_t *)(((byte *)ptr) - ALIGN_SIZE( LARGE_HEADER_SIZE ))));
// unlink from doubly linked list
if ( pg->prev ) {
pg->prev->next = pg->next;
}
if ( pg->next ) {
pg->next->prev = pg->prev;
}
if ( pg == largeFirstUsedPage ) {
largeFirstUsedPage = pg->next;
}
pg->next = pg->prev = NULL;
FreePage(pg);
}
//===============================================================
//
// memory allocation all in one place
//
//===============================================================
#undef new
static idHeap * mem_heap = NULL;
static memoryStats_t mem_total_allocs = { 0, 0x0fffffff, -1, 0 };
static memoryStats_t mem_frame_allocs;
static memoryStats_t mem_frame_frees;
/*
==================
Mem_ClearFrameStats
==================
*/
void Mem_ClearFrameStats( void ) {
mem_frame_allocs.num = mem_frame_frees.num = 0;
mem_frame_allocs.minSize = mem_frame_frees.minSize = 0x0fffffff;
mem_frame_allocs.maxSize = mem_frame_frees.maxSize = -1;
mem_frame_allocs.totalSize = mem_frame_frees.totalSize = 0;
}
/*
==================
Mem_GetFrameStats
==================
*/
void Mem_GetFrameStats( memoryStats_t &allocs, memoryStats_t &frees ) {
allocs = mem_frame_allocs;
frees = mem_frame_frees;
}
/*
==================
Mem_GetStats
==================
*/
void Mem_GetStats( memoryStats_t &stats ) {
stats = mem_total_allocs;
}
/*
==================
Mem_UpdateStats
==================
*/
void Mem_UpdateStats( memoryStats_t &stats, int size ) {
stats.num++;
if ( size < stats.minSize ) {
stats.minSize = size;
}
if ( size > stats.maxSize ) {
stats.maxSize = size;
}
stats.totalSize += size;
}
/*
==================
Mem_UpdateAllocStats
==================
*/
void Mem_UpdateAllocStats( int size ) {
Mem_UpdateStats( mem_frame_allocs, size );
Mem_UpdateStats( mem_total_allocs, size );
}
/*
==================
Mem_UpdateFreeStats
==================
*/
void Mem_UpdateFreeStats( int size ) {
Mem_UpdateStats( mem_frame_frees, size );
mem_total_allocs.num--;
mem_total_allocs.totalSize -= size;
}
#ifndef ID_DEBUG_MEMORY
/*
==================
Mem_Alloc
==================
*/
void *Mem_Alloc( const int size ) {
if ( !size ) {
return NULL;
}
if ( !mem_heap ) {
#ifdef CRASH_ON_STATIC_ALLOCATION
*((int*)0x0) = 1;
#endif
return malloc( size );
}
void *mem = mem_heap->Allocate( size );
Mem_UpdateAllocStats( mem_heap->Msize( mem ) );
return mem;
}
/*
==================
Mem_Free
==================
*/
void Mem_Free( void *ptr ) {
if ( !ptr ) {
return;
}
if ( !mem_heap ) {
#ifdef CRASH_ON_STATIC_ALLOCATION
*((int*)0x0) = 1;
#endif
free( ptr );
return;
}
Mem_UpdateFreeStats( mem_heap->Msize( ptr ) );
mem_heap->Free( ptr );
}
/*
==================
Mem_Alloc16
==================
*/
void *Mem_Alloc16( const int size ) {
if ( !size ) {
return NULL;
}
if ( !mem_heap ) {
#ifdef CRASH_ON_STATIC_ALLOCATION
*((int*)0x0) = 1;
#endif
return malloc( size );
}
void *mem = mem_heap->Allocate16( size );
// make sure the memory is 16 byte aligned
assert( ( ((intptr_t)mem) & 15) == 0 );
return mem;
}
/*
==================
Mem_Free16
==================
*/
void Mem_Free16( void *ptr ) {
if ( !ptr ) {
return;
}
if ( !mem_heap ) {
#ifdef CRASH_ON_STATIC_ALLOCATION
*((int*)0x0) = 1;
#endif
free( ptr );
return;
}
// make sure the memory is 16 byte aligned
assert( ( ((intptr_t)ptr) & 15) == 0 );
mem_heap->Free16( ptr );
}
/*
==================
Mem_ClearedAlloc
==================
*/
void *Mem_ClearedAlloc( const int size ) {
void *mem = Mem_Alloc( size );
SIMDProcessor->Memset( mem, 0, size );
return mem;
}
/*
==================
Mem_ClearedAlloc
==================
*/
void Mem_AllocDefragBlock( void ) {
mem_heap->AllocDefragBlock();
}
/*
==================
Mem_CopyString
==================
*/
char *Mem_CopyString( const char *in ) {
char *out;
out = (char *)Mem_Alloc( strlen(in) + 1 );
strcpy( out, in );
return out;
}
/*
==================
Mem_Dump_f
==================
*/
void Mem_Dump_f( const idCmdArgs &args ) {
}
/*
==================
Mem_DumpCompressed_f
==================
*/
void Mem_DumpCompressed_f( const idCmdArgs &args ) {
}
/*
==================
Mem_Init
==================
*/
void Mem_Init( void ) {
mem_heap = new idHeap;
Mem_ClearFrameStats();
}
/*
==================
Mem_Shutdown
==================
*/
void Mem_Shutdown( void ) {
idHeap *m = mem_heap;
mem_heap = NULL;
delete m;
}
/*
==================
Mem_EnableLeakTest
==================
*/
void Mem_EnableLeakTest( const char *name ) {
}
#else /* !ID_DEBUG_MEMORY */
#undef Mem_Alloc
#undef Mem_ClearedAlloc
#undef Com_ClearedReAlloc
#undef Mem_Free
#undef Mem_CopyString
#undef Mem_Alloc16
#undef Mem_Free16
// size of this struct must be a multiple of 16 bytes
typedef struct debugMemory_s {
const char * fileName;
int lineNumber;
int frameNumber;
int size;
struct debugMemory_s * prev;
struct debugMemory_s * next;
} debugMemory_t;
static debugMemory_t * mem_debugMemory = NULL;
static char mem_leakName[256] = "";
/*
==================
Mem_CleanupFileName
==================
*/
const char *Mem_CleanupFileName( const char *fileName ) {
int i1, i2;
idStr newFileName;
static char newFileNames[4][MAX_STRING_CHARS];
static int index;
newFileName = fileName;
newFileName.BackSlashesToSlashes();
i1 = newFileName.Find( "neo", false );
if ( i1 >= 0 ) {
i1 = newFileName.Find( "/", false, i1 );
newFileName = newFileName.Right( newFileName.Length() - ( i1 + 1 ) );
}
while( 1 ) {
i1 = newFileName.Find( "/../" );
if ( i1 <= 0 ) {
break;
}
i2 = i1 - 1;
while( i2 > 1 && newFileName[i2-1] != '/' ) {
i2--;
}
newFileName = newFileName.Left( i2 - 1 ) + newFileName.Right( newFileName.Length() - ( i1 + 4 ) );
}
index = ( index + 1 ) & 3;
strncpy( newFileNames[index], newFileName.c_str(), sizeof( newFileNames[index] ) );
return newFileNames[index];
}
/*
==================
Mem_Dump
==================
*/
void Mem_Dump( const char *fileName ) {
int i, numBlocks, totalSize;
char dump[32], *ptr;
debugMemory_t *b;
idStr module, funcName;
FILE *f;
f = fopen( fileName, "wb" );
if ( !f ) {
return;
}
totalSize = 0;
for ( numBlocks = 0, b = mem_debugMemory; b; b = b->next, numBlocks++ ) {
ptr = ((char *) b) + sizeof(debugMemory_t);
totalSize += b->size;
for ( i = 0; i < (sizeof(dump)-1) && i < b->size; i++) {
if ( ptr[i] >= 32 && ptr[i] < 127 ) {
dump[i] = ptr[i];
} else {
dump[i] = '_';
}
}
dump[i] = '\0';
if ( ( b->size >> 10 ) != 0 ) {
fprintf( f, "size: %6d KB: %s, line: %d [%s]\r\n", ( b->size >> 10 ), Mem_CleanupFileName(b->fileName), b->lineNumber, dump );
}
else {
fprintf( f, "size: %7d B: %s, line: %d [%s], call stack: %s\r\n", b->size, Mem_CleanupFileName(b->fileName), b->lineNumber, dump );
}
}
fprintf( f, "%8d total memory blocks allocated\r\n", numBlocks );
fprintf( f, "%8d KB memory allocated\r\n", ( totalSize >> 10 ) );
fclose( f );
}
/*
==================
Mem_Dump_f
==================
*/
void Mem_Dump_f( const idCmdArgs &args ) {
const char *fileName;
if ( args.Argc() >= 2 ) {
fileName = args.Argv( 1 );
}
else {
fileName = "memorydump.txt";
}
Mem_Dump( fileName );
}
/*
==================
Mem_DumpCompressed
==================
*/
typedef struct allocInfo_s {
const char * fileName;
int lineNumber;
int size;
int numAllocs;
struct allocInfo_s * next;
} allocInfo_t;
typedef enum {
MEMSORT_SIZE,
MEMSORT_LOCATION,
MEMSORT_NUMALLOCS,
} memorySortType_t;
void Mem_DumpCompressed( const char *fileName, memorySortType_t memSort, int numFrames ) {
int numBlocks, totalSize, r, j;
debugMemory_t *b;
allocInfo_t *a, *nexta, *allocInfo = NULL, *sortedAllocInfo = NULL, *prevSorted, *nextSorted;
idStr module, funcName;
FILE *f;
// build list with memory allocations
totalSize = 0;
numBlocks = 0;
for ( b = mem_debugMemory; b; b = b->next ) {
if ( numFrames && b->frameNumber < idLib::frameNumber - numFrames ) {
continue;
}
numBlocks++;
totalSize += b->size;
// search for an allocation from the same source location
for ( a = allocInfo; a; a = a->next ) {
if ( a->lineNumber != b->lineNumber ) {
continue;
}
if ( j < MAX_CALLSTACK_DEPTH ) {
continue;
}
if ( idStr::Cmp( a->fileName, b->fileName ) != 0 ) {
continue;
}
a->numAllocs++;
a->size += b->size;
break;
}
// if this is an allocation from a new source location
if ( !a ) {
a = (allocInfo_t *) ::malloc( sizeof( allocInfo_t ) );
a->fileName = b->fileName;
a->lineNumber = b->lineNumber;
a->size = b->size;
a->numAllocs = 1;
a->next = allocInfo;
allocInfo = a;
}
}
// sort list
for ( a = allocInfo; a; a = nexta ) {
nexta = a->next;
prevSorted = NULL;
switch( memSort ) {
// sort on size
case MEMSORT_SIZE: {
for ( nextSorted = sortedAllocInfo; nextSorted; nextSorted = nextSorted->next ) {
if ( a->size > nextSorted->size ) {
break;
}
prevSorted = nextSorted;
}
break;
}
// sort on file name and line number
case MEMSORT_LOCATION: {
for ( nextSorted = sortedAllocInfo; nextSorted; nextSorted = nextSorted->next ) {
r = idStr::Cmp( Mem_CleanupFileName( a->fileName ), Mem_CleanupFileName( nextSorted->fileName ) );
if ( r < 0 || ( r == 0 && a->lineNumber < nextSorted->lineNumber ) ) {
break;
}
prevSorted = nextSorted;
}
break;
}
// sort on the number of allocations
case MEMSORT_NUMALLOCS: {
for ( nextSorted = sortedAllocInfo; nextSorted; nextSorted = nextSorted->next ) {
if ( a->numAllocs > nextSorted->numAllocs ) {
break;
}
prevSorted = nextSorted;
}
break;
}
}
if ( !prevSorted ) {
a->next = sortedAllocInfo;
sortedAllocInfo = a;
}
else {
prevSorted->next = a;
a->next = nextSorted;
}
}
f = fopen( fileName, "wb" );
if ( !f ) {
return;
}
// write list to file
for ( a = sortedAllocInfo; a; a = nexta ) {
nexta = a->next;
fprintf( f, "size: %6d KB, allocs: %5d: %s, line: %d\r\n",
(a->size >> 10), a->numAllocs, Mem_CleanupFileName(a->fileName),
a->lineNumber );
::free( a );
}
fprintf( f, "%8d total memory blocks allocated\r\n", numBlocks );
fprintf( f, "%8d KB memory allocated\r\n", ( totalSize >> 10 ) );
fclose( f );
}
/*
==================
Mem_DumpCompressed_f
==================
*/
void Mem_DumpCompressed_f( const idCmdArgs &args ) {
int argNum;
const char *arg, *fileName;
memorySortType_t memSort = MEMSORT_LOCATION;
int numFrames = 0;
// get cmd-line options
argNum = 1;
arg = args.Argv( argNum );
while( arg[0] == '-' ) {
arg = args.Argv( ++argNum );
if ( idStr::Icmp( arg, "s" ) == 0 ) {
memSort = MEMSORT_SIZE;
} else if ( idStr::Icmp( arg, "l" ) == 0 ) {
memSort = MEMSORT_LOCATION;
} else if ( idStr::Icmp( arg, "a" ) == 0 ) {
memSort = MEMSORT_NUMALLOCS;
} else if ( arg[0] == 'f' ) {
numFrames = atoi( arg + 1 );
} else {
idLib::common->Printf( "memoryDumpCompressed [options] [filename]\n"
"options:\n"
" -s sort on size\n"
" -l sort on location\n"
" -a sort on the number of allocations\n"
" -cs1 sort on first function on call stack\n"
" -cs2 sort on second function on call stack\n"
" -cs3 sort on third function on call stack\n"
" -f<X> only report allocations the last X frames\n"
"By default the memory allocations are sorted on location.\n"
"By default a 'memorydump.txt' is written if no file name is specified.\n" );
return;
}
arg = args.Argv( ++argNum );
}
if ( argNum >= args.Argc() ) {
fileName = "memorydump.txt";
} else {
fileName = arg;
}
Mem_DumpCompressed( fileName, memSort, numFrames );
}
/*
==================
Mem_AllocDebugMemory
==================
*/
void *Mem_AllocDebugMemory( const int size, const char *fileName, const int lineNumber, const bool align16 ) {
void *p;
debugMemory_t *m;
if ( !size ) {
return NULL;
}
if ( !mem_heap ) {
#ifdef CRASH_ON_STATIC_ALLOCATION
*((int*)0x0) = 1;
#endif
// NOTE: set a breakpoint here to find memory allocations before mem_heap is initialized
return malloc( size );
}
if ( align16 ) {
p = mem_heap->Allocate16( size + sizeof( debugMemory_t ) );
}
else {
p = mem_heap->Allocate( size + sizeof( debugMemory_t ) );
}
Mem_UpdateAllocStats( size );
m = (debugMemory_t *) p;
m->fileName = fileName;
m->lineNumber = lineNumber;
m->frameNumber = idLib::frameNumber;
m->size = size;
m->next = mem_debugMemory;
m->prev = NULL;
if ( mem_debugMemory ) {
mem_debugMemory->prev = m;
}
mem_debugMemory = m;
return ( ( (byte *) p ) + sizeof( debugMemory_t ) );
}
/*
==================
Mem_FreeDebugMemory
==================
*/
void Mem_FreeDebugMemory( void *p, const char *fileName, const int lineNumber, const bool align16 ) {
debugMemory_t *m;
if ( !p ) {
return;
}
if ( !mem_heap ) {
#ifdef CRASH_ON_STATIC_ALLOCATION
*((int*)0x0) = 1;
#endif
// NOTE: set a breakpoint here to find memory being freed before mem_heap is initialized
free( p );
return;
}
m = (debugMemory_t *) ( ( (byte *) p ) - sizeof( debugMemory_t ) );
if ( m->size < 0 ) {
idLib::common->FatalError( "memory freed twice" );
}
Mem_UpdateFreeStats( m->size );
if ( m->next ) {
m->next->prev = m->prev;
}
if ( m->prev ) {
m->prev->next = m->next;
}
else {
mem_debugMemory = m->next;
}
m->fileName = fileName;
m->lineNumber = lineNumber;
m->frameNumber = idLib::frameNumber;
m->size = -m->size;
if ( align16 ) {
mem_heap->Free16( m );
}
else {
mem_heap->Free( m );
}
}
/*
==================
Mem_Alloc
==================
*/
void *Mem_Alloc( const int size, const char *fileName, const int lineNumber ) {
if ( !size ) {
return NULL;
}
return Mem_AllocDebugMemory( size, fileName, lineNumber, false );
}
/*
==================
Mem_Free
==================
*/
void Mem_Free( void *ptr, const char *fileName, const int lineNumber ) {
if ( !ptr ) {
return;
}
Mem_FreeDebugMemory( ptr, fileName, lineNumber, false );
}
/*
==================
Mem_Alloc16
==================
*/
void *Mem_Alloc16( const int size, const char *fileName, const int lineNumber ) {
if ( !size ) {
return NULL;
}
void *mem = Mem_AllocDebugMemory( size, fileName, lineNumber, true );
// make sure the memory is 16 byte aligned
assert( ( ((int)mem) & 15) == 0 );
return mem;
}
/*
==================
Mem_Free16
==================
*/
void Mem_Free16( void *ptr, const char *fileName, const int lineNumber ) {
if ( !ptr ) {
return;
}
// make sure the memory is 16 byte aligned
assert( ( ((int)ptr) & 15) == 0 );
Mem_FreeDebugMemory( ptr, fileName, lineNumber, true );
}
/*
==================
Mem_ClearedAlloc
==================
*/
void *Mem_ClearedAlloc( const int size, const char *fileName, const int lineNumber ) {
void *mem = Mem_Alloc( size, fileName, lineNumber );
SIMDProcessor->Memset( mem, 0, size );
return mem;
}
/*
==================
Mem_CopyString
==================
*/
char *Mem_CopyString( const char *in, const char *fileName, const int lineNumber ) {
char *out;
out = (char *)Mem_Alloc( strlen(in) + 1, fileName, lineNumber );
strcpy( out, in );
return out;
}
/*
==================
Mem_Init
==================
*/
void Mem_Init( void ) {
mem_heap = new idHeap;
}
/*
==================
Mem_Shutdown
==================
*/
void Mem_Shutdown( void ) {
if ( mem_leakName[0] != '\0' ) {
Mem_DumpCompressed( va( "%s_leak_size.txt", mem_leakName ), MEMSORT_SIZE, 0 );
Mem_DumpCompressed( va( "%s_leak_location.txt", mem_leakName ), MEMSORT_LOCATION, 0 );
}
idHeap *m = mem_heap;
mem_heap = NULL;
delete m;
}
/*
==================
Mem_EnableLeakTest
==================
*/
void Mem_EnableLeakTest( const char *name ) {
idStr::Copynz( mem_leakName, name, sizeof( mem_leakName ) );
}
#endif /* !ID_DEBUG_MEMORY */
| {
"pile_set_name": "Github"
} |
tags/bug121_var_multiple_i_input_custom.re:9:2: error: overlapping trailing contexts need multiple context markers, use '-t, --tags' option and '/*!stags:re2c ... */' directive
| {
"pile_set_name": "Github"
} |
{
"incident": {
"action": {
"Unknown": {}
},
"actor": {
"external": {
"country": [
"US"
],
"motive": [
"Ideology"
],
"variety": [
"Activist"
]
}
},
"asset": {
"assets": [
{
"variety": "S - Unknown"
}
]
},
"attribute": {
"availability": {
"duration": {},
"notes": "test",
"variety": [
"Loss"
]
}
},
"discovery_method": "Int - unknown",
"incident_id": "test",
"schema_version": "1.3",
"security_incident": "Confirmed",
"timeline": {
"incident": {
"year": 2014
}
}
},
"message": "attribute.availability.duration is empty. test should fail.",
"should": "fail"
} | {
"pile_set_name": "Github"
} |
--- third_party/swiftshader/third_party/llvm-7.0/configs/linux/include/llvm/Config/config.h.orig 2019-04-20 12:09:44 UTC
+++ third_party/swiftshader/third_party/llvm-7.0/configs/linux/include/llvm/Config/config.h
@@ -8,15 +8,15 @@
#define BUG_REPORT_URL "https://bugs.llvm.org/"
/* Define to 1 to enable backtraces, and to 0 otherwise. */
-/* #undef ENABLE_BACKTRACES */
+#define ENABLE_BACKTRACES 1
/* Define to 1 to enable crash overrides, and to 0 otherwise. */
-/* #undef ENABLE_CRASH_OVERRIDES */
+#define ENABLE_CRASH_OVERRIDES 1
/* Define to 1 if you have the `backtrace' function. */
-/* #undef HAVE_BACKTRACE */
+#define HAVE_BACKTRACE TRUE
-/* #undef BACKTRACE_HEADER */
+#define BACKTRACE_HEADER <execinfo.h>
/* Define to 1 if you have the <CrashReporterClient.h> header file. */
/* #undef HAVE_CRASHREPORTERCLIENT_H */
@@ -26,7 +26,7 @@
/* Define to 1 if you have the declaration of `arc4random', and to 0 if you
don't. */
-#define HAVE_DECL_ARC4RANDOM 0
+#define HAVE_DECL_ARC4RANDOM 1
/* Define to 1 if you have the declaration of `FE_ALL_EXCEPT', and to 0 if you
don't. */
@@ -50,7 +50,7 @@
#define HAVE_DLOPEN 1
/* Define if dladdr() is available on this platform. */
-/* #undef HAVE_DLADDR */
+#define HAVE_DLADDR 1
/* Define to 1 if you have the <errno.h> header file. */
#define HAVE_ERRNO_H 1
@@ -89,7 +89,7 @@
#define HAVE_ISATTY 1
/* Define to 1 if you have the `edit' library (-ledit). */
-/* #undef HAVE_LIBEDIT */
+#define HAVE_LIBEDIT 1
/* Define to 1 if you have the `pfm' library (-lpfm). */
/* #undef HAVE_LIBPFM */
@@ -107,25 +107,25 @@
/* #undef HAVE_PTHREAD_SETNAME_NP */
/* Define to 1 if you have the `z' library (-lz). */
-/* #undef HAVE_LIBZ */
+#define HAVE_LIBZ 1
/* Define to 1 if you have the <link.h> header file. */
#define HAVE_LINK_H 1
/* Define to 1 if you have the `lseek64' function. */
-#define HAVE_LSEEK64 1
+/* #undef HAVE_LSEEK64 */
/* Define to 1 if you have the <mach/mach.h> header file. */
/* #undef HAVE_MACH_MACH_H */
/* Define to 1 if you have the `mallctl' function. */
-/* #undef HAVE_MALLCTL */
+#define HAVE_MALLCTL 1
/* Define to 1 if you have the `mallinfo' function. */
-#define HAVE_MALLINFO 1
+/* #undef HAVE_MALLINFO */
/* Define to 1 if you have the <malloc.h> header file. */
-#define HAVE_MALLOC_H 1
+/* #undef HAVE_MALLOC_H */
/* Define to 1 if you have the <malloc/malloc.h> header file. */
/* #undef HAVE_MALLOC_MALLOC_H */
@@ -137,7 +137,7 @@
#define HAVE_POSIX_FALLOCATE 1
/* Define to 1 if you have the `posix_spawn' function. */
-/* #undef HAVE_POSIX_SPAWN */
+#define HAVE_POSIX_SPAWN 1
/* Define to 1 if you have the `pread' function. */
#define HAVE_PREAD 1
@@ -158,16 +158,16 @@
#define HAVE_REALPATH 1
/* Define to 1 if you have the `sbrk' function. */
-#define HAVE_SBRK 1
+/* #undef HAVE_SBRK */
/* Define to 1 if you have the `setenv' function. */
#define HAVE_SETENV 1
/* Define to 1 if you have the `sched_getaffinity' function. */
-#define HAVE_SCHED_GETAFFINITY 1
+/* #undef HAVE_SCHED_GETAFFINITY */
/* Define to 1 if you have the `CPU_COUNT' macro. */
-#define HAVE_CPU_COUNT 1
+/* #undef HAVE_CPU_COUNT */
/* Define to 1 if you have the `setrlimit' function. */
#define HAVE_SETRLIMIT 1
@@ -209,13 +209,13 @@
#define HAVE_SYS_TYPES_H 1
/* Define if the setupterm() function is supported this platform. */
-/* #undef HAVE_TERMINFO */
+#define HAVE_TERMINFO 1
/* Define if the xar_open() function is supported this platform. */
/* #undef HAVE_LIBXAR */
/* Define to 1 if you have the <termios.h> header file. */
-/* #undef HAVE_TERMIOS_H */
+#define HAVE_TERMIOS_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
@@ -224,7 +224,7 @@
/* #undef HAVE_VALGRIND_VALGRIND_H */
/* Define to 1 if you have the <zlib.h> header file. */
-/* #undef HAVE_ZLIB_H */
+#define HAVE_ZLIB_H 1
/* Have host's _alloca */
/* #undef HAVE__ALLOCA */
@@ -298,7 +298,7 @@
#elif defined(__arm__)
#define LLVM_DEFAULT_TARGET_TRIPLE "armv7-linux-gnueabihf"
#elif defined(__aarch64__)
-#define LLVM_DEFAULT_TARGET_TRIPLE "aarch64-linux-gnu"
+#define LLVM_DEFAULT_TARGET_TRIPLE "aarch64-portbld-freebsd"
#elif defined(__mips__)
#define LLVM_DEFAULT_TARGET_TRIPLE "mipsel-linux-gnu"
#elif defined(__mips64)
@@ -308,7 +308,7 @@
#endif
/* Define if zlib compression is available */
-#define LLVM_ENABLE_ZLIB 0
+#define LLVM_ENABLE_ZLIB 1
/* Define if overriding target triple is enabled */
/* #undef LLVM_TARGET_TRIPLE_ENV */
| {
"pile_set_name": "Github"
} |
const Lambda = require("aws-sdk/clients/lambda");
const ApiGateway = require("aws-sdk/clients/apigateway");
const CloudFront = require("aws-sdk/clients/cloudfront");
const IAM = require("aws-sdk/clients/iam");
const S3 = require("aws-sdk/clients/s3");
const CloudWatchLogs = require("aws-sdk/clients/cloudwatchlogs");
const { Observable } = require("rxjs");
const pRetry = require("p-retry");
const region = process.env.AWS_REGION || "us-east-1";
const lambda = new Lambda({ region });
const cloudWatchLogs = new CloudWatchLogs({ region });
const apiGateway = new ApiGateway({ region });
const cloudFront = new CloudFront({ region });
const iam = new IAM({ region });
const s3 = new S3({ region });
module.exports.getAllFunctions = async () => {
const functions = [];
let Marker = null;
while (true) {
const { Functions, NextMarker } = await lambda
.listFunctions({ Marker, MaxItems: 10 })
.promise();
Functions.forEach(item => functions.push(item));
if (!NextMarker) {
break;
}
Marker = NextMarker;
}
return functions.sort((a, b) => {
return new Date(b.LastModified).getTime() - new Date(a.LastModified).getTime();
});
};
module.exports.getAllLogGroups = async () => {
const groups = [];
let Marker = null;
while (true) {
const { logGroups, nextToken } = await cloudWatchLogs
.describeLogGroups({ logGroupNamePrefix: "/aws/", limit: 50, nextToken: Marker })
.promise();
logGroups.forEach(item => groups.push(item));
if (!nextToken) {
break;
}
Marker = nextToken;
}
return groups.sort((a, b) => {
return new Date(b.creationTime).getTime() - new Date(a.creationTime).getTime();
});
};
module.exports.getAllApiGateways = async () => {
const gateways = [];
let Marker = null;
while (true) {
const { items, position } = await apiGateway
.getRestApis({ position: Marker, limit: 10 })
.promise();
items.forEach(item => gateways.push(item));
if (!position) {
break;
}
Marker = position;
}
return gateways.sort((a, b) => {
return new Date(b.createdDate).getTime() - new Date(a.createdDate).getTime();
});
};
module.exports.getAllBuckets = async () => {
const { Buckets } = await s3.listBuckets({}).promise();
return Buckets.sort((a, b) => {
return new Date(b.CreationDate).getTime() - new Date(a.CreationDate).getTime();
});
};
module.exports.getAllCloudFrontDistributions = async () => {
const distributions = [];
let Marker = null;
while (true) {
const { DistributionList } = await cloudFront
.listDistributions({ Marker, MaxItems: "20" })
.promise();
const { IsTruncated, Items, NextMarker } = DistributionList;
Items.forEach(item => distributions.push(item));
if (!IsTruncated) {
break;
}
Marker = NextMarker;
}
return distributions.sort((a, b) => {
return new Date(b.LastModifiedTime).getTime() - new Date(a.LastModifiedTime).getTime();
});
};
module.exports.getAllIAMRoles = async () => {
const roles = [];
let Marker = null;
while (true) {
const { Marker: NextMarker, IsTruncated, Roles } = await iam
.listRoles({ Marker, MaxItems: 100 })
.promise();
Roles.forEach(item => roles.push(item));
if (!IsTruncated) {
break;
}
Marker = NextMarker;
}
return roles
.filter(({ RoleName }) => {
return (
!RoleName.startsWith("AWSService") && !RoleName.startsWith("OrganizationAccount")
);
})
.sort((a, b) => {
return new Date(b.CreateDate).getTime() - new Date(a.CreateDate).getTime();
});
};
module.exports.generateTasks = resources => {
return Object.keys(resources)
.map(type => {
switch (type) {
case "lambda":
return {
title: `Delete ${resources[type].length} Lambda functions`,
task: () => {
return new Observable(async observer => {
for (let i = 0; i < resources[type].length; i++) {
const { FunctionName } = resources[type][i];
observer.next(`Deleting ${FunctionName}...`);
await lambda.deleteFunction({ FunctionName }).promise();
}
observer.complete();
});
}
};
case "bucket":
return {
title: `Delete ${resources[type].length} buckets`,
task: () => {
return new Observable(async observer => {
for (let i = 0; i < resources[type].length; i++) {
const { Name: Bucket } = resources[type][i];
let Marker;
while (true) {
observer.next(`Emptying ${Bucket}...`);
const { Contents, IsTruncated } = await s3
.listObjects({ Bucket, Marker })
.promise();
if (!Contents.length) {
break;
}
await s3
.deleteObjects({
Bucket,
Delete: {
Objects: Contents.map(obj => ({ Key: obj.Key }))
}
})
.promise();
if (!IsTruncated) {
break;
}
Marker = Contents[Contents.length - 1].Key;
}
observer.next(`Deleting ${Bucket}...`);
await s3.deleteBucket({ Bucket }).promise();
}
observer.complete();
});
}
};
case "api-gateway":
return {
title: `Delete ${resources[type].length} API Gateways`,
task: () => {
return new Observable(async observer => {
for (let i = 0; i < resources[type].length; i++) {
const { name, id } = resources[type][i];
observer.next(`Deleting ${name}...`);
await pRetry(
async () => {
try {
await apiGateway
.deleteRestApi({ restApiId: id })
.promise();
} catch (error) {
if (error.code !== "TooManyRequestsException") {
// Stop retrying and throw the error
throw new pRetry.AbortError(error);
}
observer.next(`${error.message}. Will retry...`);
throw error;
}
},
{
retries: 3,
minTimeout: 60000,
factor: 2
}
);
}
observer.complete();
});
}
};
case "iam-role":
return {
title: `Delete ${resources[type].length} IAM roles`,
task: () => {
return new Observable(async observer => {
for (let i = 0; i < resources[type].length; i++) {
const { RoleName } = resources[type][i];
observer.next(`Deleting ${RoleName}...`);
const { PolicyNames } = await iam
.listRolePolicies({ RoleName })
.promise();
for (let i = 0; i < PolicyNames.length; i++) {
await iam
.deleteRolePolicy({
RoleName,
PolicyName: PolicyNames[i]
})
.promise();
}
const {
AttachedPolicies
} = await iam.listAttachedRolePolicies({ RoleName }).promise();
for (let i = 0; i < AttachedPolicies.length; i++) {
await iam
.detachRolePolicy({
RoleName,
PolicyArn: AttachedPolicies[i].PolicyArn
})
.promise();
}
await iam.deleteRole({ RoleName }).promise();
}
observer.complete();
});
}
};
case "cloudfront":
return {
title: `Delete ${resources[type].length} CloudFront distribution`,
task: () => {
return new Observable(async observer => {
for (let i = 0; i < resources[type].length; i++) {
const { Id, DomainName } = resources[type][i];
observer.next(`Fetching ${DomainName} configuration...`);
const {
ETag,
DistributionConfig
} = await cloudFront.getDistributionConfig({ Id }).promise();
if (DistributionConfig.Enabled) {
observer.next(`Disabling ${DomainName}...`);
await cloudFront
.updateDistribution({
Id,
DistributionConfig: {
...DistributionConfig,
Enabled: false
},
IfMatch: ETag
})
.promise();
continue;
}
try {
observer.next(`Deleting ${DomainName}...`);
await cloudFront
.deleteDistribution({ Id, IfMatch: ETag })
.promise();
} catch (err) {
observer.error(err.message);
return;
}
}
observer.complete();
});
}
};
case "log-group":
return {
title: `Delete ${resources[type].length} CloudWatch Log Groups`,
task: () => {
return new Observable(async observer => {
for (let i = 0; i < resources[type].length; i++) {
const { logGroupName } = resources[type][i];
observer.next(`Deleting ${logGroupName}...`);
await cloudWatchLogs.deleteLogGroup({ logGroupName }).promise();
}
observer.complete();
});
}
};
default:
return null;
}
})
.filter(Boolean);
};
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: f87648f776ab12c45883b01e9bebc6a3
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
| {
"pile_set_name": "Github"
} |
package org.jeecgframework.web.cgreport.dao.core;
import java.util.List;
import java.util.Map;
import org.jeecgframework.minidao.annotation.Arguments;
import org.jeecgframework.minidao.annotation.MiniDao;
/**
*
* @author zhangdaihao
*
*/
@MiniDao
public interface CgReportDao{
@Arguments("configId")
List<Map<String,Object>> queryCgReportItems(String configId);
@Arguments("id")
Map queryCgReportMainConfig(String id);
}
| {
"pile_set_name": "Github"
} |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.IO;
namespace Google.Protobuf
{
/// <summary>
/// Thrown when a protocol message being parsed is invalid in some way,
/// e.g. it contains a malformed varint or a negative byte length.
/// </summary>
public sealed class InvalidProtocolBufferException : IOException
{
internal InvalidProtocolBufferException(string message)
: base(message)
{
}
internal InvalidProtocolBufferException(string message, Exception innerException)
: base(message, innerException)
{
}
internal static InvalidProtocolBufferException MoreDataAvailable()
{
return new InvalidProtocolBufferException(
"Completed reading a message while more data was available in the stream.");
}
internal static InvalidProtocolBufferException TruncatedMessage()
{
return new InvalidProtocolBufferException(
"While parsing a protocol message, the input ended unexpectedly " +
"in the middle of a field. This could mean either that the " +
"input has been truncated or that an embedded message " +
"misreported its own length.");
}
internal static InvalidProtocolBufferException NegativeSize()
{
return new InvalidProtocolBufferException(
"CodedInputStream encountered an embedded string or message " +
"which claimed to have negative size.");
}
internal static InvalidProtocolBufferException MalformedVarint()
{
return new InvalidProtocolBufferException(
"CodedInputStream encountered a malformed varint.");
}
/// <summary>
/// Creates an exception for an error condition of an invalid tag being encountered.
/// </summary>
internal static InvalidProtocolBufferException InvalidTag()
{
return new InvalidProtocolBufferException(
"Protocol message contained an invalid tag (zero).");
}
internal static InvalidProtocolBufferException InvalidBase64(Exception innerException)
{
return new InvalidProtocolBufferException("Invalid base64 data", innerException);
}
internal static InvalidProtocolBufferException InvalidEndTag()
{
return new InvalidProtocolBufferException(
"Protocol message end-group tag did not match expected tag.");
}
internal static InvalidProtocolBufferException RecursionLimitExceeded()
{
return new InvalidProtocolBufferException(
"Protocol message had too many levels of nesting. May be malicious. " +
"Use CodedInputStream.SetRecursionLimit() to increase the depth limit.");
}
internal static InvalidProtocolBufferException JsonRecursionLimitExceeded()
{
return new InvalidProtocolBufferException(
"Protocol message had too many levels of nesting. May be malicious. " +
"Use JsonParser.Settings to increase the depth limit.");
}
internal static InvalidProtocolBufferException SizeLimitExceeded()
{
return new InvalidProtocolBufferException(
"Protocol message was too large. May be malicious. " +
"Use CodedInputStream.SetSizeLimit() to increase the size limit.");
}
internal static InvalidProtocolBufferException InvalidMessageStreamTag()
{
return new InvalidProtocolBufferException(
"Stream of protocol messages had invalid tag. Expected tag is length-delimited field 1.");
}
}
} | {
"pile_set_name": "Github"
} |
/* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna ([email protected]) **
** Gregory L. Fenves ([email protected]) **
** Filip C. Filippou ([email protected]) **
** **
** ****************************************************************** */
// $Revision: 1.3 $
// $Date: 2010-02-04 19:10:34 $
// $Source: /usr/local/cvs/OpenSees/SRC/material/section/WFFiberSection2d.cpp,v $
// Written: MHS
// Created: Aug 2001
//
// Description: This file contains the class definition for
// WFFiberSection2d.h. WFFiberSection2d provides the abstraction of a
// rectangular section discretized by fibers. The section stiffness and
// stress resultants are obtained by summing fiber contributions.
// The fiber stresses are the 11, 12, and 13 components of stress, from
// which all six beam stress resultants are obtained.
#include <stdlib.h>
#include <Channel.h>
#include <Vector.h>
#include <Matrix.h>
#include <classTags.h>
#include <WFFiberSection2d.h>
#include <ID.h>
#include <FEM_ObjectBroker.h>
#include <UniaxialMaterial.h>
// constructors:
WFFiberSection2d::WFFiberSection2d(int tag, UniaxialMaterial &theMat,
double D, double Tw, double Bf, double Tf,
int Nfdw, int Nftf):
FiberSection2d(),
d(D), tw(Tw), bf(Bf), tf(Tf), nfdw(Nfdw), nftf(Nftf)
{
int numFibers = nfdw + 2*nftf;
for (int i = 0; i < numFibers; i++) {
theMaterials[i] = theMat.getCopy();
if (theMaterials[i] == 0)
opserr << "WFFiberSection2d::WFFiberSection2d -- failed to get copy of beam fiber" << endln;
}
double dw = d-2*tf;
double a_f = bf*tf/nftf;
double a_w = dw*tw/nfdw;
int loc = 0;
double yIncr = tf/nftf;
double yStart = 0.5*d - 0.5*yIncr;
double *AFibers = new double[numFibers];
double *yFibers = new double[numFibers];
for (loc = 0; loc < nftf; loc++) {
AFibers[loc] = a_f;
yFibers[loc] = yStart - yIncr*loc;
AFibers[numFibers-loc-1] = a_f;
yFibers[numFibers-loc-1] = -yFibers[loc];
}
yIncr = dw/nfdw;
yStart = 0.5*dw - 0.5*yIncr;
int count = 0;
for ( ; loc < numFibers-nftf; loc++, count++) {
AFibers[loc] = a_w;
yFibers[loc] = yStart - yIncr*count;
}
for (int i = 0; i < numFibers; i++) {
matData[i*2] = -yFibers[i];
matData[i*2+1] = AFibers[i];
}
delete [] yFibers;
delete [] AFibers;
}
// constructor for blank object that recvSelf needs to be invoked upon
WFFiberSection2d::WFFiberSection2d():
FiberSection2d(),
d(0.0), tw(0.0), bf(0.0), tf(0.0), nfdw(0), nftf(0)
{
}
// destructor:
WFFiberSection2d::~WFFiberSection2d()
{
}
SectionForceDeformation*
WFFiberSection2d::getCopy(void)
{
WFFiberSection2d *theCopy =
new WFFiberSection2d (this->getTag(), *theMaterials[0],
d, tw, bf, tf, nfdw, nftf);
return theCopy;
}
int
WFFiberSection2d::sendSelf(int commitTag, Channel &theChannel)
{
return -1;
}
int
WFFiberSection2d::recvSelf(int commitTag, Channel &theChannel,
FEM_ObjectBroker &theBroker)
{
return -1;
}
void
WFFiberSection2d::Print(OPS_Stream &s, int flag)
{
s << "\nWFFiberSection2d, tag: " << this->getTag() << endln;
s << "\tSection depth: " << d << endln;
s << "\tWeb thickness: " << tw << endln;
s << "\tFlange width: " << bf << endln;
s << "\tFlange thickness: " << tf << endln;
FiberSection2d::Print(s, flag);
}
const Vector &
WFFiberSection2d::getStressResultantSensitivity(int gradIndex,
bool conditional)
{
static Vector ds;
// get material stress contribution
ds = FiberSection2d::getStressResultantSensitivity(gradIndex, conditional);
double y, A, stressGradient;
int loc = 0;
for (int i = 0; i < numFibers; i++) {
y = matData[loc++];
A = matData[loc++];
stressGradient = theMaterials[i]->getStressSensitivity(gradIndex,true);
stressGradient = stressGradient * A;
ds(0) += stressGradient;
ds(1) += stressGradient * y;
}
return ds;
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2017 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "mem.h"
#include "vmm.h"
#include <nvif/class.h>
static const struct nvkm_mmu_func
mcp77_mmu = {
.dma_bits = 40,
.mmu = {{ -1, -1, NVIF_CLASS_MMU_NV50}},
.mem = {{ -1, 0, NVIF_CLASS_MEM_NV50}, nv50_mem_new, nv50_mem_map },
.vmm = {{ -1, -1, NVIF_CLASS_VMM_NV50}, mcp77_vmm_new, false, 0x0200 },
.kind = nv50_mmu_kind,
.kind_sys = true,
};
int
mcp77_mmu_new(struct nvkm_device *device, int index, struct nvkm_mmu **pmmu)
{
return nvkm_mmu_new_(&mcp77_mmu, device, index, pmmu);
}
| {
"pile_set_name": "Github"
} |
using Steam.Models.DOTA2;
using System;
using System.Collections.Generic;
namespace Steam.Models.GameEconomy
{
public class SchemaItemModel
{
public uint DefIndex { get; set; }
public string Name { get; set; }
public string ImageInventoryPath { get; set; }
public string ItemName { get; set; }
public string ItemDescription { get; set; }
public string ItemTypeName { get; set; }
public string ItemClass { get; set; }
public bool ProperName { get; set; }
public string ItemSlot { get; set; }
public string ModelPlayer { get; set; }
public uint ItemQuality { get; set; }
public uint MinIlevel { get; set; }
public uint MaxIlevel { get; set; }
public string ImageUrl { get; set; }
public string ImageUrlLarge { get; set; }
public string CraftClass { get; set; }
public string CraftMaterialType { get; set; }
public string ItemLogName { get; set; }
public SchemaCapabilitiesModel Capabilities { get; set; }
public IReadOnlyCollection<string> UsedByClasses { get; set; }
public IReadOnlyCollection<SchemaStyleModel> Styles { get; set; }
public IReadOnlyCollection<SchemaItemAttributeModel> Attributes { get; set; }
public string DropType { get; set; }
public string ItemSet { get; set; }
public string HolidayRestriction { get; set; }
public SchemaPerClassLoadoutSlotsModel PerClassLoadoutSlots { get; set; }
public SchemaToolModel Tool { get; set; }
public string Prefab { get; set; }
public DateTime? CreationDate { get; set; }
public DateTime? ExpirationDate { get; set; }
public string TournamentUrl { get; set; }
public string ImageBannerPath { get; set; }
public string ItemRarity { get; set; }
public SchemaItemPriceInfo PriceInfo { get; set; }
public IList<string> UsedByHeroes { get; set; }
public IList<string> BundledItems { get; set; }
}
} | {
"pile_set_name": "Github"
} |
# The set of languages for which implicit dependencies are needed:
SET(CMAKE_DEPENDS_LANGUAGES
)
# The set of files for implicit dependencies of each language:
# Preprocessor definitions for this target.
SET(CMAKE_TARGET_DEFINITIONS
"ROS_PACKAGE_NAME=\"multi_map_server\""
)
# Targets to which this target links.
SET(CMAKE_TARGET_LINKED_INFO_FILES
)
# The include file search paths:
SET(CMAKE_C_TARGET_INCLUDE_PATH
"../include"
"/home/jchen/workspace/src/armadillo/armadillo/include"
"/home/jchen/workspace/src/pose_utils/include"
"/opt/ros/indigo/include"
"/usr/include/eigen3"
"../msg_gen/cpp/include"
)
SET(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
| {
"pile_set_name": "Github"
} |
---
:layout: refresh
:refresh_to_post_id: "/blog/2015/05/18/juc-speaker-blog-series-andrew-bayer-juc-europe"
---
| {
"pile_set_name": "Github"
} |
<!--$Id: seq_close.so,v 1.2 2004/08/13 03:39:02 bostic Exp $-->
<!--Copyright (c) 1997,2008 Oracle. All rights reserved.-->
<!--See the file LICENSE for redistribution information.-->
<html>
<head>
<title>Berkeley DB: DB_SEQUENCE->close</title>
<meta name="description" content="Berkeley DB: An embedded database programmatic toolkit.">
<meta name="keywords" content="embedded,database,programmatic,toolkit,btree,hash,hashing,transaction,transactions,locking,logging,access method,access methods,Java,C,C++">
</head>
<body bgcolor=white>
<table width="100%"><tr valign=top>
<td>
<b>DB_SEQUENCE->close</b>
</td>
<td align=right>
<a href="../api_c/api_core.html"><img src="../images/api.gif" alt="API"></a>
<a href="../ref/toc.html"><img src="../images/ref.gif" alt="Ref"></a></td>
</tr></table>
<hr size=1 noshade>
<tt>
<b><pre>
#include <db.h>
<p>
int
DB_SEQUENCE->close(DB_SEQUENCE *seq, u_int32_t flags);
</pre></b>
<hr size=1 noshade>
<b>Description: DB_SEQUENCE->close</b>
<p>The DB_SEQUENCE->close method closes the sequence handle. Any unused cached
values are lost.</p>
<p>The <a href="../api_c/seq_class.html">DB_SEQUENCE</a> handle may not be accessed again after DB_SEQUENCE->close is
called, regardless of its return.</p>
<p>The DB_SEQUENCE->close method
returns a non-zero error value on failure
and 0 on success.
</p>
<b>Parameters</b> <br>
<b>flags</b><ul compact><li>The <b>flags</b> parameter is currently unused, and must be set to 0.</ul>
<br>
<br><b>Errors</b>
<p>The DB_SEQUENCE->close method
may fail and return one of the following non-zero errors:</p>
<br>
<b>EINVAL</b><ul compact><li>An
invalid flag value or parameter was specified.</ul>
<br>
<hr size=1 noshade>
<br><b>Class</b>
<a href="../api_c/seq_class.html">DB_SEQUENCE</a>
<br><b>See Also</b>
<a href="../api_c/seq_list.html">Sequences and Related Methods</a>
</tt>
<table width="100%"><tr><td><br></td><td align=right>
<a href="../api_c/api_core.html"><img src="../images/api.gif" alt="API"></a><a href="../ref/toc.html"><img src="../images/ref.gif" alt="Ref"></a>
</td></tr></table>
<p><font size=1>Copyright (c) 1996,2008 Oracle. All rights reserved.</font>
</body>
</html>
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Azylee.YeahWeb.BaiDuWebAPI.dwz
{
/// <summary>
/// 短网址请求模型
/// </summary>
public class DwzRequestModel
{
/// <summary>
/// 长网址
/// </summary>
public string url { get; set; }
}
}
| {
"pile_set_name": "Github"
} |
---
subcategory: "Database"
layout: "azurerm"
page_title: "Azure Resource Manager: azurerm_sql_database"
description: |-
Gets information about an existing SQL Azure Database.
---
# Data Source: azurerm_sql_database
Use this data source to access information about an existing SQL Azure Database.
## Example Usage
```hcl
data "azurerm_sql_database" "example" {
name = "example_db"
server_name = "example_db_server"
resource_group_name = "example-resources"
}
output "sql_database_id" {
value = data.azurerm_sql_database.example.id
}
```
## Argument Reference
* `name` - The name of the SQL Database.
* `server_name` - The name of the SQL Server.
* `resource_group_name` - Specifies the name of the Resource Group where the Azure SQL Database exists.
## Attributes Reference
* `id` - The SQL Database ID.
* `collation` - The name of the collation.
* `creation_date` - The creation date of the SQL Database.
* `default_secondary_location` - The default secondary location of the SQL Database.
* `edition` - The edition of the database.
* `elastic_pool_name` - The name of the elastic database pool the database belongs to.
* `failover_group_id` - The ID of the failover group the database belongs to.
* `location` - The location of the Resource Group in which the SQL Server exists.
* `name` - The name of the database.
* `read_scale` - Indicate if read-only connections will be redirected to a high-available replica.
* `requested_service_objective_id` - The ID pertaining to the performance level of the database.
* `requested_service_objective_name` - The name pertaining to the performance level of the database.
* `resource_group_name` - The name of the resource group in which the database resides. This will always be the same resource group as the Database Server.
* `server_name` - The name of the SQL Server on which to create the database.
* `tags` - A mapping of tags assigned to the resource.
## Timeouts
The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions:
* `read` - (Defaults to 5 minutes) Used when retrieving the SQL Azure Database.
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <GeoServices/GEOMapItemAttribution.h>
@class NSArray, NSURL;
@interface GEOMapItemPlaceAttribution : GEOMapItemAttribution
{
}
@property(readonly, nonatomic) NSURL *webURL;
@property(readonly, nonatomic) NSArray *checkInURLs;
- (id)initWithSearchAttributionInfo:(id)arg1 attributionURLs:(id)arg2 poiID:(id)arg3;
@end
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {ReactNodeList} from 'shared/ReactTypes';
import {
createRequest,
startWork,
startFlowing,
} from 'react-server/src/ReactFizzServer';
function renderToReadableStream(children: ReactNodeList): ReadableStream {
let request;
return new ReadableStream({
start(controller) {
request = createRequest(children, controller);
startWork(request);
},
pull(controller) {
startFlowing(request);
},
cancel(reason) {},
});
}
export {renderToReadableStream};
| {
"pile_set_name": "Github"
} |
// 20.1.2.3 Number.isInteger(number)
var isObject = require('./$.is-object')
, floor = Math.floor;
module.exports = function isInteger(it){
return !isObject(it) && isFinite(it) && floor(it) === it;
}; | {
"pile_set_name": "Github"
} |
/*************************************************************************
* *
* XVII Olimpiada Informatyczna *
* *
* Zadanie: Teleporty (TEL) *
* Plik: telb8.cpp *
* Autorzy: Łukasz Bieniasz-Krzywiec, Mirosław Michalski *
* Opis: Rozwiazanie niepoprawne . *
* "Popsute" rozwiązanie wzorcowe. *
* Zlozonosc czasowa: O(n + m) *
* Zlozonosc pamieciowa: O(n + m) *
* Kodowanie znaków: UTF-8 *
* *
*************************************************************************/
#include <cstdlib>
#include <cstdio>
#include <vector>
using namespace std;
/*
* DEKLARACJE STAŁYCH
*/
#define MAXN 40000
#define MAXM 1000000
#define INF MAXN
/*
* DEKLARACJE TYPÓW:
*/
typedef vector<int> VI;
typedef vector<VI > VVI;
/*
* DEKLARACJE ZMIENNYCH GLOBALNYCH:
*/
int n, m, w; /* liczba wierzchołków, liczba krawędzi, wynik */
VVI g; /* graf w postaci list sąsiedztwa */
/*
* DEKLARACJE PODPROGRAMÓW:
*/
/* Funkcja dodaje do grafu krawędź {a,b}. */
void inline dodajKrawedz(int a, int b) {
g[a].push_back(b);
g[b].push_back(a);
}
/* Funkcja wczytuje dane. */
void wczytajDane() {
int a, b, i;
scanf("%d%d", &n, &m);
g = VVI(n);
for (i = 0; i < m; ++i) {
scanf("%d%d", &a, &b);
dodajKrawedz(a - 1, b - 1);
}
}
/* Przeszukiwanie wszerz. */
void bfs(int v, VI &d) {
int i, j, u, w;
VI q;
for (i = 0; i < n; ++i) {
d[i] = INF;
}
d[v] = 0; q.push_back(v);
for (i = 0; i < (int)q.size(); ++i) {
u = q[i];
for (j = 0; j < (int)g[u].size(); ++j) {
w = g[u][j];
if (d[w] == INF) {
d[w] = d[u] + 1;
if (d[w] < 2) {
q.push_back(w);
}
}
}
}
}
inline int min(int a, int b) {
return a < b ? a : b;
}
/*
* Funkcja oblicza moc maksymalnego rozszerzenia grafu.
* Algorytm wzorcowy.
*/
void obliczWynik() {
int a = 0, b = 0, c = 0, d = 0, i;
VI t1(n), t2(n);
bfs(0, t1);
bfs(1, t2);
for (i = 0; i < n; ++i) {
switch (t1[i]) {
case 1: a += 1; break;
case 2: b += 1; break;
}
switch (t2[i]) {
case 1: c += 1; break;
case 2: d += 1; break;
}
}
w = n*(n-1)/2-m-(n-1-a)-a*(1+c+d)-b*(1+c)-(n-1-c-1-a-b)-min(a,d)*(n-1-a-b-1-c-d);
}
/* Funkcja wypisuje wynik. */
void wypiszWynik() {
printf("%d\n", w);
}
/*
* PROGRAM GŁÓWNY:
*/
int main() {
wczytajDane();
obliczWynik();
wypiszWynik();
return 0;
}
| {
"pile_set_name": "Github"
} |
CSSStyleDeclaration
===================
CSSStyleDeclaration is a work-a-like to the CSSStyleDeclaration class in Nikita Vasilyev's [CSSOM](https://github.com/NV/CSSOM). I made it so that when using [jQuery in node](https://github.com/tmtk75/node-jquery) setting css attributes via $.fn.css() would work. node-jquery uses [jsdom](https://github.com/tmpvar/jsdom) to create a DOM to use in node. jsdom uses CSSOM for styling, and CSSOM's implementation of the [CSSStyleDeclaration](http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration) doesn't support [CSS2Properties](http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSS2Properties), which is how jQuery's [$.fn.css()](http://api.jquery.com/css/) operates.
Why not just issue a pull request?
----
Well, NV wants to keep CSSOM fast (which I can appreciate) and CSS2Properties aren't required by the standard (though every browser has the interface). So I figured the path of least resistence would be to just modify this one class, publish it as a node module (that requires CSSOM) and then make a pull request of jsdom to use it.
How do I test this code?
---
`npm test` should do the trick, assuming you have the dev dependencies installed:
> ```
> $ npm test
>
> tests
> ✔ Verify Has Properties
> ✔ Verify Has Functions
> ✔ Verify Has Special Properties
> ✔ Test From Style String
> ✔ Test From Properties
> ✔ Test Shorthand Properties
> ✔ Test width and height Properties and null and empty strings
> ✔ Test Implicit Properties
> ```
| {
"pile_set_name": "Github"
} |
// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2018, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Rene Rahn <[email protected]>
// ==========================================================================
#ifndef INCLUDE_SEQAN_ALIGN_ALIGNED_SEQUENCE_CONCEPT_H_
#define INCLUDE_SEQAN_ALIGN_ALIGNED_SEQUENCE_CONCEPT_H_
namespace seqan
{
// ============================================================================
// Forwards
// ============================================================================
// ============================================================================
// Tags, Classes, Enums
// ============================================================================
SEQAN_CONCEPT_REFINE(AlignedSequenceConcept, (TSequence), (ContainerConcept))
{
SEQAN_CONCEPT_USAGE(AlignedSequenceConcept)
{}
};
// ============================================================================
// Metafunctions
// ============================================================================
// ============================================================================
// Functions
// ============================================================================
} // namespace seqan
#endif // #ifndef INCLUDE_SEQAN_ALIGN_ALIGNED_SEQUENCE_CONCEPT_H_
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2017 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WasmWorklist.h"
#if ENABLE(WEBASSEMBLY)
#include "WasmPlan.h"
#include <wtf/NumberOfCores.h>
namespace JSC { namespace Wasm {
namespace WasmWorklistInternal {
static const bool verbose = false;
}
const char* Worklist::priorityString(Priority priority)
{
switch (priority) {
case Priority::Preparation: return "Preparation";
case Priority::Shutdown: return "Shutdown";
case Priority::Compilation: return "Compilation";
case Priority::Synchronous: return "Synchronous";
}
RELEASE_ASSERT_NOT_REACHED();
}
// The Thread class is designed to prevent threads from blocking when there is still work
// in the queue. Wasm's Plans have some phases, Validiation, Preparation, and Completion,
// that can only be done by one thread, and another phase, Compilation, that can be done
// many threads. In order to stop a thread from wasting time we remove any plan that is
// is currently in a single threaded state from the work queue so other plans can run.
class Worklist::Thread final : public AutomaticThread {
public:
using Base = AutomaticThread;
Thread(const AbstractLocker& locker, Worklist& work)
: Base(locker, work.m_lock, work.m_planEnqueued.copyRef())
, worklist(work)
{
}
protected:
PollResult poll(const AbstractLocker&) override
{
auto& queue = worklist.m_queue;
synchronize.notifyAll();
while (!queue.isEmpty()) {
Priority priority = queue.peek().priority;
if (priority == Worklist::Priority::Shutdown)
return PollResult::Stop;
element = queue.peek();
// Only one thread should validate/prepare.
if (!queue.peek().plan->multiThreaded())
queue.dequeue();
if (element.plan->hasWork())
return PollResult::Work;
// There must be a another thread linking this plan so we can deque and see if there is other work.
queue.dequeue();
element = QueueElement();
}
return PollResult::Wait;
}
WorkResult work() override
{
auto complete = [&] (const AbstractLocker&) {
// We need to hold the lock to release our plan otherwise the main thread, while canceling plans
// might use after free the plan we are looking at
element = QueueElement();
return WorkResult::Continue;
};
Plan* plan = element.plan.get();
ASSERT(plan);
bool wasMultiThreaded = plan->multiThreaded();
plan->work(Plan::Partial);
ASSERT(!plan->hasWork() || plan->multiThreaded());
if (plan->hasWork() && !wasMultiThreaded && plan->multiThreaded()) {
LockHolder locker(*worklist.m_lock);
element.setToNextPriority();
worklist.m_queue.enqueue(WTFMove(element));
worklist.m_planEnqueued->notifyAll(locker);
return complete(locker);
}
return complete(holdLock(*worklist.m_lock));
}
const char* name() const override
{
return "Wasm Worklist Helper Thread";
}
public:
Condition synchronize;
Worklist& worklist;
// We can only modify element when holding the lock. A synchronous compile might look at each thread's tasks in order to boost the priority.
QueueElement element;
};
void Worklist::QueueElement::setToNextPriority()
{
switch (priority) {
case Priority::Preparation:
priority = Priority::Compilation;
return;
case Priority::Synchronous:
return;
default:
break;
}
RELEASE_ASSERT_NOT_REACHED();
}
void Worklist::enqueue(Ref<Plan> plan)
{
LockHolder locker(*m_lock);
if (!ASSERT_DISABLED) {
for (const auto& element : m_queue)
ASSERT_UNUSED(element, element.plan.get() != &plan.get());
}
dataLogLnIf(WasmWorklistInternal::verbose, "Enqueuing plan");
m_queue.enqueue({ Priority::Preparation, nextTicket(), WTFMove(plan) });
m_planEnqueued->notifyOne(locker);
}
void Worklist::completePlanSynchronously(Plan& plan)
{
{
LockHolder locker(*m_lock);
m_queue.decreaseKey([&] (QueueElement& element) {
if (element.plan == &plan) {
element.priority = Priority::Synchronous;
return true;
}
return false;
});
for (auto& thread : m_threads) {
if (thread->element.plan == &plan)
thread->element.priority = Priority::Synchronous;
}
}
plan.waitForCompletion();
}
void Worklist::stopAllPlansForContext(Context& context)
{
LockHolder locker(*m_lock);
Vector<QueueElement> elements;
while (!m_queue.isEmpty()) {
QueueElement element = m_queue.dequeue();
bool didCancel = element.plan->tryRemoveContextAndCancelIfLast(context);
if (!didCancel)
elements.append(WTFMove(element));
}
for (auto& element : elements)
m_queue.enqueue(WTFMove(element));
for (auto& thread : m_threads) {
if (thread->element.plan) {
bool didCancel = thread->element.plan->tryRemoveContextAndCancelIfLast(context);
if (didCancel) {
// We don't have to worry about the deadlocking since the thread can't block without checking for a new plan and must hold the lock to do so.
thread->synchronize.wait(*m_lock);
}
}
}
}
Worklist::Worklist()
: m_lock(Box<Lock>::create())
, m_planEnqueued(AutomaticThreadCondition::create())
{
unsigned numberOfCompilationThreads = Options::useConcurrentJIT() ? WTF::numberOfProcessorCores() : 1;
m_threads.reserveCapacity(numberOfCompilationThreads);
LockHolder locker(*m_lock);
for (unsigned i = 0; i < numberOfCompilationThreads; i++)
m_threads.uncheckedAppend(std::make_unique<Worklist::Thread>(locker, *this));
}
Worklist::~Worklist()
{
{
LockHolder locker(*m_lock);
m_queue.enqueue({ Priority::Shutdown, nextTicket(), nullptr });
m_planEnqueued->notifyAll(locker);
}
for (unsigned i = 0; i < m_threads.size(); ++i)
m_threads[i]->join();
}
static Worklist* globalWorklist;
Worklist* existingWorklistOrNull() { return globalWorklist; }
Worklist& ensureWorklist()
{
static std::once_flag initializeWorklist;
std::call_once(initializeWorklist, [] {
globalWorklist = new Worklist();
});
return *globalWorklist;
}
} } // namespace JSC::Wasm
#endif // ENABLE(WEBASSEMBLY)
| {
"pile_set_name": "Github"
} |
#include "envoy/data/tap/v3/wrapper.pb.h"
#include "common/protobuf/utility.h"
#include "extensions/common/tap/tap.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
namespace envoy {
namespace data {
namespace tap {
namespace v3 {
// TODO(mattklein123): AFAICT gtest has built in printing for proto messages but it doesn't seem
// to work unless this is here.
std::ostream& operator<<(std::ostream& os, const TraceWrapper& trace);
} // namespace v3
} // namespace tap
} // namespace data
} // namespace envoy
namespace Envoy {
namespace Extensions {
// TODO(mattklein123): Make this a common matcher called ProtoYamlEq and figure out how to
// correctly templatize it.
MATCHER_P(TraceEqual, rhs, "") {
envoy::data::tap::v3::TraceWrapper expected_trace;
TestUtility::loadFromYaml(rhs, expected_trace);
return TestUtility::protoEqual(expected_trace, arg);
}
namespace Common {
namespace Tap {
class MockPerTapSinkHandleManager : public PerTapSinkHandleManager {
public:
MockPerTapSinkHandleManager();
~MockPerTapSinkHandleManager() override;
void submitTrace(TraceWrapperPtr&& trace) override { submitTrace_(*trace); }
MOCK_METHOD(void, submitTrace_, (const envoy::data::tap::v3::TraceWrapper& trace));
};
class MockMatcher : public Matcher {
public:
using Matcher::Matcher;
~MockMatcher() override;
MOCK_METHOD(void, onNewStream, (MatchStatusVector & statuses), (const));
MOCK_METHOD(void, onHttpRequestHeaders,
(const Http::RequestHeaderMap& request_headers, MatchStatusVector& statuses),
(const));
MOCK_METHOD(void, onHttpRequestTrailers,
(const Http::RequestTrailerMap& request_trailers, MatchStatusVector& statuses),
(const));
MOCK_METHOD(void, onHttpResponseHeaders,
(const Http::ResponseHeaderMap& response_headers, MatchStatusVector& statuses),
(const));
MOCK_METHOD(void, onHttpResponseTrailers,
(const Http::ResponseTrailerMap& response_trailers, MatchStatusVector& statuses),
(const));
MOCK_METHOD(void, onRequestBody, (const Buffer::Instance& data, MatchStatusVector& statuses));
MOCK_METHOD(void, onResponseBody, (const Buffer::Instance& data, MatchStatusVector& statuses),
());
};
} // namespace Tap
} // namespace Common
} // namespace Extensions
} // namespace Envoy
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo support and contact module."""
from __future__ import absolute_import, print_function
from .ext import ZenodoSupport
__all__ = ('ZenodoSupport', )
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<!-- ////////////////////////////////////////////////////////////////////////
// @license
// This demo file is part of yFiles for HTML 2.3.
// Copyright (c) 2000-2020 by yWorks GmbH, Vor dem Kreuzberg 28,
// 72070 Tuebingen, Germany. All rights reserved.
//
// yFiles demo files exhibit yFiles for HTML functionalities. Any redistribution
// of demo files in source code or binary form, with or without
// modification, is not permitted.
//
// Owners of a valid software license for a yFiles for HTML version that this
// demo is shipped with are allowed to use the demo source code as basis
// for their own yFiles for HTML powered applications. Use of such programs is
// governed by the rights and conditions as set out in the yFiles for HTML
// license agreement.
//
// THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
// NO EVENT SHALL yWorks BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
////////////////////////////////////////////////////////////////////////-->
<title>Custom Edge Creation Demo [yFiles for HTML]</title>
<link rel="stylesheet" href="../../node_modules/yfiles/yfiles.css">
<link rel="stylesheet" href="../../resources/style/demo.css">
<script src="../../resources/filesystem-warning.js"></script>
</head>
<body class="demo-has-left">
<aside class="demo-sidebar demo-left">
<h1 class="demo-sidebar-header">Description</h1>
<div class="demo-sidebar-content">
<p>
This demo shows how to provide directional <a href="https://docs.yworks.com/yfileshtml/#/api/IPort" target="_blank">IPort</a>s and <a href="https://docs.yworks.com/yfileshtml/#/api/PortCandidate" target="_blank">PortCandidate</a>s and demonstrates
several customizations for the edge creation gesture.
</p>
<h2>Ports and PortCandiates</h2>
<p>
Each node provides directional ports that are visualized with the <a href="https://docs.yworks.com/yfileshtml/#/api/NodeStylePortStyleAdapter" target="_blank">NodeStylePortStyleAdapter</a> and a
circular <a href="https://docs.yworks.com/yfileshtml/#/api/ShapeNodeStyle" target="_blank">ShapeNodeStyle</a>.
</p>
<p>This demo restricts edge creation to the provided <a href="https://docs.yworks.com/yfileshtml/#/api/PortCandidate" target="_blank">PortCandidate</a>s. Therefore, the PortCandidates are
also shown on the source on hover to indicate that edge creation may start there.</p>
<p>
The <b>Show Ports</b> button in the toolbar toggles the visualization of the ports. Note how the PortCandidates
are still visible on hover even if the ports are not visualized anymore.
</p>
<h2>Edge Creation</h2>
<p>
The edge color of newly created edges is dynamically determined by the source node from which the edge creation
gesture originates.
</p>
<p>
<b>Enable Target Node</b> toggles whether edge creation should create a target node as well. This enables users to
end the creation gesture on the empty canvas.
</p>
<h2>Interactive Edge Routing</h2>
<p>
This demo illustrates different approaches to interactive edge routing during edge creation:
</p>
<ul>
<li>
<b>Default Orthogonal</b>: Utilizes the <a href="https://docs.yworks.com/yfileshtml/#/api/OrthogonalEdgeEditingContext" target="_blank">OrthogonalEdgeEditingContext</a> which does not use a dedicated
layout algorithm. It is the fastest approach but does not consider port directions or other nodes.
</li>
<li>
<b>Edge Router (Quality)</b>: Applies the <a href="https://docs.yworks.com/yfileshtml/#/api/EdgeRouter" target="_blank">EdgeRouter</a> with each move during the edge creation gesture.
This is the most expensive approach but yields nicely routed edges.
</li>
<li>
<b>Edge Router (Performance)</b>: Applies the <a href="https://docs.yworks.com/yfileshtml/#/api/EdgeRouter" target="_blank">EdgeRouter</a> as well but sets its
<code>maximumDuration</code> to <code>0</code> such that a less performance heavy approach is used. This still
routes around other nodes but sometimes yields less appealing results.
</li>
<li>
<b>Channel Edge Router</b>: Uses the <a href="https://docs.yworks.com/yfileshtml/#/api/ChannelEdgeRouter" target="_blank">ChannelEdgeRouter</a> to layout the edge during the gesture. This
implementation is usually faster than the EdgeRouter but may produce node-edge overlaps.
</li>
</ul>
</div>
</aside>
<div class="demo-content">
<div class="demo-toolbar">
<button data-command="Reset" title="Reset Graph" class="demo-icon-yIconReload"></button>
<span class="demo-separator"></span>
<button data-command="ZoomOriginal" title="Zoom to original size"
class="demo-icon-yIconZoomOriginal"></button>
<button data-command="FitContent" title="Fit Content" class="demo-icon-yIconZoomFit"></button>
<span class="demo-separator"></span> <input type="checkbox" id="togglePortVisualization"
class="demo-toggle-button labeled" data-command="TogglePortVisualization" checked/> <label
for="togglePortVisualization" title="Toggles port visualization">Show Ports</label>
<span class="demo-separator"></span> <input type="checkbox" id="toggleTargetNode" class="demo-toggle-button labeled"
data-command="ToggleTargetNode" checked/> <label for="toggleTargetNode"
title="Whether edge creation can end on empty canvas">Enable Target Node</label>
<span class="demo-separator"></span> <span>Interactive Edge Routing:</span> <select
data-command="createEdgeModeChanged" id="createEdgeMode">
<option>Default Orthogonal
<option>Edge Router (Quality)
<option selected>Edge Router (Performance)
<option>Channel Edge Router
</select>
</div>
<div id="graphComponent"></div>
</div>
<script type="module" crossorigin="anonymous" src="CustomEdgeCreationDemo.js"></script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
FROM adoptopenjdk:11-jdk-openj9-bionic
ARG MAVEN_VERSION=3.6.3
ARG USER_HOME_DIR="/root"
ARG SHA=c35a1803a6e70a126e80b2b3ae33eed961f83ed74d18fcd16909b2d44d7dada3203f1ffe726c17ef8dcca2dcaa9fca676987befeadc9b9f759967a8cb77181c0
ARG BASE_URL=https://apache.osuosl.org/maven/maven-3/${MAVEN_VERSION}/binaries
RUN mkdir -p /usr/share/maven /usr/share/maven/ref \
&& curl -fsSL -o /tmp/apache-maven.tar.gz ${BASE_URL}/apache-maven-${MAVEN_VERSION}-bin.tar.gz \
&& echo "${SHA} /tmp/apache-maven.tar.gz" | sha512sum -c - \
&& tar -xzf /tmp/apache-maven.tar.gz -C /usr/share/maven --strip-components=1 \
&& rm -f /tmp/apache-maven.tar.gz \
&& ln -s /usr/share/maven/bin/mvn /usr/bin/mvn
ENV MAVEN_HOME /usr/share/maven
ENV MAVEN_CONFIG "$USER_HOME_DIR/.m2"
COPY mvn-entrypoint.sh /usr/local/bin/mvn-entrypoint.sh
COPY settings-docker.xml /usr/share/maven/ref/
ENTRYPOINT ["/usr/local/bin/mvn-entrypoint.sh"]
CMD ["mvn"]
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Magento_InventoryVisualMerchandiser" />
</config>
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2017, OpenRemote Inc.
*
* See the CONTRIBUTORS.txt file in the distribution for a
* full listing of individual contributors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openremote.model.rules;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.datapoint.DatapointInterval;
import org.openremote.model.datapoint.ValueDatapoint;
public abstract class HistoricDatapoints {
public abstract ValueDatapoint[] getValueDataPoints(AttributeRef attributeRef,
DatapointInterval interval,
long fromTimestamp,
long toTimestamp);
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceModel;
using Mono.Options;
using Stride.Core.Storage;
using Stride.Core.Diagnostics;
using Stride.Core.IO;
using Stride.Core.MicroThreading;
using Stride.Core.Serialization;
using Stride.Core.Serialization.Assets;
using Stride.Core.Serialization.Contents;
using System.Threading;
namespace Stride.Core.BuildEngine
{
public static class BuildEngineCommands
{
public static BuildResultCode Build(BuilderOptions options)
{
BuildResultCode result;
if (options.IsValidForSlave())
{
// Sleeps one second so that debugger can attach
//Thread.Sleep(1000);
result = BuildSlave(options);
}
else if (options.IsValidForMaster())
{
result = BuildLocal(options);
if (!string.IsNullOrWhiteSpace(options.OutputDirectory) && options.BuilderMode == Builder.Mode.Build)
{
CopyBuildToOutput(options);
}
}
else
{
throw new OptionException("Insufficient parameters, no action taken", "build-path");
}
return result;
}
private static void PrepareDatabases(BuilderOptions options)
{
AssetManager.GetDatabaseFileProvider = () => IndexFileCommand.DatabaseFileProvider.Value;
}
public static BuildResultCode BuildLocal(BuilderOptions options)
{
string inputFile = options.InputFiles[0];
string sdkDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../..");
BuildScript buildScript = BuildScript.LoadFromFile(sdkDir, inputFile);
buildScript.Compile(options.Plugins);
if (buildScript.GetWarnings().FirstOrDefault() != null)
{
foreach (string warning in buildScript.GetWarnings())
{
options.Logger.Warning(warning);
}
}
if (buildScript.HasErrors)
{
foreach (string error in buildScript.GetErrors())
{
options.Logger.Error(error);
}
throw new InvalidOperationException("Can't compile the provided build script.");
}
string inputDir = Path.GetDirectoryName(inputFile) ?? Environment.CurrentDirectory;
options.SourceBaseDirectory = options.SourceBaseDirectory ?? Path.Combine(inputDir, buildScript.SourceBaseDirectory ?? "");
options.BuildDirectory = options.BuildDirectory ?? Path.Combine(inputDir, buildScript.BuildDirectory ?? "");
options.OutputDirectory = options.OutputDirectory ?? (buildScript.OutputDirectory != null ? Path.Combine(inputDir, buildScript.OutputDirectory) : "");
options.MetadataDatabaseDirectory = options.MetadataDatabaseDirectory ?? (buildScript.MetadataDatabaseDirectory != null ? Path.Combine(inputDir, buildScript.MetadataDatabaseDirectory) : "");
if (!string.IsNullOrWhiteSpace(options.SourceBaseDirectory))
{
if (!Directory.Exists(options.SourceBaseDirectory))
{
string error = string.Format("Source base directory \"{0}\" does not exists.", options.SourceBaseDirectory);
options.Logger.Error(error);
throw new OptionException(error, "sourcebase");
}
Environment.CurrentDirectory = options.SourceBaseDirectory;
}
if (string.IsNullOrWhiteSpace(options.BuildDirectory))
{
throw new OptionException("This tool requires a build path.", "build-path");
}
// Mount build path
((FileSystemProvider)VirtualFileSystem.ApplicationData).ChangeBasePath(options.BuildDirectory);
options.ValidateOptionsForMaster();
// assets is always added by default
//options.Databases.Add(new DatabaseMountInfo("/assets"));
PrepareDatabases(options);
try
{
VirtualFileSystem.CreateDirectory("/data/");
VirtualFileSystem.CreateDirectory("/data/db/");
}
catch (Exception)
{
throw new OptionException("Invalid Build database path", "database");
}
// Create builder
LogMessageType logLevel = options.Debug ? LogMessageType.Debug : (options.Verbose ? LogMessageType.Verbose : LogMessageType.Info);
var logger = Logger.GetLogger("builder");
logger.ActivateLog(logLevel);
var builder = new Builder("builder", options.BuildDirectory, options.BuilderMode, logger) { ThreadCount = options.ThreadCount };
builder.MonitorPipeNames.AddRange(options.MonitorPipeNames);
builder.ActivateConfiguration(options.Configuration);
foreach (var sourceFolder in buildScript.SourceFolders)
{
builder.InitialVariables.Add(("SourceFolder:" + sourceFolder.Key).ToUpperInvariant(), sourceFolder.Value);
}
Console.CancelKeyPress += (sender, e) => Cancel(builder, e);
buildScript.Execute(builder);
// Run builder
return builder.Run(options.Append == false);
}
private static void RegisterRemoteLogger(IProcessBuilderRemote processBuilderRemote)
{
// The pipe might be broken while we try to output log, so let's try/catch the call to prevent program for crashing here (it should crash at a proper location anyway if the pipe is broken/closed)
// ReSharper disable EmptyGeneralCatchClause
GlobalLogger.MessageLogged += msg => { try { processBuilderRemote.ForwardLog(msg); } catch { } };
// ReSharper restore EmptyGeneralCatchClause
}
public static BuildResultCode BuildSlave(BuilderOptions options)
{
// Mount build path
((FileSystemProvider)VirtualFileSystem.ApplicationData).ChangeBasePath(options.BuildDirectory);
PrepareDatabases(options);
try
{
VirtualFileSystem.CreateDirectory("/data/");
VirtualFileSystem.CreateDirectory("/data/db/");
}
catch (Exception)
{
throw new OptionException("Invalid Build database path", "database");
}
// Open WCF channel with master builder
var namedPipeBinding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None) { SendTimeout = TimeSpan.FromSeconds(300.0) };
var processBuilderRemote = ChannelFactory<IProcessBuilderRemote>.CreateChannel(namedPipeBinding, new EndpointAddress(options.SlavePipe));
try
{
RegisterRemoteLogger(processBuilderRemote);
// Create scheduler
var scheduler = new Scheduler();
var status = ResultStatus.NotProcessed;
// Schedule command
string buildPath = options.BuildDirectory;
Logger logger = options.Logger;
MicroThread microthread = scheduler.Add(async () =>
{
// Deserialize command and parameters
Command command = processBuilderRemote.GetCommandToExecute();
BuildParameterCollection parameters = processBuilderRemote.GetBuildParameters();
// Run command
var inputHashes = new DictionaryStore<InputVersionKey, ObjectId>(VirtualFileSystem.OpenStream("/data/db/InputHashes", VirtualFileMode.OpenOrCreate, VirtualFileAccess.ReadWrite, VirtualFileShare.ReadWrite));
var builderContext = new BuilderContext(buildPath, inputHashes, parameters, 0, null);
var commandContext = new RemoteCommandContext(processBuilderRemote, command, builderContext, logger);
command.PreCommand(commandContext);
status = await command.DoCommand(commandContext);
command.PostCommand(commandContext, status);
// Returns result to master builder
processBuilderRemote.RegisterResult(commandContext.ResultEntry);
});
while (true)
{
scheduler.Run();
// Exit loop if no more micro threads
lock (scheduler.MicroThreads)
{
if (!scheduler.MicroThreads.Any())
break;
}
Thread.Sleep(0);
}
// Rethrow any exception that happened in microthread
if (microthread.Exception != null)
{
options.Logger.Fatal(microthread.Exception.ToString());
return BuildResultCode.BuildError;
}
if (status == ResultStatus.Successful || status == ResultStatus.NotTriggeredWasSuccessful)
return BuildResultCode.Successful;
return BuildResultCode.BuildError;
}
finally
{
// Close WCF channel
// ReSharper disable SuspiciousTypeConversion.Global
((IClientChannel)processBuilderRemote).Close();
// ReSharper restore SuspiciousTypeConversion.Global
}
}
public static void CopyBuildToOutput(BuilderOptions options)
{
throw new InvalidOperationException();
}
private static void Collect(HashSet<ObjectId> objectIds, ObjectId objectId, IAssetIndexMap assetIndexMap)
{
// Already added?
if (!objectIds.Add(objectId))
return;
using (var stream = AssetManager.FileProvider.OpenStream(DatabaseFileProvider.ObjectIdUrl + objectId, VirtualFileMode.Open, VirtualFileAccess.Read))
{
// Read chunk header
var streamReader = new BinarySerializationReader(stream);
var header = ChunkHeader.Read(streamReader);
// Only process chunks
if (header != null)
{
if (header.OffsetToReferences != -1)
{
// Seek to where references are stored and deserialize them
streamReader.NativeStream.Seek(header.OffsetToReferences, SeekOrigin.Begin);
List<ChunkReference> references = null;
streamReader.Serialize(ref references, ArchiveMode.Deserialize);
foreach (var reference in references)
{
ObjectId refObjectId;
var databaseFileProvider = DatabaseFileProvider.ResolveObjectId(reference.Location, out refObjectId);
if (databaseFileProvider != null)
{
Collect(objectIds, refObjectId, databaseFileProvider.AssetIndexMap);
}
}
}
}
}
}
public static void Cancel(Builder builder, ConsoleCancelEventArgs e)
{
if (builder != null && builder.IsRunning)
{
e.Cancel = true;
builder.CancelBuild();
}
}
}
}
| {
"pile_set_name": "Github"
} |
File: commonSuperTypeOfErrorTypes.kt - b98ae2d1729bb4300b162b3460df211d
NL("\n")
NL("\n")
NL("\n")
packageHeader
importList
topLevelObject
declaration
classDeclaration
CLASS("class")
simpleIdentifier
Identifier("Foo")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
semis
NL("\n")
topLevelObject
declaration
classDeclaration
CLASS("class")
simpleIdentifier
Identifier("Bar")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("S")
RANGLE(">")
semis
NL("\n")
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
simpleIdentifier
Identifier("consume")
functionValueParameters
LPAREN("(")
functionValueParameter
parameter
simpleIdentifier
Identifier("x")
COLON(":")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Foo")
typeArguments
LANGLE("<")
typeProjection
typeProjectionModifiers
typeProjectionModifier
varianceModifier
OUT("out")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
COMMA(",")
functionValueParameter
parameter
simpleIdentifier
Identifier("y")
COLON(":")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Foo")
typeArguments
LANGLE("<")
typeProjection
typeProjectionModifiers
typeProjectionModifier
varianceModifier
OUT("out")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
RPAREN(")")
functionBody
block
LCURL("{")
statements
RCURL("}")
semis
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
simpleIdentifier
Identifier("materialize")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
literalConstant
NullLiteral("null")
asOperator
AS("as")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
semis
NL("\n")
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
simpleIdentifier
Identifier("test")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
block
LCURL("{")
NL("\n")
statements
statement
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("consume")
callSuffix
valueArguments
LPAREN("(")
valueArgument
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("materialize")
callSuffix
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Foo")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Bar")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("ErrorType")
RANGLE(">")
RANGLE(">")
RANGLE(">")
valueArguments
LPAREN("(")
RPAREN(")")
COMMA(",")
valueArgument
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("materialize")
callSuffix
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Foo")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Bar")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("ErrorType")
RANGLE(">")
RANGLE(">")
RANGLE(">")
valueArguments
LPAREN("(")
RPAREN(")")
RPAREN(")")
semis
NL("\n")
NL("\n")
statement
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("consume")
callSuffix
valueArguments
LPAREN("(")
valueArgument
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("materialize")
callSuffix
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Foo")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Bar")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("ErrorType")
RANGLE(">")
RANGLE(">")
RANGLE(">")
valueArguments
LPAREN("(")
RPAREN(")")
COMMA(",")
valueArgument
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("materialize")
callSuffix
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Foo")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("ErrorType")
RANGLE(">")
RANGLE(">")
valueArguments
LPAREN("(")
RPAREN(")")
RPAREN(")")
semis
NL("\n")
NL("\n")
RCURL("}")
semis
NL("\n")
EOF("<EOF>")
| {
"pile_set_name": "Github"
} |
This directory contains source and tests for the lldb test runner
architecture. This directory is not for lldb python tests. It
is the test runner. The tests under this diretory are test-runner
tests (i.e. tests that verify the test runner itself runs properly).
| {
"pile_set_name": "Github"
} |
# Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]
| {
"pile_set_name": "Github"
} |
require('../../modules/web.dom.iterable');
module.exports = require('../../modules/$.core'); | {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.