text stringlengths 2 99k | meta dict |
|---|---|
//
// main.m
// RegisteredLoggingTest
//
// Created by Robbie Hanson on 9/5/11.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[])
{
@autoreleasepool {
int retVal = UIApplicationMain(argc, argv, nil, nil);
return retVal;
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2005 bayside
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN TEXT OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#if !defined(_TEXTLISTENER_H_INCLUDED_)
#define _TEXTLISTENER_H_INCLUDED_
namespace monagui {
/**
IMEリスナークラス
*/
class TextListener {
public:
/** テキストの値が変更された時に呼ばれる */
virtual void textValueChanged(TextEvent* e) = 0;
};
}
#endif // _TEXTLISTENER_H_INCLUDED_
| {
"pile_set_name": "Github"
} |
/*
* Simple tool for setting an icon on a file.
*/
#import <Cocoa/Cocoa.h>
#include <stdio.h>
int main(int argc, char** argv)
{
if (argc != 3) {
fprintf(stderr, "Usage: seticon ICON TARGET");
return 1;
}
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSString* iconPath = [NSString stringWithUTF8String:argv[1]];
NSString* filePath = [NSString stringWithUTF8String:argv[2]];
[NSApplication sharedApplication];
[[NSWorkspace sharedWorkspace]
setIcon: [[NSImage alloc] initWithContentsOfFile: iconPath]
forFile: filePath
options: 0];
[pool release];
return 0;
}
| {
"pile_set_name": "Github"
} |
# cacache [](https://npm.im/cacache) [](https://npm.im/cacache) [](https://travis-ci.org/zkat/cacache) [](https://ci.appveyor.com/project/zkat/cacache) [](https://coveralls.io/github/zkat/cacache?branch=latest)
[`cacache`](https://github.com/zkat/cacache) es una librería de Node.js para
manejar caches locales en disco, con acceso tanto con claves únicas como
direcciones de contenido (hashes/hacheos). Es súper rápida, excelente con el
acceso concurrente, y jamás te dará datos incorrectos, aún si se corrompen o
manipulan directamente los ficheros del cache.
El propósito original era reemplazar el caché local de
[npm](https://npm.im/npm), pero se puede usar por su propia cuenta.
_Traducciones: [English](README.md)_
## Instalación
`$ npm install --save cacache`
## Índice
* [Ejemplo](#ejemplo)
* [Características](#características)
* [Cómo Contribuir](#cómo-contribuir)
* [API](#api)
* [Usando el API en español](#localized-api)
* Leer
* [`ls`](#ls)
* [`ls.flujo`](#ls-stream)
* [`saca`](#get-data)
* [`saca.flujo`](#get-stream)
* [`saca.info`](#get-info)
* [`saca.tieneDatos`](#get-hasContent)
* Escribir
* [`mete`](#put-data)
* [`mete.flujo`](#put-stream)
* [opciones para `mete*`](#put-options)
* [`rm.todo`](#rm-all)
* [`rm.entrada`](#rm-entry)
* [`rm.datos`](#rm-content)
* Utilidades
* [`ponLenguaje`](#set-locale)
* [`limpiaMemoizado`](#clear-memoized)
* [`tmp.hazdir`](#tmp-mkdir)
* [`tmp.conTmp`](#with-tmp)
* Integridad
* [Subresource Integrity](#integrity)
* [`verifica`](#verify)
* [`verifica.ultimaVez`](#verify-last-run)
### Ejemplo
```javascript
const cacache = require('cacache/es')
const fs = require('fs')
const tarbol = '/ruta/a/mi-tar.tgz'
const rutaCache = '/tmp/my-toy-cache'
const clave = 'mi-clave-única-1234'
// ¡Añádelo al caché! Usa `rutaCache` como raíz del caché.
cacache.mete(rutaCache, clave, '10293801983029384').then(integrity => {
console.log(`Saved content to ${rutaCache}.`)
})
const destino = '/tmp/mytar.tgz'
// Copia el contenido del caché a otro fichero, pero esta vez con flujos.
cacache.saca.flujo(
rutaCache, clave
).pipe(
fs.createWriteStream(destino)
).on('finish', () => {
console.log('extracción completada')
})
// La misma cosa, pero accesando el contenido directamente, sin tocar el índice.
cacache.saca.porHacheo(rutaCache, integridad).then(datos => {
fs.writeFile(destino, datos, err => {
console.log('datos del tarbol sacados basado en su sha512, y escrito a otro fichero')
})
})
```
### Características
* Extracción por clave o por dirección de contenido (shasum, etc)
* Usa el estándard de web, [Subresource Integrity](#integrity)
* Compatible con multiples algoritmos - usa sha1, sha512, etc, en el mismo caché sin problema
* Entradas con contenido idéntico comparten ficheros
* Tolerancia de fallas (inmune a corrupción, ficheros parciales, carreras de proceso, etc)
* Verificación completa de datos cuando (escribiendo y leyendo)
* Concurrencia rápida, segura y "lockless"
* Compatible con `stream`s (flujos)
* Compatible con `Promise`s (promesas)
* Bastante rápida -- acceso, incluyendo verificación, en microsegundos
* Almacenaje de metadatos arbitrarios
* Colección de basura y verificación adicional fuera de banda
* Cobertura rigurosa de pruebas
* Probablente hay un "Bloom filter" por ahí en algún lado. Eso le mola a la gente, ¿Verdad? 🤔
### Cómo Contribuir
El equipo de cacache felizmente acepta contribuciones de código y otras maneras de participación. ¡Hay muchas formas diferentes de contribuir! La [Guía de Colaboradores](CONTRIBUTING.md) (en inglés) tiene toda la información que necesitas para cualquier tipo de contribución: todo desde cómo reportar errores hasta cómo someter parches con nuevas características. Con todo y eso, no se preocupe por si lo que haces está exáctamente correcto: no hay ningún problema en hacer preguntas si algo no está claro, o no lo encuentras.
El equipo de cacache tiene miembros hispanohablantes: es completamente aceptable crear `issues` y `pull requests` en español/castellano.
Todos los participantes en este proyecto deben obedecer el [Código de Conducta](CODE_OF_CONDUCT.md) (en inglés), y en general actuar de forma amable y respetuosa mientras participan en esta comunidad.
Por favor refiérase al [Historial de Cambios](CHANGELOG.md) (en inglés) para detalles sobre cambios importantes incluídos en cada versión.
Finalmente, cacache tiene un sistema de localización de lenguaje. Si te interesa añadir lenguajes o mejorar los que existen, mira en el directorio `./locales` para comenzar.
Happy hacking!
### API
#### <a name="localized-api"></a> Usando el API en español
cacache incluye una traducción completa de su API al castellano, con las mismas
características. Para usar el API como está documentado en este documento, usa
`require('cacache/es')`
cacache también tiene otros lenguajes: encuéntralos bajo `./locales`, y podrás
usar el API en ese lenguaje con `require('cacache/<lenguaje>')`
#### <a name="ls"></a> `> cacache.ls(cache) -> Promise<Object>`
Enumera todas las entradas en el caché, dentro de un solo objeto. Cada entrada
en el objeto tendrá como clave la clave única usada para el índice, el valor
siendo un objeto de [`saca.info`](#get-info).
##### Ejemplo
```javascript
cacache.ls(rutaCache).then(console.log)
// Salida
{
'my-thing': {
key: 'my-thing',
integrity: 'sha512-BaSe64/EnCoDED+HAsh=='
path: '.testcache/content/deadbeef', // unido con `rutaCache`
time: 12345698490,
size: 4023948,
metadata: {
name: 'blah',
version: '1.2.3',
description: 'this was once a package but now it is my-thing'
}
},
'other-thing': {
key: 'other-thing',
integrity: 'sha1-ANothER+hasH=',
path: '.testcache/content/bada55',
time: 11992309289,
size: 111112
}
}
```
#### <a name="ls-stream"></a> `> cacache.ls.flujo(cache) -> Readable`
Enumera todas las entradas en el caché, emitiendo un objeto de
[`saca.info`](#get-info) por cada evento de `data` en el flujo.
##### Ejemplo
```javascript
cacache.ls.flujo(rutaCache).on('data', console.log)
// Salida
{
key: 'my-thing',
integrity: 'sha512-BaSe64HaSh',
path: '.testcache/content/deadbeef', // unido con `rutaCache`
time: 12345698490,
size: 13423,
metadata: {
name: 'blah',
version: '1.2.3',
description: 'this was once a package but now it is my-thing'
}
}
{
key: 'other-thing',
integrity: 'whirlpool-WoWSoMuchSupport',
path: '.testcache/content/bada55',
time: 11992309289,
size: 498023984029
}
{
...
}
```
#### <a name="get-data"></a> `> cacache.saca(cache, clave, [ops]) -> Promise({data, metadata, integrity})`
Devuelve un objeto con los datos, hacheo de integridad y metadatos identificados
por la `clave`. La propiedad `data` de este objeto será una instancia de
`Buffer` con los datos almacenados en el caché. to do with it! cacache just
won't care.
`integrity` es un `string` de [Subresource Integrity](#integrity). Dígase, un
`string` que puede ser usado para verificar a la `data`, que tiene como formato
`<algoritmo>-<hacheo-integridad-base64>`.
So no existe ninguna entrada identificada por `clave`, o se los datos
almacenados localmente fallan verificación, el `Promise` fallará.
Una sub-función, `saca.porHacheo`, tiene casi el mismo comportamiento, excepto
que busca entradas usando el hacheo de integridad, sin tocar el índice general.
Esta versión *sólo* devuelve `data`, sin ningún objeto conteniéndola.
##### Nota
Esta función lee la entrada completa a la memoria antes de devolverla. Si estás
almacenando datos Muy Grandes, es posible que [`saca.flujo`](#get-stream) sea
una mejor solución.
##### Ejemplo
```javascript
// Busca por clave
cache.saca(rutaCache, 'my-thing').then(console.log)
// Salida:
{
metadata: {
thingName: 'my'
},
integrity: 'sha512-BaSe64HaSh',
data: Buffer#<deadbeef>,
size: 9320
}
// Busca por hacheo
cache.saca.porHacheo(rutaCache, 'sha512-BaSe64HaSh').then(console.log)
// Salida:
Buffer#<deadbeef>
```
#### <a name="get-stream"></a> `> cacache.saca.flujo(cache, clave, [ops]) -> Readable`
Devuelve un [Readable
Stream](https://nodejs.org/api/stream.html#stream_readable_streams) de los datos
almacenados bajo `clave`.
So no existe ninguna entrada identificada por `clave`, o se los datos
almacenados localmente fallan verificación, el `Promise` fallará.
`metadata` y `integrity` serán emitidos como eventos antes de que el flujo
cierre.
Una sub-función, `saca.flujo.porHacheo`, tiene casi el mismo comportamiento,
excepto que busca entradas usando el hacheo de integridad, sin tocar el índice
general. Esta versión no emite eventos de `metadata` o `integrity`.
##### Ejemplo
```javascript
// Busca por clave
cache.saca.flujo(
rutaCache, 'my-thing'
).on('metadata', metadata => {
console.log('metadata:', metadata)
}).on('integrity', integrity => {
console.log('integrity:', integrity)
}).pipe(
fs.createWriteStream('./x.tgz')
)
// Salidas:
metadata: { ... }
integrity: 'sha512-SoMeDIGest+64=='
// Busca por hacheo
cache.saca.flujo.porHacheo(
rutaCache, 'sha512-SoMeDIGest+64=='
).pipe(
fs.createWriteStream('./x.tgz')
)
```
#### <a name="get-info"></a> `> cacache.saca.info(cache, clave) -> Promise`
Busca la `clave` en el índice del caché, devolviendo información sobre la
entrada si existe.
##### Campos
* `key` - Clave de la entrada. Igual al argumento `clave`.
* `integrity` - [hacheo de Subresource Integrity](#integrity) del contenido al que se refiere esta entrada.
* `path` - Dirección del fichero de datos almacenados, relativa al argumento `cache`.
* `time` - Hora de creación de la entrada
* `metadata` - Metadatos asignados a esta entrada por el usuario
##### Ejemplo
```javascript
cacache.saca.info(rutaCache, 'my-thing').then(console.log)
// Salida
{
key: 'my-thing',
integrity: 'sha256-MUSTVERIFY+ALL/THINGS=='
path: '.testcache/content/deadbeef',
time: 12345698490,
size: 849234,
metadata: {
name: 'blah',
version: '1.2.3',
description: 'this was once a package but now it is my-thing'
}
}
```
#### <a name="get-hasContent"></a> `> cacache.saca.tieneDatos(cache, integrity) -> Promise`
Busca un [hacheo Subresource Integrity](#integrity) en el caché. Si existe el
contenido asociado con `integrity`, devuelve un objeto con dos campos: el hacheo
_específico_ que se usó para la búsqueda, `sri`, y el tamaño total del
contenido, `size`. Si no existe ningún contenido asociado con `integrity`,
devuelve `false`.
##### Ejemplo
```javascript
cacache.saca.tieneDatos(rutaCache, 'sha256-MUSTVERIFY+ALL/THINGS==').then(console.log)
// Salida
{
sri: {
source: 'sha256-MUSTVERIFY+ALL/THINGS==',
algorithm: 'sha256',
digest: 'MUSTVERIFY+ALL/THINGS==',
options: []
},
size: 9001
}
cacache.saca.tieneDatos(rutaCache, 'sha521-NOT+IN/CACHE==').then(console.log)
// Salida
false
```
#### <a name="put-data"></a> `> cacache.mete(cache, clave, datos, [ops]) -> Promise`
Inserta `datos` en el caché. El `Promise` devuelto se resuelve con un hacheo
(generado conforme a [`ops.algorithms`](#optsalgorithms)) después que la entrada
haya sido escrita en completo.
##### Ejemplo
```javascript
fetch(
'https://registry.npmjs.org/cacache/-/cacache-1.0.0.tgz'
).then(datos => {
return cacache.mete(rutaCache, 'registry.npmjs.org|cacache@1.0.0', datos)
}).then(integridad => {
console.log('el hacheo de integridad es', integridad)
})
```
#### <a name="put-stream"></a> `> cacache.mete.flujo(cache, clave, [ops]) -> Writable`
Devuelve un [Writable
Stream](https://nodejs.org/api/stream.html#stream_writable_streams) que inserta
al caché los datos escritos a él. Emite un evento `integrity` con el hacheo del
contenido escrito, cuando completa.
##### Ejemplo
```javascript
request.get(
'https://registry.npmjs.org/cacache/-/cacache-1.0.0.tgz'
).pipe(
cacache.mete.flujo(
rutaCache, 'registry.npmjs.org|cacache@1.0.0'
).on('integrity', d => console.log(`integrity digest is ${d}`))
)
```
#### <a name="put-options"></a> `> opciones para cacache.mete`
La funciones `cacache.mete` tienen un número de opciones en común.
##### `ops.metadata`
Metadatos del usuario que se almacenarán con la entrada.
##### `ops.size`
El tamaño declarado de los datos que se van a insertar. Si es proveído, cacache
verificará que los datos escritos sean de ese tamaño, o si no, fallará con un
error con código `EBADSIZE`.
##### `ops.integrity`
El hacheo de integridad de los datos siendo escritos.
Si es proveído, y los datos escritos no le corresponden, la operación fallará
con un error con código `EINTEGRITY`.
`ops.algorithms` no tiene ningún efecto si esta opción está presente.
##### `ops.algorithms`
Por Defecto: `['sha512']`
Algoritmos que se deben usar cuando se calcule el hacheo de [subresource
integrity](#integrity) para los datos insertados. Puede usar cualquier algoritmo
enumerado en `crypto.getHashes()`.
Por el momento, sólo se acepta un algoritmo (dígase, un array con exáctamente un
valor). No tiene ningún efecto si `ops.integrity` también ha sido proveido.
##### `ops.uid`/`ops.gid`
Si están presentes, cacache hará todo lo posible para asegurarse que todos los
ficheros creados en el proceso de sus operaciones en el caché usen esta
combinación en particular.
##### `ops.memoize`
Por Defecto: `null`
Si es verdad, cacache tratará de memoizar los datos de la entrada en memoria. La
próxima vez que el proceso corriente trate de accesar los datos o entrada,
cacache buscará en memoria antes de buscar en disco.
Si `ops.memoize` es un objeto regular o un objeto como `Map` (es decir, un
objeto con métodos `get()` y `set()`), este objeto en sí sera usado en vez del
caché de memoria global. Esto permite tener lógica específica a tu aplicación
encuanto al almacenaje en memoria de tus datos.
Si quieres asegurarte que los datos se lean del disco en vez de memoria, usa
`memoize: false` cuando uses funciones de `cacache.saca`.
#### <a name="rm-all"></a> `> cacache.rm.todo(cache) -> Promise`
Borra el caché completo, incluyendo ficheros temporeros, ficheros de datos, y el
índice del caché.
##### Ejemplo
```javascript
cacache.rm.todo(rutaCache).then(() => {
console.log('THE APOCALYPSE IS UPON US 😱')
})
```
#### <a name="rm-entry"></a> `> cacache.rm.entrada(cache, clave) -> Promise`
Alias: `cacache.rm`
Borra la entrada `clave` del índuce. El contenido asociado con esta entrada
seguirá siendo accesible por hacheo usando
[`saca.flujo.porHacheo`](#get-stream).
Para borrar el contenido en sí, usa [`rm.datos`](#rm-content). Si quieres hacer
esto de manera más segura (pues ficheros de contenido pueden ser usados por
multiples entradas), usa [`verifica`](#verify) para borrar huérfanos.
##### Ejemplo
```javascript
cacache.rm.entrada(rutaCache, 'my-thing').then(() => {
console.log('I did not like it anyway')
})
```
#### <a name="rm-content"></a> `> cacache.rm.datos(cache, integrity) -> Promise`
Borra el contenido identificado por `integrity`. Cualquier entrada que se
refiera a este contenido quedarán huérfanas y se invalidarán si se tratan de
accesar, al menos que contenido idéntico sea añadido bajo `integrity`.
##### Ejemplo
```javascript
cacache.rm.datos(rutaCache, 'sha512-SoMeDIGest/IN+BaSE64==').then(() => {
console.log('los datos para `mi-cosa` se borraron')
})
```
#### <a name="set-locale"></a> `> cacache.ponLenguaje(locale)`
Configura el lenguaje usado para mensajes y errores de cacache. La lista de
lenguajes disponibles está en el directorio `./locales` del proyecto.
_Te interesa añadir más lenguajes? [Somete un PR](CONTRIBUTING.md)!_
#### <a name="clear-memoized"></a> `> cacache.limpiaMemoizado()`
Completamente reinicializa el caché de memoria interno. Si estás usando tu
propio objecto con `ops.memoize`, debes hacer esto de manera específica a él.
#### <a name="tmp-mkdir"></a> `> tmp.hazdir(cache, ops) -> Promise<Path>`
Alias: `tmp.mkdir`
Devuelve un directorio único dentro del directorio `tmp` del caché.
Una vez tengas el directorio, es responsabilidad tuya asegurarte que todos los
ficheros escrito a él sean creados usando los permisos y `uid`/`gid` concordante
con el caché. Si no, puedes pedirle a cacache que lo haga llamando a
[`cacache.tmp.fix()`](#tmp-fix). Esta función arreglará todos los permisos en el
directorio tmp.
Si quieres que cacache limpie el directorio automáticamente cuando termines, usa
[`cacache.tmp.conTmp()`](#with-tpm).
##### Ejemplo
```javascript
cacache.tmp.mkdir(cache).then(dir => {
fs.writeFile(path.join(dir, 'blablabla'), Buffer#<1234>, ...)
})
```
#### <a name="with-tmp"></a> `> tmp.conTmp(cache, ops, cb) -> Promise`
Crea un directorio temporero con [`tmp.mkdir()`](#tmp-mkdir) y ejecuta `cb` con
él como primer argumento. El directorio creado será removido automáticamente
cuando el valor devolvido por `cb()` se resuelva.
Las mismas advertencias aplican en cuanto a manejando permisos para los ficheros
dentro del directorio.
##### Ejemplo
```javascript
cacache.tmp.conTmp(cache, dir => {
return fs.writeFileAsync(path.join(dir, 'blablabla'), Buffer#<1234>, ...)
}).then(() => {
// `dir` no longer exists
})
```
#### <a name="integrity"></a> Hacheos de Subresource Integrity
cacache usa strings que siguen la especificación de [Subresource Integrity
spec](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
Es decir, donde quiera cacache espera un argumento o opción `integrity`, ese
string debería usar el formato `<algoritmo>-<hacheo-base64>`.
Una variación importante sobre los hacheos que cacache acepta es que acepta el
nombre de cualquier algoritmo aceptado por el proceso de Node.js donde se usa.
Puedes usar `crypto.getHashes()` para ver cuales están disponibles.
##### Generando tus propios hacheos
Si tienes un `shasum`, en general va a estar en formato de string hexadecimal
(es decir, un `sha1` se vería como algo así:
`5f5513f8822fdbe5145af33b64d8d970dcf95c6e`).
Para ser compatible con cacache, necesitas convertir esto a su equivalente en
subresource integrity. Por ejemplo, el hacheo correspondiente al ejemplo
anterior sería: `sha1-X1UT+IIv2+UUWvM7ZNjZcNz5XG4=`.
Puedes usar código así para generarlo por tu cuenta:
```javascript
const crypto = require('crypto')
const algoritmo = 'sha512'
const datos = 'foobarbaz'
const integrity = (
algorithm +
'-' +
crypto.createHash(algoritmo).update(datos).digest('base64')
)
```
También puedes usar [`ssri`](https://npm.im/ssri) para deferir el trabajo a otra
librería que garantiza que todo esté correcto, pues maneja probablemente todas
las operaciones que tendrías que hacer con SRIs, incluyendo convirtiendo entre
hexadecimal y el formato SRI.
#### <a name="verify"></a> `> cacache.verifica(cache, ops) -> Promise`
Examina y arregla tu caché:
* Limpia entradas inválidas, huérfanas y corrompidas
* Te deja filtrar cuales entradas retener, con tu propio filtro
* Reclama cualquier ficheros de contenido sin referencias en el índice
* Verifica integridad de todos los ficheros de contenido y remueve los malos
* Arregla permisos del caché
* Remieve el directorio `tmp` en el caché, y todo su contenido.
Cuando termine, devuelve un objeto con varias estadísticas sobre el proceso de
verificación, por ejemplo la cantidad de espacio de disco reclamado, el número
de entradas válidas, número de entradas removidas, etc.
##### Opciones
* `ops.uid` - uid para asignarle al caché y su contenido
* `ops.gid` - gid para asignarle al caché y su contenido
* `ops.filter` - recibe una entrada como argumento. Devuelve falso para removerla. Nota: es posible que esta función sea invocada con la misma entrada más de una vez.
##### Example
```sh
echo somegarbage >> $RUTACACHE/content/deadbeef
```
```javascript
cacache.verifica(rutaCache).then(stats => {
// deadbeef collected, because of invalid checksum.
console.log('cache is much nicer now! stats:', stats)
})
```
#### <a name="verify-last-run"></a> `> cacache.verifica.ultimaVez(cache) -> Promise`
Alias: `últimaVez`
Devuelve un `Date` que representa la última vez que `cacache.verifica` fue
ejecutada en `cache`.
##### Example
```javascript
cacache.verifica(rutaCache).then(() => {
cacache.verifica.ultimaVez(rutaCache).then(última => {
console.log('La última vez que se usó cacache.verifica() fue ' + última)
})
})
```
| {
"pile_set_name": "Github"
} |
package com.plaid.quickstart;
import io.dropwizard.Configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.*;
public class QuickstartConfiguration extends Configuration {
@NotEmpty
private String plaidClientID;
@NotEmpty
private String plaidSecret;
@NotEmpty
private String plaidEnv;
@NotEmpty
private String plaidProducts;
@NotEmpty
private String plaidCountryCodes;
// Parameters used for the OAuth redirect Link flow.
// Set PLAID_REDIRECT_URI to 'http://localhost:8000/oauth-response.html'
// The OAuth redirect flow requires an endpoint on the developer's website
// that the bank website should redirect to. You will need to configure
// this redirect URI for your client ID through the Plaid developer dashboard
// at https://dashboard.plaid.com/team/api.
private String plaidRedirectUri;
@JsonProperty
public String getPlaidClientID() {
return plaidClientID;
}
@JsonProperty
public String getPlaidSecret() {
return plaidSecret;
}
@JsonProperty
public String getPlaidEnv() {
return plaidEnv;
}
@JsonProperty
public String getPlaidProducts() {
return plaidProducts;
}
@JsonProperty
public String getPlaidCountryCodes() {
return plaidCountryCodes;
}
@JsonProperty
public String getPlaidRedirectUri() {
return plaidRedirectUri;
}
}
| {
"pile_set_name": "Github"
} |
Anton Gorenko
| {
"pile_set_name": "Github"
} |
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(void 0);
* // => false
*/
function isNull(value) {
return value === null;
}
module.exports = isNull;
| {
"pile_set_name": "Github"
} |
#! /bin/bash -e
OVERLAY="$1"
NAME="$2"
FREQ=40000
BASE=$(dirname "$0")
TARGET="$BASE"/core-$NAME
[ $# -ge 2 -a -f "$OVERLAY" ] || { cat <<EOF
Usage: $0 overlay-archive-to-import core-name [frequency-in-KHz]
overlay-archive-to-import: file name of xtensa-config-overlay.tar.gz
to import configuration from.
core-name: QEMU name of the imported core. Must be valid
C identifier.
frequency-in-KHz: core frequency (40MHz if not specified).
EOF
exit
}
[ $# -ge 3 ] && FREQ="$3"
mkdir -p "$TARGET"
tar -xf "$OVERLAY" -C "$TARGET" --strip-components=1 \
--xform='s/core/core-isa/' config/core.h
tar -xf "$OVERLAY" -O gdb/xtensa-config.c | \
sed -n '1,/*\//p;/XTREG/,/XTREG_END/p' > "$TARGET"/gdb-config.c
cat <<EOF > "${TARGET}.c"
#include "cpu.h"
#include "exec/exec-all.h"
#include "exec/gdbstub.h"
#include "qemu/host-utils.h"
#include "core-$NAME/core-isa.h"
#include "overlay_tool.h"
static XtensaConfig $NAME __attribute__((unused)) = {
.name = "$NAME",
.gdb_regmap = {
.reg = {
#include "core-$NAME/gdb-config.c"
}
},
.clock_freq_khz = $FREQ,
DEFAULT_SECTIONS
};
REGISTER_CORE($NAME)
EOF
grep -q core-${NAME}.o "$BASE"/Makefile.objs || \
echo "obj-y += core-${NAME}.o" >> "$BASE"/Makefile.objs
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Guardian.Cli.win10-x64" version="0.20.1"/>
</packages>
| {
"pile_set_name": "Github"
} |
package com.beijunyi.parallelgit.filesystem;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.AccessMode;
import java.nio.file.NoSuchFileException;
import org.junit.Before;
import org.junit.Test;
import static org.eclipse.jgit.lib.FileMode.EXECUTABLE_FILE;
public class GitFileSystemProviderCheckAccessTest extends AbstractGitFileSystemTest {
@Before
public void setupFileSystem() throws IOException {
initRepository();
writeToCache("dir/file.txt");
writeToCache("dir/executable.sh", someBytes(), EXECUTABLE_FILE);
commitToMaster();
initGitFileSystem();
}
@Test
public void fileCheckReadAccess() throws IOException {
provider.checkAccess(gfs.getPath("/dir/file.txt"), AccessMode.READ);
}
@Test
public void fileCheckWriteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/dir/file.txt"), AccessMode.WRITE);
}
@Test
public void fileCheckReadWriteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/dir/file.txt"), AccessMode.READ, AccessMode.WRITE);
}
@Test(expected = AccessDeniedException.class)
public void fileCheckExecuteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/dir/file.txt"), AccessMode.EXECUTE);
}
@Test
public void executableFileCheckExecuteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/dir/executable.sh"), AccessMode.EXECUTE);
}
@Test
public void directoryCheckReadAccess() throws IOException {
provider.checkAccess(gfs.getPath("/dir"), AccessMode.READ);
}
@Test
public void directoryCheckWriteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/dir"), AccessMode.WRITE);
}
@Test
public void directoryCheckReadWriteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/dir"), AccessMode.READ, AccessMode.WRITE);
}
@Test(expected = AccessDeniedException.class)
public void directoryCheckExecuteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/dir"), AccessMode.EXECUTE);
}
@Test
public void rootCheckReadAccess() throws IOException {
provider.checkAccess(gfs.getPath("/"), AccessMode.READ);
}
@Test
public void rootCheckWriteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/"), AccessMode.WRITE);
}
@Test
public void rootCheckReadWriteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/"), AccessMode.READ, AccessMode.WRITE);
}
@Test(expected = AccessDeniedException.class)
public void rootCheckExecuteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/"), AccessMode.EXECUTE);
}
@Test(expected = NoSuchFileException.class)
public void nonExistentFileCheckReadAccess() throws IOException {
provider.checkAccess(gfs.getPath("/non_existent_file.txt"), AccessMode.READ);
}
@Test(expected = NoSuchFileException.class)
public void nonExistentFileCheckWriteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/non_existent_file.txt"), AccessMode.WRITE);
}
@Test(expected = NoSuchFileException.class)
public void nonExistentFileCheckReadWriteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/non_existent_file.txt"), AccessMode.READ, AccessMode.WRITE);
}
@Test(expected = NoSuchFileException.class)
public void nonExistentFileCheckExecuteAccess() throws IOException {
provider.checkAccess(gfs.getPath("/non_existent_file.txt"), AccessMode.EXECUTE);
}
}
| {
"pile_set_name": "Github"
} |
diff --git a/configure.ac b/configure.ac
index ee63091..1d09ade 100644
--- a/configure.ac
+++ b/configure.ac
@@ -69,6 +69,8 @@ examples/echo/echo-keygen/Makefile
examples/echo/echo-server/Makefile
doc/Makefile])
+AC_ARG_VAR([AR], [Specifies the archiver to use])
+
AC_ARG_WITH([libsodium],
[AS_HELP_STRING([--with-libsodium],
[use libsodium for crypto @<:@default=check@:>@])],
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='UTF-8'?>
<!--
TITLE: db0b6ac6-874a-498e-892b-ac7c2020e061.ioc
VERSION: 1.0
DESCRIPTION: OpenIOC file
LICENSE: Copyright 2014 FireEye Corporation. Licensed under the Apache 2.0 license.
FireEye 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.
-->
<ioc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.mandiant.com/2010/ioc" id="db0b6ac6-874a-498e-892b-ac7c2020e061" last-modified="2014-11-21T17:13:09Z">
<short_description>OPERATION DOUBLE TAP (BLOG)</short_description>
<description>This IOC contains indicators detailed in the blog post "Operation Double Tap" that can be read here: https://www.fireeye.com/blog/threat-research/2014/11/operation_doubletap.html. This IOC contains indicators for a spearphishing campaign carried out by APT3.</description>
<keywords/>
<authored_by>FireEye</authored_by>
<authored_date>2014-11-21T16:02:16Z</authored_date>
<links>
<link rel="threatgroup">APT3</link>
<link rel="threatcategory">APT</link>
<link rel="category">Downloader</link>
<link rel="license">Apache 2.0</link>
</links>
<definition>
<Indicator id="913a13b9-7b27-4545-82a7-5f79379887c4" operator="OR">
<IndicatorItem id="1817f443-6ef0-430a-ae3b-ec67625bdf8c" condition="is">
<Context document="FileItem" search="FileItem/Md5sum" type="mir"/>
<Content type="md5">5a0c4e1925c76a959ab0588f683ab437</Content>
</IndicatorItem>
<IndicatorItem id="fa516ed8-abad-4d18-9a58-dad86b8ec673" condition="is">
<Context document="FileItem" search="FileItem/Md5sum" type="mir"/>
<Content type="md5">492a839a3bf9c61b7065589a18c5aa8d</Content>
</IndicatorItem>
<IndicatorItem id="c987c697-71b1-4618-b8b3-e4b4479fb955" condition="is">
<Context document="FileItem" search="FileItem/Md5sum" type="mir"/>
<Content type="md5">744a17a3bc6dbd535f568ef1e87d8b9a</Content>
</IndicatorItem>
<IndicatorItem id="874eaa02-c369-4e7f-bd8e-51bb3cb4b14a" condition="is">
<Context document="FileItem" search="FileItem/Md5sum" type="mir"/>
<Content type="md5">5c08957f05377004376e6a622406f9aa</Content>
</IndicatorItem>
<IndicatorItem id="3442cfc6-7a16-4df7-bc37-2cd53628c64c" condition="is">
<Context document="FileItem" search="FileItem/Md5sum" type="mir"/>
<Content type="md5">8849538ef1c3471640230605c2623c67</Content>
</IndicatorItem>
<IndicatorItem id="80a94416-f08a-4428-8807-f0f8b1975be0" condition="contains">
<Context document="DnsEntryItem" search="DnsEntryItem/RecordName" type="mir"/>
<Content type="string">join.playboysplus.com</Content>
</IndicatorItem>
<IndicatorItem id="fa1c1b69-274f-42e0-90f6-b5da1f79f933" condition="contains">
<Context document="DnsEntryItem" search="DnsEntryItem/RecordName" type="mir"/>
<Content type="string">inform.bedircati.com</Content>
</IndicatorItem>
<IndicatorItem id="f38535da-5a76-41a7-9132-33b89622ff5d" condition="contains">
<Context document="DnsEntryItem" search="DnsEntryItem/RecordName" type="mir"/>
<Content type="string">pn.lamb-site.com</Content>
</IndicatorItem>
<IndicatorItem id="8fc8bfca-c183-4de8-ad09-6e59200f50f8" condition="contains">
<Context document="DnsEntryItem" search="DnsEntryItem/RecordName" type="mir"/>
<Content type="string">securitywap.com</Content>
</IndicatorItem>
<IndicatorItem id="30f8f64c-7dd2-446c-ac38-e2fb976ce5a4" condition="contains">
<Context document="DnsEntryItem" search="DnsEntryItem/RecordName" type="mir"/>
<Content type="string">walterclean.com</Content>
</IndicatorItem>
<IndicatorItem id="243d75b5-b297-43c1-b23f-8adbd64a24bf" condition="contains">
<Context document="PortItem" search="PortItem/remoteIP" type="mir"/>
<Content type="IP">192.157.198.103</Content>
</IndicatorItem>
<IndicatorItem id="ef749445-2e6d-4dd2-94cd-d1c42dae0f1e" condition="contains">
<Context document="PortItem" search="PortItem/remoteIP" type="mir"/>
<Content type="IP">192.184.60.229</Content>
</IndicatorItem>
<IndicatorItem id="0cabbc62-7898-4b60-81be-e7e5cd9f45b8" condition="contains">
<Context document="PortItem" search="PortItem/remoteIP" type="mir"/>
<Content type="IP">198.55.115.71</Content>
</IndicatorItem>
<IndicatorItem id="6ad592ae-b3f5-4098-a86a-44faac241e5f" condition="contains">
<Context document="PortItem" search="PortItem/remoteIP" type="mir"/>
<Content type="IP">210.109.99.64</Content>
</IndicatorItem>
<IndicatorItem id="02c77f79-d893-463c-9877-5e077dc47daf" condition="contains">
<Context document="PortItem" search="PortItem/remoteIP" type="mir"/>
<Content type="IP">104.151.248.173</Content>
</IndicatorItem>
<IndicatorItem id="bf5d9d0e-51d6-4385-aa98-7fe0efa88089" condition="is">
<Context document="FileItem" search="FileItem/FullPath" type="mir"/>
<Content type="string">C:\Users\Public\doc.exe</Content>
</IndicatorItem>
<IndicatorItem id="af184ec2-2798-4f7b-88e3-9cdd8af4d25c" condition="is">
<Context document="FileItem" search="FileItem/FullPath" type="mir"/>
<Content type="string">C:\Users\Public\test.exe</Content>
</IndicatorItem>
<IndicatorItem id="89aca0a4-c5b7-4ecd-b639-ed285423da0b" condition="contains">
<Context document="FileItem" search="FileItem/FullPath" type="mir"/>
<Content type="string">AppData\Local\Temp\notepad1.exe</Content>
</IndicatorItem>
<IndicatorItem id="1a437cb3-274c-4d18-9f2c-5d116b68e6e4" condition="contains">
<Context document="FileItem" search="FileItem/FullPath" type="mir"/>
<Content type="string">AppData\Local\Temp\notepad.exe</Content>
</IndicatorItem>
<IndicatorItem id="5da8c5a7-42bd-44b0-89b0-264679885cb3" condition="contains">
<Context document="FileItem" search="FileItem/FullPath" type="mir"/>
<Content type="string">AppData\Local\Temp\newnotepad.exe</Content>
</IndicatorItem>
<IndicatorItem id="b057cfd8-48c3-4d70-a5bf-871974c75f7f" condition="contains">
<Context document="FileItem" search="FileItem/FullPath" type="mir"/>
<Content type="string">AppData\Local\Temp\notepad2.exe</Content>
</IndicatorItem>
<IndicatorItem id="35bd099b-0030-4ec3-8fe4-386235cdd124" condition="contains">
<Context document="FileItem" search="FileItem/FullPath" type="mir"/>
<Content type="string">AppData\Local\Temp\note.txt</Content>
</IndicatorItem>
<IndicatorItem id="fb92c3b8-c770-453d-8942-249a5287744e" condition="is">
<Context document="FileItem" search="FileItem/StringList/string" type="mir"/>
<Content type="string">c:\Users\aa\Documents\Visual Studio 2008\Projects\MShell\Release\MShell.pdb</Content>
</IndicatorItem>
<IndicatorItem id="70acd39a-bbd9-44f0-95ef-29e5a65c70ba" condition="is">
<Context document="FileItem" search="FileItem/StringList/string" type="mir"/>
<Content type="string">c:\Users\aa\Documents\Visual Studio 2008\Projects\4113\Release\4113.pdb</Content>
</IndicatorItem>
<IndicatorItem id="1f9da0fd-06d1-44f2-b7db-6c0a817db532" condition="is">
<Context document="FileItem" search="FileItem/StringList/string" type="mir"/>
<Content type="string">C:\Users\aa\Documents\Visual Studio 2010\Projects\MyRat\Client\Client\obj\x86\Release\Client.pdb</Content>
</IndicatorItem>
<IndicatorItem id="4bbc1f95-db58-4f09-be5f-8b7f436b26e9" condition="contains">
<Context document="FileItem" search="FileItem/StringList/string" type="mir"/>
<Content type="string">C:\Users\aa\Documents\Visual Studio 2010\Projects</Content>
</IndicatorItem>
<IndicatorItem id="d7fff4c4-0c0e-4cbe-afe0-31715237f531" condition="is">
<Context document="TaskItem" search="TaskItem/ActionList/Action/ExecProgramPath" type="mir"/>
<Content type="string">C:\Users\Public\test.exe</Content>
</IndicatorItem>
<Indicator id="1c095197-148b-4c31-8760-704793a674b5" operator="AND">
<IndicatorItem id="198ef6ca-64f7-4484-b325-406656e2dac5" condition="contains">
<Context document="TaskItem" search="TaskItem/Name" type="mir"/>
<Content type="string">mysc</Content>
</IndicatorItem>
<Indicator id="fdc61631-2435-447a-a07a-d973fbd97184" operator="OR">
<IndicatorItem id="7e2e355c-ca9c-4a19-92a0-c02d14e5bbcb" condition="is">
<Context document="TaskItem" search="TaskItem/TriggerList/Trigger/TriggerFrequency" type="mir"/>
<Content type="string">TASK_TRIGGER_LOGON</Content>
</IndicatorItem>
<IndicatorItem id="d8447a59-ab54-4fa4-9609-7e03fdbd689b" condition="is">
<Context document="TaskItem" search="TaskItem/AccountName" type="mir"/>
<Content type="string">SYSTEM</Content>
</IndicatorItem>
</Indicator>
</Indicator>
</Indicator>
</definition>
</ioc>
| {
"pile_set_name": "Github"
} |
// -*- C++ -*-
// Definition for Win32 Export directives.
// This file is generated automatically by generate_export_file.pl
// ------------------------------
#ifndef TAO_LOADBALANCING_EXPORT_H
#define TAO_LOADBALANCING_EXPORT_H
#include "ace/config-all.h"
#if defined (TAO_AS_STATIC_LIBS)
# if !defined (TAO_LOADBALANCING_HAS_DLL)
# define TAO_LOADBALANCING_HAS_DLL 0
# endif /* ! TAO_LOADBALANCING_HAS_DLL */
#else
# if !defined (TAO_LOADBALANCING_HAS_DLL)
# define TAO_LOADBALANCING_HAS_DLL 1
# endif /* ! TAO_LOADBALANCING_HAS_DLL */
#endif
#if defined (TAO_LOADBALANCING_HAS_DLL) && (TAO_LOADBALANCING_HAS_DLL == 1)
# if defined (TAO_LOADBALANCING_BUILD_DLL)
# define TAO_LoadBalancing_Export ACE_Proper_Export_Flag
# define TAO_LOADBALANCING_SINGLETON_DECLARATION(T) ACE_EXPORT_SINGLETON_DECLARATION (T)
# define TAO_LOADBALANCING_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK)
# else /* TAO_LOADBALANCING_BUILD_DLL */
# define TAO_LoadBalancing_Export ACE_Proper_Import_Flag
# define TAO_LOADBALANCING_SINGLETON_DECLARATION(T) ACE_IMPORT_SINGLETON_DECLARATION (T)
# define TAO_LOADBALANCING_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK)
# endif /* TAO_LOADBALANCING_BUILD_DLL */
#else /* TAO_LOADBALANCING_HAS_DLL == 1 */
# define TAO_LoadBalancing_Export
# define TAO_LOADBALANCING_SINGLETON_DECLARATION(T)
# define TAO_LOADBALANCING_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK)
#endif /* TAO_LOADBALANCING_HAS_DLL == 1 */
#endif /* TAO_LOADBALANCING_EXPORT_H */
// End of auto generated file.
| {
"pile_set_name": "Github"
} |
auto: REMOVE_FILE,CREATE_FILE,MUNGE,COMPARE_FILE %TESTID%.stdout %TESTID%.stderr
test action: CMD_CAPTURE %SWAKS% --dump data --to user@host1.nodns.test.swaks.net --server ser.ver --data @%TESTDIR%/%TESTID%.eml --h-Header6 "TEST PASSED 6" --h-Header2 "TEST PASSED 2"
| {
"pile_set_name": "Github"
} |
// #docplaster
// #docregion
// #docregion component
import { Component } from '@angular/core';
// #enddocregion component
import '../assets/css/styles.css';
// #docregion component
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent { }
// #enddocregion
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Abs (Apache Commons Math 3.3 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Abs (Apache Commons Math 3.3 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Abs.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../../../org/apache/commons/math3/analysis/function/Acos.html" title="class in org.apache.commons.math3.analysis.function"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/commons/math3/analysis/function/Abs.html" target="_top">Frames</a></li>
<li><a href="Abs.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.commons.math3.analysis.function</div>
<h2 title="Class Abs" class="title">Class Abs</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">java.lang.Object</a></li>
<li>
<ul class="inheritance">
<li>org.apache.commons.math3.analysis.function.Abs</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../../../org/apache/commons/math3/analysis/UnivariateFunction.html" title="interface in org.apache.commons.math3.analysis">UnivariateFunction</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">Abs</span>
extends <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>
implements <a href="../../../../../../org/apache/commons/math3/analysis/UnivariateFunction.html" title="interface in org.apache.commons.math3.analysis">UnivariateFunction</a></pre>
<div class="block">Absolute value function.</div>
<dl><dt><span class="strong">Since:</span></dt>
<dd>3.0</dd>
<dt><span class="strong">Version:</span></dt>
<dd>$Id: Abs.java 1364377 2012-07-22 17:39:16Z tn $</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../org/apache/commons/math3/analysis/function/Abs.html#Abs()">Abs</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/commons/math3/analysis/function/Abs.html#value(double)">value</a></strong>(double x)</code>
<div class="block">Compute the value of the function.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></h3>
<code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#clone()" title="class or interface in java.lang">clone</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#equals(java.lang.Object)" title="class or interface in java.lang">equals</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#finalize()" title="class or interface in java.lang">finalize</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#getClass()" title="class or interface in java.lang">getClass</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#hashCode()" title="class or interface in java.lang">hashCode</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#notify()" title="class or interface in java.lang">notify</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#notifyAll()" title="class or interface in java.lang">notifyAll</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#toString()" title="class or interface in java.lang">toString</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#wait()" title="class or interface in java.lang">wait</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#wait(long)" title="class or interface in java.lang">wait</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#wait(long, int)" title="class or interface in java.lang">wait</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Abs()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Abs</h4>
<pre>public Abs()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="value(double)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>value</h4>
<pre>public double value(double x)</pre>
<div class="block">Compute the value of the function.</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../../../org/apache/commons/math3/analysis/UnivariateFunction.html#value(double)">value</a></code> in interface <code><a href="../../../../../../org/apache/commons/math3/analysis/UnivariateFunction.html" title="interface in org.apache.commons.math3.analysis">UnivariateFunction</a></code></dd>
<dt><span class="strong">Parameters:</span></dt><dd><code>x</code> - Point at which the function value should be computed.</dd>
<dt><span class="strong">Returns:</span></dt><dd>the value of the function.</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Abs.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../../../org/apache/commons/math3/analysis/function/Acos.html" title="class in org.apache.commons.math3.analysis.function"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/commons/math3/analysis/function/Abs.html" target="_top">Frames</a></li>
<li><a href="Abs.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2003–2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env php
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2017 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
// Try to find an autoloader for a local psysh version.
// We'll wrap this whole mess in a Closure so it doesn't leak any globals.
call_user_func(function () {
$cwd = null;
// Find the cwd arg (if present)
$argv = isset($_SERVER['argv']) ? $_SERVER['argv'] : array();
foreach ($argv as $i => $arg) {
if ($arg === '--cwd') {
if ($i >= count($argv) - 1) {
echo 'Missing --cwd argument.' . PHP_EOL;
exit(1);
}
$cwd = $argv[$i + 1];
break;
}
if (preg_match('/^--cwd=/', $arg)) {
$cwd = substr($arg, 6);
break;
}
}
// Or fall back to the actual cwd
if (!isset($cwd)) {
$cwd = getcwd();
}
$cwd = str_replace('\\', '/', $cwd);
$chunks = explode('/', $cwd);
while (!empty($chunks)) {
$path = implode('/', $chunks);
// Find composer.json
if (is_file($path . '/composer.json')) {
if ($cfg = json_decode(file_get_contents($path . '/composer.json'), true)) {
if (isset($cfg['name']) && $cfg['name'] === 'psy/psysh') {
// We're inside the psysh project. Let's use the local
// Composer autoload.
if (is_file($path . '/vendor/autoload.php')) {
require $path . '/vendor/autoload.php';
}
return;
}
}
}
// Or a composer.lock
if (is_file($path . '/composer.lock')) {
if ($cfg = json_decode(file_get_contents($path . '/composer.lock'), true)) {
foreach (array_merge($cfg['packages'], $cfg['packages-dev']) as $pkg) {
if (isset($pkg['name']) && $pkg['name'] === 'psy/psysh') {
// We're inside a project which requires psysh. We'll
// use the local Composer autoload.
if (is_file($path . '/vendor/autoload.php')) {
require $path . '/vendor/autoload.php';
}
return;
}
}
}
}
array_pop($chunks);
}
});
// We didn't find an autoloader for a local version, so use the autoloader that
// came with this script.
if (!class_exists('Psy\Shell')) {
/* <<< */
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require __DIR__ . '/../vendor/autoload.php';
} elseif (is_file(__DIR__ . '/../../../autoload.php')) {
require __DIR__ . '/../../../autoload.php';
} else {
echo 'PsySH dependencies not found, be sure to run `composer install`.' . PHP_EOL;
echo 'See https://getcomposer.org to get Composer.' . PHP_EOL;
exit(1);
}
/* >>> */
}
// If the psysh binary was included directly, assume they just wanted an
// autoloader and bail early.
//
// Keep this PHP 5.3 code around for a while in case someone is using a globally
// installed psysh as a bin launcher for older local versions.
if (version_compare(PHP_VERSION, '5.3.6', '<')) {
$trace = debug_backtrace();
} elseif (version_compare(PHP_VERSION, '5.4.0', '<')) {
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
} else {
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
}
if (Psy\Shell::isIncluded($trace)) {
unset($trace);
return;
}
// Clean up after ourselves.
unset($trace);
// If the local version is too old, we can't do this
if (!function_exists('Psy\bin')) {
$argv = $_SERVER['argv'];
$first = array_shift($argv);
if (preg_match('/php(\.exe)?$/', $first)) {
array_shift($argv);
}
array_unshift($argv, 'vendor/bin/psysh');
echo 'A local PsySH dependency was found, but it cannot be loaded. Please update to' . PHP_EOL;
echo 'the latest version, or run the local copy directly, e.g.:' . PHP_EOL;
echo PHP_EOL;
echo ' ' . implode(' ', $argv) . PHP_EOL;
exit(1);
}
// And go!
call_user_func(Psy\bin());
| {
"pile_set_name": "Github"
} |
#N struct 4215preview float x float y float p float h;
#N canvas 1331 34 789 899 10;
#X msg -225 423 1;
#X msg -253 412 0;
#X text -151 648 You can send a signal to sample.groove~'s third inlet
to modulate the playback rate.;
#X text 41 217 <- Click and drag up and down to change the playback
region.;
#X obj -292 -37 cnv 1 430 1 empty empty empty 0 -10 0 16 -66577 -66577
0;
#X obj -292 -130 cnv 15 430 20 empty empty empty 20 12 0 14 -216438
-66577 0;
#X obj -292 -109 cnv 1 430 1 empty empty empty 4 -10 2 12 -66577 -1
0;
#X obj -292 -130 cnv 1 430 1 empty empty empty 0 -10 0 16 -66577 -66577
0;
#X text -276 -97 Description: Groove a sample.;
#X text -279 -67 Comments: Wraps xgroove~ from the xsample library
;
#X text -291 -127 :: sample/groove ::;
#X msg -23 422 speed \$1;
#X obj -83 326 vradio 15 1 0 3 empty empty empty 0 -8 0 8 -195568 -262144
-1 0;
#X obj -20 377 hsl 50 22 -10 10 0 0 empty empty empty -2 -8 0 8 -33289
-262144 -33289 0 1;
#X obj -264 127 sample.display_;
#X obj -264 214 sample.bounds_;
#X text -278 -26 WARNING: This abstraction requires the xsample library.
;
#X obj -263 53 file.path.top;
#X floatatom -23 403 5 0 0 0 - - -;
#X text -2 -126 Version: 2007-06-12;
#X msg -263 7 medias/sounds/loop0.wav;
#X msg -155 29 medias/sounds/loop1.wav;
#X obj -264 97 sample.filer;
#X msg -39 52 medias/sounds/note0.wav;
#X floatatom 43 393 5 0 0 0 - - -;
#X text 81 391 milliseconds;
#X obj -267 702 mix.out_~;
#X obj -261 655 sample.groove~;
#X obj 206 363 vdl 15 0 0 4 empty empty empty 0 -6 0 8 -262144 -1 -1
0;
#X text 225 378 keep loop length;
#X text 225 394 keep fade length;
#X text 225 409 zone inside loop;
#X msg 43 422 xfade \$1;
#X msg 205 428 xfademode \$1;
#X text 225 362 keep loop pos (default);
#X obj -264 271 sample.adsr_;
#X msg -243 345 56 0;
#X msg -253 321 56 64;
#X text 41 245 <- Set the sustain loop by changing the loop region.
;
#X text -64 342 loop forward;
#X text -64 357 loop back&forth;
#X text -64 325 play once (ignore sustain loop);
#X msg -83 423 loop \$1;
#X text -278 -82 Flags: sample_id;
#X msg -173 322 60 127;
#X msg -145 342 60 0;
#X msg -250 468 -1;
#X msg 21 556 realtime.bounds 1;
#X text 19 575 Usually a change in the bounds of a sample will only
take effect once you retrigger sample.groove~. But \, if you set realtime.bounds
to 1 \, the changes to bounds will immediatly affect the the sample
being played.;
#X obj -153 73 bng 15 250 50 0 empty empty empty 0 -6 0 10 -262144
-1 -1;
#X obj -133 700 anal.sig_~;
#X text -32 701 Relative progress;
#X connect 0 0 27 1;
#X connect 1 0 27 1;
#X connect 11 0 27 1;
#X connect 12 0 42 0;
#X connect 13 0 18 0;
#X connect 14 0 15 0;
#X connect 15 0 35 0;
#X connect 17 0 22 0;
#X connect 18 0 11 0;
#X connect 20 0 17 0;
#X connect 21 0 17 0;
#X connect 22 0 14 0;
#X connect 23 0 17 0;
#X connect 24 0 32 0;
#X connect 27 0 26 0;
#X connect 27 1 26 1;
#X connect 27 2 50 0;
#X connect 28 0 33 0;
#X connect 32 0 27 1;
#X connect 33 0 27 1;
#X connect 35 0 27 0;
#X connect 36 0 27 1;
#X connect 37 0 27 1;
#X connect 42 0 27 1;
#X connect 44 0 27 1;
#X connect 45 0 27 1;
#X connect 46 0 27 1;
#X connect 47 0 27 1;
#X connect 49 0 22 0;
| {
"pile_set_name": "Github"
} |
/*
*
* Copyright 2015 gRPC authors.
*
* 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.
*
*/
#include <string.h>
#include <grpc/support/alloc.h>
#include "src/core/lib/json/json.h"
grpc_json* grpc_json_create(grpc_json_type type) {
grpc_json* json = (grpc_json*)gpr_zalloc(sizeof(*json));
json->type = type;
return json;
}
void grpc_json_destroy(grpc_json* json) {
while (json->child) {
grpc_json_destroy(json->child);
}
if (json->next) {
json->next->prev = json->prev;
}
if (json->prev) {
json->prev->next = json->next;
} else if (json->parent) {
json->parent->child = json->next;
}
gpr_free(json);
}
| {
"pile_set_name": "Github"
} |
class Board_Info:
def __init__(self):
self.pin_num = 48
self.JTAG_TCK = 0
self.JTAG_TDI = 1
self.JTAG_TMS = 2
self.JTAG_TDO = 3
self.ISP_RX = 4
self.ISP_TX = 5
self.WIFI_TX = 6
self.WIFI_RX = 7
self.WIFI_EN = 8
self.PIN9 = 9
self.PIN10 = 10
self.PIN11 = 11
self.LED_B = 12
self.LED_G = 13
self.LED_R = 14
self.PIN15 = 15
self.BOOT_KEY = 16
self.PIN17 = 17
self.MIC_ARRAY_BCK = 18
self.MIC_ARRAY_WS = 19
self.MIC_ARRAY_DATA3 = 20
self.MIC_ARRAY_DATA2 = 21
self.MIC_ARRAY_DATA1 = 22
self.MIC_ARRAY_DATA0 = 23
self.MIC_ARRAY_LED = 24
self.SPI0_CS1 = 25
self.SPI0_MISO = 26
self.SPI0_CLK = 27
self.SPI0_MOSI = 28
self.SPI0_CS0 = 29
self.MIC0_WS = 30
self.MIC0_DATA = 31
self.MIC0_BCK = 32
self.I2S_WS = 33
self.I2S_DA = 34
self.I2S_BCK = 35
self.LCD_CS = 36
self.LCD_RST = 37
self.LCD_DC = 38
self.LCD_WR = 39
self.DVP_SDA = 40
self.DVP_SCL = 41
self.DVP_RST = 42
self.DVP_VSYNC = 43
self.DVP_PWDN = 44
self.DVP_HSYNC = 45
self.DVP_XCLK = 46
self.DVP_PCLK = 47
self.pin_name=['JTAG_TCK','JTAG_TDI','JTAG_TMS','JTAG_TDO','ISP_RX','ISP_TX','WIFI_TX ','WIFI_RX ','WIFI_EN ','PIN9','PIN10','PIN11','LED_B','LED_G','LED_R','PIN15','BOOT_KEY','PIN17','MIC_ARRAY_BCK','MIC_ARRAY_WS ','MIC_ARRAY_DATA3','MIC_ARRAY_DATA2','MIC_ARRAY_DATA1','MIC_ARRAY_DATA0','MIC_ARRAY_LED','SPI0_CS1','SPI0_MISO','SPI0_CLK ','SPI0_MOSI','SPI0_CS0','MIC0_WS','MIC0_DATA','MIC0_BCK','I2S_WS','I2S_DA','I2S_BCK','LCD_CS','LCD_RST','LCD_DC','LCD_WR ','DVP_SDA','DVP_SCL','DVP_RST','DVP_VSYNC','DVP_PWDN','DVP_HSYNC','DVP_XCLK','DVP_PCLK']
self.D = [4, 5, 21, 22, 23, 24, 32, 15, 14, 13, 12, 11, 10, 3]
def pin_map(self,Pin = None):
num_len = 10
str_len = 23
if Pin == None :
num_sum_length = num_len
str_sum_length = str_len
Pin_str_obj = "Pin"
Pin_str_obj_length = len(Pin_str_obj)
Pin_str_obj_front = 3
Pin_str_obj_rear = num_sum_length - Pin_str_obj_front - Pin_str_obj_front
fun_str_obj = "Function"
fun_str_obj_length = len(fun_str_obj)
fun_str_obj_front = 5
fun_str_obj_rear = str_sum_length - fun_str_obj_front - fun_str_obj_length
print("|%s%s%s|%s%s%s|"%(str(Pin_str_obj_front * '-'),Pin_str_obj,str(Pin_str_obj_rear * '-'),str(fun_str_obj_front * '-'),fun_str_obj,str(fun_str_obj_rear*'-')))
for i in range(0,len(self.pin_name)):
num = str(i)
num_length = len(num)
num_front = 3
num_rear = num_sum_length - num_front - num_length
str_length = len(self.pin_name[i])
str_front = 5
str_rear = str_sum_length - str_front - str_length
print("|%s%d%s|%s%s%s|"%(str(num_front * ' '),i,str(num_rear * ' '),str(str_front * ' '),self.pin_name[i],str(str_rear*' ')))
print("+%s|%s+"%(str(num_sum_length*'-'),str(str_sum_length*'-')))
elif isinstance(Pin,int) and Pin < 0 or Pin > 47:
print("Pin num must in range[0,47]")
return False
elif isinstance(Pin,int):
Pin_sum_length = num_len
string_sum_length = str_len
pin_str_obj = "Pin"
pin_str_obj_length = len(pin_str_obj)
pin_str_obj_front = 3
pin_str_obj_rear = Pin_sum_length - pin_str_obj_front - pin_str_obj_front
Fun_str_obj = "Function"
Fun_str_obj_length = len(Fun_str_obj)
Fun_str_obj_front = 5
Fun_str_obj_rear = string_sum_length - Fun_str_obj_front - Fun_str_obj_length
print("|%s%s%s|%s%s%s|"%(str(pin_str_obj_front * '-'),pin_str_obj,str(pin_str_obj_rear * '-'),str(Fun_str_obj_front * '-'),Fun_str_obj,str(Fun_str_obj_rear*'-')))
Pin_str = str(Pin)
Pin_length = len(Pin_str)
Pin_front = 3
Pin_rear = Pin_sum_length - Pin_front - Pin_length
string_length = len(self.pin_name[Pin])
string_front = 5
string_rear = string_sum_length - string_front - string_length
print("|%s%d%s|%s%s%s|"%(str(Pin_front * ' '),Pin,str(Pin_rear * ' '),str(string_front * ' '),self.pin_name[Pin],str(string_rear*' ')))
print("+%s|%s+"%(str(Pin_sum_length*'-'),str(string_sum_length*'-')))
else:
print("Unknow error")
return False
global board_info
board_info=Board_Info()
| {
"pile_set_name": "Github"
} |
// ------------------------------------------------------------------
// Fast R-CNN
// Copyright (c) 2015 Microsoft
// Licensed under The MIT License [see fast-rcnn/LICENSE for details]
// Written by Ross Girshick
// ------------------------------------------------------------------
#ifndef CAFFE_ROI_MASK_POOLING_LAYER_HPP_
#define CAFFE_ROI_MASK_POOLING_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/* ROIMaskPoolingLayer - Region of Interest Pooling Layer With Mask
*/
template <typename Dtype>
class ROIMaskPoolingLayer : public Layer<Dtype> {
public:
explicit ROIMaskPoolingLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "ROIMaskPooling"; }
virtual inline int MinBottomBlobs() const { return 2; }
virtual inline int MaxBottomBlobs() const { return 2; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline int MaxTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
int channels_;
int height_;
int width_;
int pooled_height_;
int pooled_width_;
Dtype spatial_scale_;
Dtype spatial_shift_;
int half_part_;
Dtype roi_scale_;
Dtype mask_scale_;
Blob<int> max_idx_;
};
} // namespace caffe
#endif // CAFFE_ROI_MASK_POOLING_LAYER_HPP_
| {
"pile_set_name": "Github"
} |
var baseEach = require('./baseEach'),
isArrayLike = require('./isArrayLike');
/**
* The base implementation of `_.map` without support for callback shorthands
* and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
module.exports = baseMap;
| {
"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 <objc/NSObject.h>
@interface SymptomEvaluator : NSObject
{
}
+ (void)setPersistentData:(id)arg1;
+ (id)getPersistentData;
+ (BOOL)hasNewPersistentData;
@end
| {
"pile_set_name": "Github"
} |
package net.corda.isolated.contracts
import net.corda.core.contracts.ContractState
import net.corda.core.contracts.PartyAndReference
import net.corda.core.identity.Party
import net.corda.core.transactions.TransactionBuilder
/**
* This interface deliberately mirrors the one in the isolated module.
* We will actually link [AnotherDummyContract] against this interface rather
* than the one inside isolated.jar, which means we won't need to use reflection
* to execute the contract's generateInitial() method.
*/
interface DummyContractBackdoor {
fun generateInitial(owner: PartyAndReference, magicNumber: Int, notary: Party): TransactionBuilder
fun inspectState(state: ContractState): Int
}
| {
"pile_set_name": "Github"
} |
/*
* blob.h
*
* Binary blob handling.
*
* Copyright (c) 2002 Dug Song <dugsong@monkey.org>
*
* $Id: blob.h 334 2002-04-05 03:06:44Z dugsong $
*/
#ifndef DNET_BLOB_H
#define DNET_BLOB_H
typedef struct blob {
u_char *base; /* start of data */
int off; /* offset into data */
int end; /* end of data */
int size; /* size of allocation */
} blob_t;
__BEGIN_DECLS
blob_t *blob_new(void);
int blob_read(blob_t *b, void *buf, int len);
int blob_write(blob_t *b, const void *buf, int len);
int blob_seek(blob_t *b, int off, int whence);
#define blob_skip(b, l) blob_seek(b, l, SEEK_CUR)
#define blob_rewind(b) blob_seek(b, 0, SEEK_SET)
#define blob_offset(b) ((b)->off)
#define blob_left(b) ((b)->end - (b)->off)
int blob_index(blob_t *b, const void *buf, int len);
int blob_rindex(blob_t *b, const void *buf, int len);
int blob_pack(blob_t *b, const char *fmt, ...);
int blob_unpack(blob_t *b, const char *fmt, ...);
int blob_insert(blob_t *b, const void *buf, int len);
int blob_delete(blob_t *b, void *buf, int len);
int blob_print(blob_t *b, char *style, int len);
blob_t *blob_free(blob_t *b);
int blob_register_alloc(size_t size, void *(*bmalloc)(size_t),
void (*bfree)(void *), void *(*brealloc)(void *, size_t));
#ifdef va_start
typedef int (*blob_fmt_cb)(int pack, int len, blob_t *b, va_list *arg);
int blob_register_pack(char c, blob_fmt_cb fmt_cb);
#endif
__END_DECLS
#endif /* DNET_BLOB_H */
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.android.dx.dex.code;
import com.android.dex.util.ExceptionWithContext;
import com.android.dx.io.Opcodes;
import com.android.dx.rop.cst.Constant;
import com.android.dx.rop.cst.CstBaseMethodRef;
import com.android.dx.rop.cst.CstCallSiteRef;
import com.android.dx.rop.cst.CstProtoRef;
import com.android.dx.util.AnnotatedOutput;
import com.android.dx.util.FixedSizeList;
import com.android.dx.util.IndentingWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
/**
* List of {@link DalvInsn} instances.
*/
public final class DalvInsnList extends FixedSizeList {
/**
* The amount of register space, in register units, required for this
* code block. This may be greater than the largest observed register+
* category because the method this code block exists in may
* specify arguments that are unused by the method.
*/
private final int regCount;
/**
* Constructs and returns an immutable instance whose elements are
* identical to the ones in the given list, in the same order.
*
* @param list {@code non-null;} the list to use for elements
* @param regCount count, in register-units, of the number of registers
* this code block requires.
* @return {@code non-null;} an appropriately-constructed instance of this
* class
*/
public static DalvInsnList makeImmutable(ArrayList<DalvInsn> list,
int regCount) {
int size = list.size();
DalvInsnList result = new DalvInsnList(size, regCount);
for (int i = 0; i < size; i++) {
result.set(i, list.get(i));
}
result.setImmutable();
return result;
}
/**
* Constructs an instance. All indices initially contain {@code null}.
*
* @param size the size of the list
* @param regCount count, in register-units, of the number of registers
* this code block requires.
*/
public DalvInsnList(int size, int regCount) {
super(size);
this.regCount = regCount;
}
/**
* Gets the element at the given index. It is an error to call
* this with the index for an element which was never set; if you
* do that, this will throw {@code NullPointerException}.
*
* @param n {@code >= 0, < size();} which index
* @return {@code non-null;} element at that index
*/
public DalvInsn get(int n) {
return (DalvInsn) get0(n);
}
/**
* Sets the instruction at the given index.
*
* @param n {@code >= 0, < size();} which index
* @param insn {@code non-null;} the instruction to set at {@code n}
*/
public void set(int n, DalvInsn insn) {
set0(n, insn);
}
/**
* Gets the size of this instance, in 16-bit code units. This will only
* return a meaningful result if the instructions in this instance all
* have valid addresses.
*
* @return {@code >= 0;} the size
*/
public int codeSize() {
int sz = size();
if (sz == 0) {
return 0;
}
DalvInsn last = get(sz - 1);
return last.getNextAddress();
}
/**
* Writes all the instructions in this instance to the given output
* destination.
*
* @param out {@code non-null;} where to write to
*/
public void writeTo(AnnotatedOutput out) {
int startCursor = out.getCursor();
int sz = size();
if (out.annotates()) {
boolean verbose = out.isVerbose();
for (int i = 0; i < sz; i++) {
DalvInsn insn = (DalvInsn) get0(i);
int codeBytes = insn.codeSize() * 2;
String s;
if ((codeBytes != 0) || verbose) {
s = insn.listingString(" ", out.getAnnotationWidth(),
true);
} else {
s = null;
}
if (s != null) {
out.annotate(codeBytes, s);
} else if (codeBytes != 0) {
out.annotate(codeBytes, "");
}
}
}
for (int i = 0; i < sz; i++) {
DalvInsn insn = (DalvInsn) get0(i);
try {
insn.writeTo(out);
} catch (RuntimeException ex) {
throw ExceptionWithContext.withContext(ex,
"...while writing " + insn);
}
}
// Check the amount written.
int written = (out.getCursor() - startCursor) / 2;
if (written != codeSize()) {
throw new RuntimeException("write length mismatch; expected " +
codeSize() + " but actually wrote " + written);
}
}
/**
* Gets the minimum required register count implied by this
* instance. This includes any unused parameters that could
* potentially be at the top of the register space.
* @return {@code >= 0;} the required registers size
*/
public int getRegistersSize() {
return regCount;
}
/**
* Gets the size of the outgoing arguments area required by this
* method. This is equal to the largest argument word count of any
* method referred to by this instance.
*
* @return {@code >= 0;} the required outgoing arguments size
*/
public int getOutsSize() {
int sz = size();
int result = 0;
for (int i = 0; i < sz; i++) {
DalvInsn insn = (DalvInsn) get0(i);
int count = 0;
if (insn instanceof CstInsn) {
Constant cst = ((CstInsn) insn).getConstant();
if (cst instanceof CstBaseMethodRef) {
CstBaseMethodRef methodRef = (CstBaseMethodRef) cst;
boolean isStatic =
(insn.getOpcode().getFamily() == Opcodes.INVOKE_STATIC);
count = methodRef.getParameterWordCount(isStatic);
} else if (cst instanceof CstCallSiteRef) {
CstCallSiteRef invokeDynamicRef = (CstCallSiteRef) cst;
count = invokeDynamicRef.getPrototype().getParameterTypes().getWordCount();
}
} else if (insn instanceof MultiCstInsn) {
if (insn.getOpcode().getFamily() != Opcodes.INVOKE_POLYMORPHIC) {
throw new RuntimeException("Expecting invoke-polymorphic");
}
MultiCstInsn mci = (MultiCstInsn) insn;
// Invoke-polymorphic has two constants: [0] method-ref and
// [1] call site prototype. The number of arguments is based
// on the call site prototype since these are the arguments
// presented. The method-ref is always MethodHandle.invoke(Object[])
// or MethodHandle.invokeExact(Object[]).
CstProtoRef proto = (CstProtoRef) mci.getConstant(1);
count = proto.getPrototype().getParameterTypes().getWordCount();
count = count + 1; // And one for receiver (method handle).
} else {
continue;
}
if (count > result) {
result = count;
}
}
return result;
}
/**
* Does a human-friendly dump of this instance.
*
* @param out {@code non-null;} where to dump
* @param prefix {@code non-null;} prefix to attach to each line of output
* @param verbose whether to be verbose; verbose output includes
* lines for zero-size instructions and explicit constant pool indices
*/
public void debugPrint(Writer out, String prefix, boolean verbose) {
IndentingWriter iw = new IndentingWriter(out, 0, prefix);
int sz = size();
try {
for (int i = 0; i < sz; i++) {
DalvInsn insn = (DalvInsn) get0(i);
String s;
if ((insn.codeSize() != 0) || verbose) {
s = insn.listingString("", 0, verbose);
} else {
s = null;
}
if (s != null) {
iw.write(s);
}
}
iw.flush();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
/**
* Does a human-friendly dump of this instance.
*
* @param out {@code non-null;} where to dump
* @param prefix {@code non-null;} prefix to attach to each line of output
* @param verbose whether to be verbose; verbose output includes
* lines for zero-size instructions
*/
public void debugPrint(OutputStream out, String prefix, boolean verbose) {
Writer w = new OutputStreamWriter(out);
debugPrint(w, prefix, verbose);
try {
w.flush();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Setup\Module\Di\Code\Scanner;
/**
* Interface \Magento\Setup\Module\Di\Code\Scanner\ScannerInterface
*
*/
interface ScannerInterface
{
/**
* Get array of class names
*
* @param array $files
* @return array
*/
public function collectEntities(array $files);
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2015 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. AND ITS 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 APPLE INC. OR ITS 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 "DataURLDecoder.h"
#include "DecodeEscapeSequences.h"
#include "HTTPParsers.h"
#include "ParsedContentType.h"
#include "SharedBuffer.h"
#include "TextEncoding.h"
#include <wtf/MainThread.h>
#include <wtf/Optional.h>
#include <wtf/RunLoop.h>
#include <wtf/URL.h>
#include <wtf/WorkQueue.h>
#include <wtf/text/Base64.h>
namespace WebCore {
namespace DataURLDecoder {
static WorkQueue& decodeQueue()
{
static auto& queue = WorkQueue::create("org.webkit.DataURLDecoder", WorkQueue::Type::Serial, WorkQueue::QOS::UserInitiated).leakRef();
return queue;
}
static Result parseMediaType(const String& mediaType)
{
if (Optional<ParsedContentType> parsedContentType = ParsedContentType::create(mediaType))
return { parsedContentType->mimeType(), parsedContentType->charset(), parsedContentType->serialize(), nullptr };
return { "text/plain"_s, "US-ASCII"_s, "text/plain;charset=US-ASCII"_s, nullptr };
}
struct DecodeTask {
WTF_MAKE_FAST_ALLOCATED;
public:
DecodeTask(const String& urlString, const ScheduleContext& scheduleContext, DecodeCompletionHandler&& completionHandler)
: urlString(urlString.isolatedCopy())
, scheduleContext(scheduleContext)
, completionHandler(WTFMove(completionHandler))
{
}
bool process()
{
if (urlString.find(',') == notFound)
return false;
const char dataString[] = "data:";
const char base64String[] = ";base64";
ASSERT(urlString.startsWith(dataString));
size_t headerEnd = urlString.find(',', strlen(dataString));
size_t encodedDataStart = headerEnd == notFound ? headerEnd : headerEnd + 1;
encodedData = StringView(urlString).substring(encodedDataStart);
auto header = StringView(urlString).substring(strlen(dataString), headerEnd - strlen(dataString));
isBase64 = header.endsWithIgnoringASCIICase(StringView(base64String));
auto mediaType = (isBase64 ? header.substring(0, header.length() - strlen(base64String)) : header).toString();
mediaType = mediaType.stripWhiteSpace();
if (mediaType.startsWith(';'))
mediaType.insert("text/plain", 0);
result = parseMediaType(mediaType);
return true;
}
const String urlString;
StringView encodedData;
bool isBase64 { false };
const ScheduleContext scheduleContext;
const DecodeCompletionHandler completionHandler;
Result result;
};
#if HAVE(RUNLOOP_TIMER)
class DecodingResultDispatcher : public ThreadSafeRefCounted<DecodingResultDispatcher> {
public:
static void dispatch(std::unique_ptr<DecodeTask> decodeTask)
{
Ref<DecodingResultDispatcher> dispatcher = adoptRef(*new DecodingResultDispatcher(WTFMove(decodeTask)));
dispatcher->startTimer();
}
private:
DecodingResultDispatcher(std::unique_ptr<DecodeTask> decodeTask)
: m_timer(*this, &DecodingResultDispatcher::timerFired)
, m_decodeTask(WTFMove(decodeTask))
{
}
void startTimer()
{
// Keep alive until the timer has fired.
ref();
auto scheduledPairs = m_decodeTask->scheduleContext.scheduledPairs;
m_timer.startOneShot(0_s);
m_timer.schedule(scheduledPairs);
}
void timerFired()
{
if (m_decodeTask->result.data)
m_decodeTask->completionHandler(WTFMove(m_decodeTask->result));
else
m_decodeTask->completionHandler({ });
// Ensure DecodeTask gets deleted in the main thread.
m_decodeTask = nullptr;
deref();
}
RunLoopTimer<DecodingResultDispatcher> m_timer;
std::unique_ptr<DecodeTask> m_decodeTask;
};
#endif // HAVE(RUNLOOP_TIMER)
static std::unique_ptr<DecodeTask> createDecodeTask(const URL& url, const ScheduleContext& scheduleContext, DecodeCompletionHandler&& completionHandler)
{
return makeUnique<DecodeTask>(
url.string(),
scheduleContext,
WTFMove(completionHandler)
);
}
static void decodeBase64(DecodeTask& task)
{
Vector<char> buffer;
// First try base64url.
if (!base64URLDecode(task.encodedData.toStringWithoutCopying(), buffer)) {
// Didn't work, try unescaping and decoding as base64.
auto unescapedString = decodeURLEscapeSequences(task.encodedData.toStringWithoutCopying());
if (!base64Decode(unescapedString, buffer, Base64IgnoreSpacesAndNewLines))
return;
}
buffer.shrinkToFit();
task.result.data = SharedBuffer::create(WTFMove(buffer));
}
static void decodeEscaped(DecodeTask& task)
{
TextEncoding encodingFromCharset(task.result.charset);
auto& encoding = encodingFromCharset.isValid() ? encodingFromCharset : UTF8Encoding();
auto buffer = decodeURLEscapeSequencesAsData(task.encodedData, encoding);
buffer.shrinkToFit();
task.result.data = SharedBuffer::create(WTFMove(buffer));
}
void decode(const URL& url, const ScheduleContext& scheduleContext, DecodeCompletionHandler&& completionHandler)
{
ASSERT(url.protocolIsData());
decodeQueue().dispatch([decodeTask = createDecodeTask(url, scheduleContext, WTFMove(completionHandler))]() mutable {
if (decodeTask->process()) {
if (decodeTask->isBase64)
decodeBase64(*decodeTask);
else
decodeEscaped(*decodeTask);
}
#if HAVE(RUNLOOP_TIMER)
DecodingResultDispatcher::dispatch(WTFMove(decodeTask));
#else
callOnMainThread([decodeTask = WTFMove(decodeTask)] {
if (!decodeTask->result.data) {
decodeTask->completionHandler({ });
return;
}
decodeTask->completionHandler(WTFMove(decodeTask->result));
});
#endif
});
}
}
}
| {
"pile_set_name": "Github"
} |
import shortid from 'shortid'
import {SuggestedActionTypeEnum} from 'parabol-client/types/graphql'
interface Input {
id?: string
createdAt?: Date
priority: number
removedAt?: Date | null
type: SuggestedActionTypeEnum
userId: string
}
export default abstract class SuggestedAction {
id: string
createdAt: Date
priority: number
removedAt: Date | null
type: SuggestedActionTypeEnum
userId: string
protected constructor(input: Input) {
const {type, userId, id, createdAt, priority, removedAt} = input
this.id = id || shortid.generate()
this.createdAt = createdAt || new Date()
this.userId = userId
this.type = type
this.priority = priority
this.removedAt = removedAt || null
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !purego,!appengine
package impl
// When using unsafe pointers, we can just treat enum values as int32s.
var (
coderEnumNoZero = coderInt32NoZero
coderEnum = coderInt32
coderEnumPtr = coderInt32Ptr
coderEnumSlice = coderInt32Slice
coderEnumPackedSlice = coderInt32PackedSlice
)
| {
"pile_set_name": "Github"
} |
/*
* (C) Copyright 2017 Rockchip Electronics Co., Ltd
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <dm.h>
#include <syscon.h>
#include <asm/arch/clock.h>
static const struct udevice_id px30_syscon_ids[] = {
{ .compatible = "rockchip,px30-pmu", .data = ROCKCHIP_SYSCON_PMU },
{ .compatible = "rockchip,px30-pmugrf", .data = ROCKCHIP_SYSCON_PMUGRF },
{ .compatible = "rockchip,px30-grf", .data = ROCKCHIP_SYSCON_GRF },
{ }
};
U_BOOT_DRIVER(syscon_px30) = {
.name = "px30_syscon",
.id = UCLASS_SYSCON,
.of_match = px30_syscon_ids,
#if !CONFIG_IS_ENABLED(OF_PLATDATA)
.bind = dm_scan_fdt_dev,
#endif
};
| {
"pile_set_name": "Github"
} |
/*
* Regulator driver for TI TPS6586x
*
* Copyright (C) 2010 Compulab Ltd.
* Author: Mike Rapoport <mike@compulab.co.il>
*
* Based on da903x
* Copyright (C) 2006-2008 Marvell International Ltd.
* Copyright (C) 2008 Compulab Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/of.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/of_regulator.h>
#include <linux/mfd/tps6586x.h>
/* supply control and voltage setting */
#define TPS6586X_SUPPLYENA 0x10
#define TPS6586X_SUPPLYENB 0x11
#define TPS6586X_SUPPLYENC 0x12
#define TPS6586X_SUPPLYEND 0x13
#define TPS6586X_SUPPLYENE 0x14
#define TPS6586X_VCC1 0x20
#define TPS6586X_VCC2 0x21
#define TPS6586X_SM1V1 0x23
#define TPS6586X_SM1V2 0x24
#define TPS6586X_SM1SL 0x25
#define TPS6586X_SM0V1 0x26
#define TPS6586X_SM0V2 0x27
#define TPS6586X_SM0SL 0x28
#define TPS6586X_LDO2AV1 0x29
#define TPS6586X_LDO2AV2 0x2A
#define TPS6586X_LDO2BV1 0x2F
#define TPS6586X_LDO2BV2 0x30
#define TPS6586X_LDO4V1 0x32
#define TPS6586X_LDO4V2 0x33
/* converter settings */
#define TPS6586X_SUPPLYV1 0x41
#define TPS6586X_SUPPLYV2 0x42
#define TPS6586X_SUPPLYV3 0x43
#define TPS6586X_SUPPLYV4 0x44
#define TPS6586X_SUPPLYV5 0x45
#define TPS6586X_SUPPLYV6 0x46
#define TPS6586X_SMODE1 0x47
#define TPS6586X_SMODE2 0x48
struct tps6586x_regulator {
struct regulator_desc desc;
int enable_bit[2];
int enable_reg[2];
};
static struct regulator_ops tps6586x_rw_regulator_ops = {
.list_voltage = regulator_list_voltage_table,
.map_voltage = regulator_map_voltage_ascend,
.get_voltage_sel = regulator_get_voltage_sel_regmap,
.set_voltage_sel = regulator_set_voltage_sel_regmap,
.is_enabled = regulator_is_enabled_regmap,
.enable = regulator_enable_regmap,
.disable = regulator_disable_regmap,
};
static struct regulator_ops tps6586x_rw_linear_regulator_ops = {
.list_voltage = regulator_list_voltage_linear,
.get_voltage_sel = regulator_get_voltage_sel_regmap,
.set_voltage_sel = regulator_set_voltage_sel_regmap,
.is_enabled = regulator_is_enabled_regmap,
.enable = regulator_enable_regmap,
.disable = regulator_disable_regmap,
};
static struct regulator_ops tps6586x_ro_regulator_ops = {
.list_voltage = regulator_list_voltage_table,
.map_voltage = regulator_map_voltage_ascend,
.get_voltage_sel = regulator_get_voltage_sel_regmap,
.is_enabled = regulator_is_enabled_regmap,
.enable = regulator_enable_regmap,
.disable = regulator_disable_regmap,
};
static struct regulator_ops tps6586x_sys_regulator_ops = {
};
static const unsigned int tps6586x_ldo0_voltages[] = {
1200000, 1500000, 1800000, 2500000, 2700000, 2850000, 3100000, 3300000,
};
static const unsigned int tps6586x_ldo_voltages[] = {
1250000, 1500000, 1800000, 2500000, 2700000, 2850000, 3100000, 3300000,
};
static const unsigned int tps658640_rtc_voltages[] = {
2500000, 2850000, 3100000, 3300000,
};
#define TPS6586X_REGULATOR(_id, _ops, _pin_name, vdata, vreg, shift, nbits, \
ereg0, ebit0, ereg1, ebit1, goreg, gobit) \
.desc = { \
.supply_name = _pin_name, \
.name = "REG-" #_id, \
.ops = &tps6586x_## _ops ## _regulator_ops, \
.type = REGULATOR_VOLTAGE, \
.id = TPS6586X_ID_##_id, \
.n_voltages = ARRAY_SIZE(vdata##_voltages), \
.volt_table = vdata##_voltages, \
.owner = THIS_MODULE, \
.enable_reg = TPS6586X_SUPPLY##ereg0, \
.enable_mask = 1 << (ebit0), \
.vsel_reg = TPS6586X_##vreg, \
.vsel_mask = ((1 << (nbits)) - 1) << (shift), \
.apply_reg = (goreg), \
.apply_bit = (gobit), \
}, \
.enable_reg[0] = TPS6586X_SUPPLY##ereg0, \
.enable_bit[0] = (ebit0), \
.enable_reg[1] = TPS6586X_SUPPLY##ereg1, \
.enable_bit[1] = (ebit1),
#define TPS6586X_REGULATOR_LINEAR(_id, _ops, _pin_name, n_volt, min_uv, \
uv_step, vreg, shift, nbits, ereg0, \
ebit0, ereg1, ebit1, goreg, gobit) \
.desc = { \
.supply_name = _pin_name, \
.name = "REG-" #_id, \
.ops = &tps6586x_## _ops ## _regulator_ops, \
.type = REGULATOR_VOLTAGE, \
.id = TPS6586X_ID_##_id, \
.n_voltages = n_volt, \
.min_uV = min_uv, \
.uV_step = uv_step, \
.owner = THIS_MODULE, \
.enable_reg = TPS6586X_SUPPLY##ereg0, \
.enable_mask = 1 << (ebit0), \
.vsel_reg = TPS6586X_##vreg, \
.vsel_mask = ((1 << (nbits)) - 1) << (shift), \
.apply_reg = (goreg), \
.apply_bit = (gobit), \
}, \
.enable_reg[0] = TPS6586X_SUPPLY##ereg0, \
.enable_bit[0] = (ebit0), \
.enable_reg[1] = TPS6586X_SUPPLY##ereg1, \
.enable_bit[1] = (ebit1),
#define TPS6586X_LDO(_id, _pname, vdata, vreg, shift, nbits, \
ereg0, ebit0, ereg1, ebit1) \
{ \
TPS6586X_REGULATOR(_id, rw, _pname, vdata, vreg, shift, nbits, \
ereg0, ebit0, ereg1, ebit1, 0, 0) \
}
#define TPS6586X_LDO_LINEAR(_id, _pname, n_volt, min_uv, uv_step, vreg, \
shift, nbits, ereg0, ebit0, ereg1, ebit1) \
{ \
TPS6586X_REGULATOR_LINEAR(_id, rw_linear, _pname, n_volt, \
min_uv, uv_step, vreg, shift, nbits, \
ereg0, ebit0, ereg1, ebit1, 0, 0) \
}
#define TPS6586X_FIXED_LDO(_id, _pname, vdata, vreg, shift, nbits, \
ereg0, ebit0, ereg1, ebit1) \
{ \
TPS6586X_REGULATOR(_id, ro, _pname, vdata, vreg, shift, nbits, \
ereg0, ebit0, ereg1, ebit1, 0, 0) \
}
#define TPS6586X_DVM(_id, _pname, n_volt, min_uv, uv_step, vreg, shift, \
nbits, ereg0, ebit0, ereg1, ebit1, goreg, gobit) \
{ \
TPS6586X_REGULATOR_LINEAR(_id, rw_linear, _pname, n_volt, \
min_uv, uv_step, vreg, shift, nbits, \
ereg0, ebit0, ereg1, ebit1, goreg, \
gobit) \
}
#define TPS6586X_SYS_REGULATOR() \
{ \
.desc = { \
.supply_name = "sys", \
.name = "REG-SYS", \
.ops = &tps6586x_sys_regulator_ops, \
.type = REGULATOR_VOLTAGE, \
.id = TPS6586X_ID_SYS, \
.owner = THIS_MODULE, \
}, \
}
static struct tps6586x_regulator tps6586x_regulator[] = {
TPS6586X_SYS_REGULATOR(),
TPS6586X_LDO(LDO_0, "vinldo01", tps6586x_ldo0, SUPPLYV1, 5, 3, ENC, 0,
END, 0),
TPS6586X_LDO(LDO_3, "vinldo23", tps6586x_ldo, SUPPLYV4, 0, 3, ENC, 2,
END, 2),
TPS6586X_LDO(LDO_5, "REG-SYS", tps6586x_ldo, SUPPLYV6, 0, 3, ENE, 6,
ENE, 6),
TPS6586X_LDO(LDO_6, "vinldo678", tps6586x_ldo, SUPPLYV3, 0, 3, ENC, 4,
END, 4),
TPS6586X_LDO(LDO_7, "vinldo678", tps6586x_ldo, SUPPLYV3, 3, 3, ENC, 5,
END, 5),
TPS6586X_LDO(LDO_8, "vinldo678", tps6586x_ldo, SUPPLYV2, 5, 3, ENC, 6,
END, 6),
TPS6586X_LDO(LDO_9, "vinldo9", tps6586x_ldo, SUPPLYV6, 3, 3, ENE, 7,
ENE, 7),
TPS6586X_LDO(LDO_RTC, "REG-SYS", tps6586x_ldo, SUPPLYV4, 3, 3, V4, 7,
V4, 7),
TPS6586X_LDO_LINEAR(LDO_1, "vinldo01", 32, 725000, 25000, SUPPLYV1,
0, 5, ENC, 1, END, 1),
TPS6586X_LDO_LINEAR(SM_2, "vin-sm2", 32, 3000000, 50000, SUPPLYV2,
0, 5, ENC, 7, END, 7),
TPS6586X_DVM(LDO_2, "vinldo23", 32, 725000, 25000, LDO2BV1, 0, 5,
ENA, 3, ENB, 3, TPS6586X_VCC2, BIT(6)),
TPS6586X_DVM(LDO_4, "vinldo4", 32, 1700000, 25000, LDO4V1, 0, 5,
ENC, 3, END, 3, TPS6586X_VCC1, BIT(6)),
TPS6586X_DVM(SM_0, "vin-sm0", 32, 725000, 25000, SM0V1, 0, 5,
ENA, 1, ENB, 1, TPS6586X_VCC1, BIT(2)),
TPS6586X_DVM(SM_1, "vin-sm1", 32, 725000, 25000, SM1V1, 0, 5,
ENA, 0, ENB, 0, TPS6586X_VCC1, BIT(0)),
};
static struct tps6586x_regulator tps658623_regulator[] = {
TPS6586X_LDO_LINEAR(SM_2, "vin-sm2", 32, 1700000, 25000, SUPPLYV2,
0, 5, ENC, 7, END, 7),
};
static struct tps6586x_regulator tps658640_regulator[] = {
TPS6586X_LDO(LDO_3, "vinldo23", tps6586x_ldo0, SUPPLYV4, 0, 3,
ENC, 2, END, 2),
TPS6586X_LDO(LDO_5, "REG-SYS", tps6586x_ldo0, SUPPLYV6, 0, 3,
ENE, 6, ENE, 6),
TPS6586X_LDO(LDO_6, "vinldo678", tps6586x_ldo0, SUPPLYV3, 0, 3,
ENC, 4, END, 4),
TPS6586X_LDO(LDO_7, "vinldo678", tps6586x_ldo0, SUPPLYV3, 3, 3,
ENC, 5, END, 5),
TPS6586X_LDO(LDO_8, "vinldo678", tps6586x_ldo0, SUPPLYV2, 5, 3,
ENC, 6, END, 6),
TPS6586X_LDO(LDO_9, "vinldo9", tps6586x_ldo0, SUPPLYV6, 3, 3,
ENE, 7, ENE, 7),
TPS6586X_LDO_LINEAR(SM_2, "vin-sm2", 32, 2150000, 50000, SUPPLYV2,
0, 5, ENC, 7, END, 7),
TPS6586X_FIXED_LDO(LDO_RTC, "REG-SYS", tps658640_rtc, SUPPLYV4, 3, 2,
V4, 7, V4, 7),
};
static struct tps6586x_regulator tps658643_regulator[] = {
TPS6586X_LDO_LINEAR(SM_2, "vin-sm2", 32, 1025000, 25000, SUPPLYV2,
0, 5, ENC, 7, END, 7),
};
/*
* TPS6586X has 2 enable bits that are OR'ed to determine the actual
* regulator state. Clearing one of this bits allows switching
* regulator on and of with single register write.
*/
static inline int tps6586x_regulator_preinit(struct device *parent,
struct tps6586x_regulator *ri)
{
uint8_t val1, val2;
int ret;
if (ri->enable_reg[0] == ri->enable_reg[1] &&
ri->enable_bit[0] == ri->enable_bit[1])
return 0;
ret = tps6586x_read(parent, ri->enable_reg[0], &val1);
if (ret)
return ret;
ret = tps6586x_read(parent, ri->enable_reg[1], &val2);
if (ret)
return ret;
if (!(val2 & (1 << ri->enable_bit[1])))
return 0;
/*
* The regulator is on, but it's enabled with the bit we don't
* want to use, so we switch the enable bits
*/
if (!(val1 & (1 << ri->enable_bit[0]))) {
ret = tps6586x_set_bits(parent, ri->enable_reg[0],
1 << ri->enable_bit[0]);
if (ret)
return ret;
}
return tps6586x_clr_bits(parent, ri->enable_reg[1],
1 << ri->enable_bit[1]);
}
static int tps6586x_regulator_set_slew_rate(struct platform_device *pdev,
int id, struct regulator_init_data *p)
{
struct device *parent = pdev->dev.parent;
struct tps6586x_settings *setting = p->driver_data;
uint8_t reg;
if (setting == NULL)
return 0;
if (!(setting->slew_rate & TPS6586X_SLEW_RATE_SET))
return 0;
/* only SM0 and SM1 can have the slew rate settings */
switch (id) {
case TPS6586X_ID_SM_0:
reg = TPS6586X_SM0SL;
break;
case TPS6586X_ID_SM_1:
reg = TPS6586X_SM1SL;
break;
default:
dev_err(&pdev->dev, "Only SM0/SM1 can set slew rate\n");
return -EINVAL;
}
return tps6586x_write(parent, reg,
setting->slew_rate & TPS6586X_SLEW_RATE_MASK);
}
static struct tps6586x_regulator *find_regulator_info(int id, int version)
{
struct tps6586x_regulator *ri;
struct tps6586x_regulator *table = NULL;
int num;
int i;
switch (version) {
case TPS658623:
table = tps658623_regulator;
num = ARRAY_SIZE(tps658623_regulator);
break;
case TPS658640:
case TPS658640v2:
table = tps658640_regulator;
num = ARRAY_SIZE(tps658640_regulator);
break;
case TPS658643:
table = tps658643_regulator;
num = ARRAY_SIZE(tps658643_regulator);
break;
}
/* Search version specific table first */
if (table) {
for (i = 0; i < num; i++) {
ri = &table[i];
if (ri->desc.id == id)
return ri;
}
}
for (i = 0; i < ARRAY_SIZE(tps6586x_regulator); i++) {
ri = &tps6586x_regulator[i];
if (ri->desc.id == id)
return ri;
}
return NULL;
}
#ifdef CONFIG_OF
static struct of_regulator_match tps6586x_matches[] = {
{ .name = "sys", .driver_data = (void *)TPS6586X_ID_SYS },
{ .name = "sm0", .driver_data = (void *)TPS6586X_ID_SM_0 },
{ .name = "sm1", .driver_data = (void *)TPS6586X_ID_SM_1 },
{ .name = "sm2", .driver_data = (void *)TPS6586X_ID_SM_2 },
{ .name = "ldo0", .driver_data = (void *)TPS6586X_ID_LDO_0 },
{ .name = "ldo1", .driver_data = (void *)TPS6586X_ID_LDO_1 },
{ .name = "ldo2", .driver_data = (void *)TPS6586X_ID_LDO_2 },
{ .name = "ldo3", .driver_data = (void *)TPS6586X_ID_LDO_3 },
{ .name = "ldo4", .driver_data = (void *)TPS6586X_ID_LDO_4 },
{ .name = "ldo5", .driver_data = (void *)TPS6586X_ID_LDO_5 },
{ .name = "ldo6", .driver_data = (void *)TPS6586X_ID_LDO_6 },
{ .name = "ldo7", .driver_data = (void *)TPS6586X_ID_LDO_7 },
{ .name = "ldo8", .driver_data = (void *)TPS6586X_ID_LDO_8 },
{ .name = "ldo9", .driver_data = (void *)TPS6586X_ID_LDO_9 },
{ .name = "ldo_rtc", .driver_data = (void *)TPS6586X_ID_LDO_RTC },
};
static struct tps6586x_platform_data *tps6586x_parse_regulator_dt(
struct platform_device *pdev,
struct of_regulator_match **tps6586x_reg_matches)
{
const unsigned int num = ARRAY_SIZE(tps6586x_matches);
struct device_node *np = pdev->dev.parent->of_node;
struct device_node *regs;
const char *sys_rail = NULL;
unsigned int i;
struct tps6586x_platform_data *pdata;
int err;
regs = of_get_child_by_name(np, "regulators");
if (!regs) {
dev_err(&pdev->dev, "regulator node not found\n");
return NULL;
}
err = of_regulator_match(&pdev->dev, regs, tps6586x_matches, num);
of_node_put(regs);
if (err < 0) {
dev_err(&pdev->dev, "Regulator match failed, e %d\n", err);
return NULL;
}
pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return NULL;
for (i = 0; i < num; i++) {
uintptr_t id;
if (!tps6586x_matches[i].init_data)
continue;
pdata->reg_init_data[i] = tps6586x_matches[i].init_data;
id = (uintptr_t)tps6586x_matches[i].driver_data;
if (id == TPS6586X_ID_SYS)
sys_rail = pdata->reg_init_data[i]->constraints.name;
if ((id == TPS6586X_ID_LDO_5) || (id == TPS6586X_ID_LDO_RTC))
pdata->reg_init_data[i]->supply_regulator = sys_rail;
}
*tps6586x_reg_matches = tps6586x_matches;
return pdata;
}
#else
static struct tps6586x_platform_data *tps6586x_parse_regulator_dt(
struct platform_device *pdev,
struct of_regulator_match **tps6586x_reg_matches)
{
*tps6586x_reg_matches = NULL;
return NULL;
}
#endif
static int tps6586x_regulator_probe(struct platform_device *pdev)
{
struct tps6586x_regulator *ri = NULL;
struct regulator_config config = { };
struct regulator_dev *rdev;
struct regulator_init_data *reg_data;
struct tps6586x_platform_data *pdata;
struct of_regulator_match *tps6586x_reg_matches = NULL;
int version;
int id;
int err;
dev_dbg(&pdev->dev, "Probing regulator\n");
pdata = dev_get_platdata(pdev->dev.parent);
if ((!pdata) && (pdev->dev.parent->of_node))
pdata = tps6586x_parse_regulator_dt(pdev,
&tps6586x_reg_matches);
if (!pdata) {
dev_err(&pdev->dev, "Platform data not available, exiting\n");
return -ENODEV;
}
version = tps6586x_get_version(pdev->dev.parent);
for (id = 0; id < TPS6586X_ID_MAX_REGULATOR; ++id) {
reg_data = pdata->reg_init_data[id];
ri = find_regulator_info(id, version);
if (!ri) {
dev_err(&pdev->dev, "invalid regulator ID specified\n");
return -EINVAL;
}
err = tps6586x_regulator_preinit(pdev->dev.parent, ri);
if (err) {
dev_err(&pdev->dev,
"regulator %d preinit failed, e %d\n", id, err);
return err;
}
config.dev = pdev->dev.parent;
config.init_data = reg_data;
config.driver_data = ri;
if (tps6586x_reg_matches)
config.of_node = tps6586x_reg_matches[id].of_node;
rdev = devm_regulator_register(&pdev->dev, &ri->desc, &config);
if (IS_ERR(rdev)) {
dev_err(&pdev->dev, "failed to register regulator %s\n",
ri->desc.name);
return PTR_ERR(rdev);
}
if (reg_data) {
err = tps6586x_regulator_set_slew_rate(pdev, id,
reg_data);
if (err < 0) {
dev_err(&pdev->dev,
"Slew rate config failed, e %d\n", err);
return err;
}
}
}
platform_set_drvdata(pdev, rdev);
return 0;
}
static struct platform_driver tps6586x_regulator_driver = {
.driver = {
.name = "tps6586x-regulator",
},
.probe = tps6586x_regulator_probe,
};
static int __init tps6586x_regulator_init(void)
{
return platform_driver_register(&tps6586x_regulator_driver);
}
subsys_initcall(tps6586x_regulator_init);
static void __exit tps6586x_regulator_exit(void)
{
platform_driver_unregister(&tps6586x_regulator_driver);
}
module_exit(tps6586x_regulator_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mike Rapoport <mike@compulab.co.il>");
MODULE_DESCRIPTION("Regulator Driver for TI TPS6586X PMIC");
MODULE_ALIAS("platform:tps6586x-regulator");
| {
"pile_set_name": "Github"
} |
{
"NonZeroValue_CALL_ToNonNonZeroBalance_d0g0v0_Istanbul" : {
"_info" : {
"comment" : "",
"filling-rpc-server" : "Geth-1.9.6-unstable-63b18027-20190920",
"filling-tool-version" : "retesteth-0.0.1+commit.0ae18aef.Linux.g++",
"lllcversion" : "Version: 0.5.12-develop.2019.9.13+commit.2d601a4f.Linux.g++",
"source" : "src/GeneralStateTestsFiller/stNonZeroCallsTest/NonZeroValue_CALL_ToNonNonZeroBalanceFiller.json",
"sourceHash" : "74a253412cad10d43a3632152d2d3d461ac474860c683f49e2bb6f9dc10db03f"
},
"genesisBlockHeader" : {
"bloom" : "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"coinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"difficulty" : "0x20000",
"extraData" : "0x00",
"gasLimit" : "0x989680",
"gasUsed" : "0x0",
"hash" : "0x1833f7081c392d8268bd509ee2e3b55858bf056fedd533ed0dc3fd981735088e",
"mixHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"nonce" : "0x0000000000000000",
"number" : "0x0",
"parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"receiptTrie" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"stateRoot" : "0x23855517542adc11f43bd4941c37d22e8ff150b8c5543fb046360e2b4f4f3b65",
"timestamp" : "0x0",
"transactionsTrie" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"uncleHash" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
},
"pre" : {
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0xe8d4a51000",
"code" : "0x",
"nonce" : "0x00",
"storage" : {
}
},
"0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x00",
"code" : "0x5a6000556000600060006000600173c94f5374fce5edbc8e2a8697c15331677e6ebf0b61ea60f16001555a60645500",
"nonce" : "0x00",
"storage" : {
}
},
"0xc94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x64",
"code" : "0x",
"nonce" : "0x00",
"storage" : {
}
}
},
"postState" : {
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"code" : "0x",
"nonce" : "0x01",
"balance" : "0xe8d4a4018e",
"storage" : {
}
},
"0xc94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"code" : "0x",
"nonce" : "0x00",
"balance" : "0x64",
"storage" : {
}
},
"0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" : {
"code" : "0x",
"nonce" : "0x00",
"balance" : "0x1bc16d674ec90e72",
"storage" : {
}
},
"0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"code" : "0x5a6000556000600060006000600173c94f5374fce5edbc8e2a8697c15331677e6ebf0b61ea60f16001555a60645500",
"nonce" : "0x00",
"balance" : "0x00",
"storage" : {
"0x64" : "0x086771",
"0x00" : "0x08d5b6"
}
}
},
"network" : "Istanbul",
"sealEngine" : "NoProof",
"lastblockhash" : "0xde5937ade526e002205e7bcf3e3f42cf6535aaffec5cbacdc59eedfbceeb90dc",
"genesisRLP" : "0xf901f8f901f3a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa023855517542adc11f43bd4941c37d22e8ff150b8c5543fb046360e2b4f4f3b65a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200008083989680808000a00000000000000000000000000000000000000000000000000000000000000000880000000000000000c0c0",
"blocks" : [
{
"rlp" : "0xf90260f901f8a01833f7081c392d8268bd509ee2e3b55858bf056fedd533ed0dc3fd981735088ea01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa03740fc2bcb3646905d4ffb2a6d3e15bc25802174ecca6abe13873166051ea22ba059652e5662eb625efd106d67b9b25d3c12a15e69494d1d24f59d867c211f6761a0d31f204b921a6b93d81e5cba328f4b8d63924f842824c3753959d329a5ebe425b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000018398bca483010e728203e800a00000000000000000000000000000000000000000000000000000000000000000880000000000000000f862f8608001830927c094b94f5374fce5edbc8e2a8697c15331677e6ebf0b80801ba08d0699f23d032b86db35ed7bb39c2357bec870fbfbe7db30b1795d320d8965c6a002f578fd949e84f0dc1307f5dd714c9a7158b31891d43f45459edcb52e345f7cc0",
"blockHeader" : {
"bloom" : "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"coinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"difficulty" : "0x20000",
"extraData" : "0x00",
"gasLimit" : "0x98bca4",
"gasUsed" : "0x10e72",
"hash" : "0xde5937ade526e002205e7bcf3e3f42cf6535aaffec5cbacdc59eedfbceeb90dc",
"mixHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"nonce" : "0x0000000000000000",
"number" : "0x1",
"parentHash" : "0x1833f7081c392d8268bd509ee2e3b55858bf056fedd533ed0dc3fd981735088e",
"receiptTrie" : "0xd31f204b921a6b93d81e5cba328f4b8d63924f842824c3753959d329a5ebe425",
"stateRoot" : "0x3740fc2bcb3646905d4ffb2a6d3e15bc25802174ecca6abe13873166051ea22b",
"timestamp" : "0x3e8",
"transactionsTrie" : "0x59652e5662eb625efd106d67b9b25d3c12a15e69494d1d24f59d867c211f6761",
"uncleHash" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
},
"transactions" : [
{
"data" : "0x",
"gasLimit" : "0x0927c0",
"gasPrice" : "0x01",
"nonce" : "0x00",
"to" : "0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"value" : "0x00",
"v" : "0x1b",
"r" : "0x8d0699f23d032b86db35ed7bb39c2357bec870fbfbe7db30b1795d320d8965c6",
"s" : "0x02f578fd949e84f0dc1307f5dd714c9a7158b31891d43f45459edcb52e345f7c"
}
]
}
]
}
} | {
"pile_set_name": "Github"
} |
// This module implements the QsciPrinter class.
//
// Copyright (c) 2017 Riverbank Computing Limited <info@riverbankcomputing.com>
//
// This file is part of QScintilla.
//
// This file may be used under the terms of the GNU General Public License
// version 3.0 as published by the Free Software Foundation and appearing in
// the file LICENSE included in the packaging of this file. Please review the
// following information to ensure the GNU General Public License version 3.0
// requirements will be met: http://www.gnu.org/copyleft/gpl.html.
//
// If you do not wish to use this file under the terms of the GPL version 3.0
// then you may purchase a commercial license. For more information contact
// info@riverbankcomputing.com.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#include "Qsci/qsciprinter.h"
#if !defined(QT_NO_PRINTER)
#include <QPrinter>
#include <QPainter>
#include <QStack>
#include "Qsci/qsciscintillabase.h"
// The ctor.
QsciPrinter::QsciPrinter(QPrinter::PrinterMode mode)
: QPrinter(mode), mag(0), wrap(QsciScintilla::WrapWord)
{
}
// The dtor.
QsciPrinter::~QsciPrinter()
{
}
// Format the page before the document text is drawn.
void QsciPrinter::formatPage(QPainter &, bool, QRect &, int)
{
}
// Print a range of lines to a printer.
int QsciPrinter::printRange(QsciScintillaBase *qsb, int from, int to)
{
// Sanity check.
if (!qsb)
return false;
// Setup the printing area.
QRect def_area;
def_area.setX(0);
def_area.setY(0);
def_area.setWidth(width());
def_area.setHeight(height());
// Get the page range.
int pgFrom, pgTo;
pgFrom = fromPage();
pgTo = toPage();
// Find the position range.
long startPos, endPos;
endPos = qsb->SendScintilla(QsciScintillaBase::SCI_GETLENGTH);
startPos = (from > 0 ? qsb -> SendScintilla(QsciScintillaBase::SCI_POSITIONFROMLINE,from) : 0);
if (to >= 0)
{
long toPos = qsb -> SendScintilla(QsciScintillaBase::SCI_POSITIONFROMLINE,to + 1);
if (endPos > toPos)
endPos = toPos;
}
if (startPos >= endPos)
return false;
QPainter painter(this);
bool reverse = (pageOrder() == LastPageFirst);
bool needNewPage = false;
qsb -> SendScintilla(QsciScintillaBase::SCI_SETPRINTMAGNIFICATION,mag);
qsb -> SendScintilla(QsciScintillaBase::SCI_SETPRINTWRAPMODE,wrap);
for (int i = 1; i <= numCopies(); ++i)
{
// If we are printing in reverse page order then remember the start
// position of each page.
QStack<long> pageStarts;
int currPage = 1;
long pos = startPos;
while (pos < endPos)
{
// See if we have finished the requested page range.
if (pgTo > 0 && pgTo < currPage)
break;
// See if we are going to render this page, or just see how much
// would fit onto it.
bool render = false;
if (pgFrom == 0 || pgFrom <= currPage)
{
if (reverse)
pageStarts.push(pos);
else
{
render = true;
if (needNewPage)
{
if (!newPage())
return false;
}
else
needNewPage = true;
}
}
QRect area = def_area;
formatPage(painter,render,area,currPage);
pos = qsb -> SendScintilla(QsciScintillaBase::SCI_FORMATRANGE,render,&painter,area,pos,endPos);
++currPage;
}
// All done if we are printing in normal page order.
if (!reverse)
continue;
// Now go through each page on the stack and really print it.
while (!pageStarts.isEmpty())
{
--currPage;
long ePos = pos;
pos = pageStarts.pop();
if (needNewPage)
{
if (!newPage())
return false;
}
else
needNewPage = true;
QRect area = def_area;
formatPage(painter,true,area,currPage);
qsb->SendScintilla(QsciScintillaBase::SCI_FORMATRANGE,true,&painter,area,pos,ePos);
}
}
return true;
}
// Set the print magnification in points.
void QsciPrinter::setMagnification(int magnification)
{
mag = magnification;
}
// Set the line wrap mode.
void QsciPrinter::setWrapMode(QsciScintilla::WrapMode wmode)
{
wrap = wmode;
}
#endif
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2011, Chris Aniszczyk <caniszczyk@gmail.com> and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.api;
import java.io.IOException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.notes.Note;
import org.eclipse.jgit.notes.NoteMap;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevObject;
import org.eclipse.jgit.revwalk.RevWalk;
/**
* Show an object note.
*
* @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-notes.html"
* >Git documentation about Notes</a>
*/
public class ShowNoteCommand extends GitCommand<Note> {
private RevObject id;
private String notesRef = Constants.R_NOTES_COMMITS;
/**
* Constructor for ShowNoteCommand.
*
* @param repo
* the {@link org.eclipse.jgit.lib.Repository}
*/
protected ShowNoteCommand(Repository repo) {
super(repo);
}
/** {@inheritDoc} */
@Override
public Note call() throws GitAPIException {
checkCallable();
NoteMap map = NoteMap.newEmptyMap();
RevCommit notesCommit = null;
try (RevWalk walk = new RevWalk(repo)) {
Ref ref = repo.exactRef(notesRef);
// if we have a notes ref, use it
if (ref != null) {
notesCommit = walk.parseCommit(ref.getObjectId());
map = NoteMap.read(walk.getObjectReader(), notesCommit);
}
return map.getNote(id);
} catch (IOException e) {
throw new JGitInternalException(e.getMessage(), e);
}
}
/**
* Sets the object id of object you want a note on
*
* @param id
* the {@link org.eclipse.jgit.revwalk.RevObject} to show notes
* for.
* @return {@code this}
*/
public ShowNoteCommand setObjectId(RevObject id) {
checkCallable();
this.id = id;
return this;
}
/**
* Set the {@code Ref} to read notes from.
*
* @param notesRef
* the ref to read notes from. Note, the default value of
* {@link org.eclipse.jgit.lib.Constants#R_NOTES_COMMITS} will be
* used if nothing is set
* @return {@code this}
* @see Constants#R_NOTES_COMMITS
*/
public ShowNoteCommand setNotesRef(String notesRef) {
checkCallable();
this.notesRef = notesRef;
return this;
}
}
| {
"pile_set_name": "Github"
} |
/*
* linux/fs/isofs/namei.c
*
* (C) 1992 Eric Youngdale Modified for ISO 9660 filesystem.
*
* (C) 1991 Linus Torvalds - minix filesystem
*/
#include <linux/gfp.h>
#include "isofs.h"
/*
* ok, we cannot use strncmp, as the name is not in our data space.
* Thus we'll have to use isofs_match. No big problem. Match also makes
* some sanity tests.
*/
static int
isofs_cmp(struct dentry *dentry, const char *compare, int dlen)
{
struct qstr qstr;
if (!compare)
return 1;
/* check special "." and ".." files */
if (dlen == 1) {
/* "." */
if (compare[0] == 0) {
if (!dentry->d_name.len)
return 0;
compare = ".";
} else if (compare[0] == 1) {
compare = "..";
dlen = 2;
}
}
qstr.name = compare;
qstr.len = dlen;
return dentry->d_op->d_compare(NULL, NULL, NULL, NULL,
dentry->d_name.len, dentry->d_name.name, &qstr);
}
/*
* isofs_find_entry()
*
* finds an entry in the specified directory with the wanted name. It
* returns the inode number of the found entry, or 0 on error.
*/
static unsigned long
isofs_find_entry(struct inode *dir, struct dentry *dentry,
unsigned long *block_rv, unsigned long *offset_rv,
char *tmpname, struct iso_directory_record *tmpde)
{
unsigned long bufsize = ISOFS_BUFFER_SIZE(dir);
unsigned char bufbits = ISOFS_BUFFER_BITS(dir);
unsigned long block, f_pos, offset, block_saved, offset_saved;
struct buffer_head *bh = NULL;
struct isofs_sb_info *sbi = ISOFS_SB(dir->i_sb);
if (!ISOFS_I(dir)->i_first_extent)
return 0;
f_pos = 0;
offset = 0;
block = 0;
while (f_pos < dir->i_size) {
struct iso_directory_record *de;
int de_len, match, i, dlen;
char *dpnt;
if (!bh) {
bh = isofs_bread(dir, block);
if (!bh)
return 0;
}
de = (struct iso_directory_record *) (bh->b_data + offset);
de_len = *(unsigned char *) de;
if (!de_len) {
brelse(bh);
bh = NULL;
f_pos = (f_pos + ISOFS_BLOCK_SIZE) & ~(ISOFS_BLOCK_SIZE - 1);
block = f_pos >> bufbits;
offset = 0;
continue;
}
block_saved = bh->b_blocknr;
offset_saved = offset;
offset += de_len;
f_pos += de_len;
/* Make sure we have a full directory entry */
if (offset >= bufsize) {
int slop = bufsize - offset + de_len;
memcpy(tmpde, de, slop);
offset &= bufsize - 1;
block++;
brelse(bh);
bh = NULL;
if (offset) {
bh = isofs_bread(dir, block);
if (!bh)
return 0;
memcpy((void *) tmpde + slop, bh->b_data, offset);
}
de = tmpde;
}
dlen = de->name_len[0];
dpnt = de->name;
/* Basic sanity check, whether name doesn't exceed dir entry */
if (de_len < dlen + sizeof(struct iso_directory_record)) {
printk(KERN_NOTICE "iso9660: Corrupted directory entry"
" in block %lu of inode %lu\n", block,
dir->i_ino);
return 0;
}
if (sbi->s_rock &&
((i = get_rock_ridge_filename(de, tmpname, dir)))) {
dlen = i; /* possibly -1 */
dpnt = tmpname;
#ifdef CONFIG_JOLIET
} else if (sbi->s_joliet_level) {
dlen = get_joliet_filename(de, tmpname, dir);
dpnt = tmpname;
#endif
} else if (sbi->s_mapping == 'a') {
dlen = get_acorn_filename(de, tmpname, dir);
dpnt = tmpname;
} else if (sbi->s_mapping == 'n') {
dlen = isofs_name_translate(de, tmpname, dir);
dpnt = tmpname;
}
/*
* Skip hidden or associated files unless hide or showassoc,
* respectively, is set
*/
match = 0;
if (dlen > 0 &&
(!sbi->s_hide ||
(!(de->flags[-sbi->s_high_sierra] & 1))) &&
(sbi->s_showassoc ||
(!(de->flags[-sbi->s_high_sierra] & 4)))) {
match = (isofs_cmp(dentry, dpnt, dlen) == 0);
}
if (match) {
isofs_normalize_block_and_offset(de,
&block_saved,
&offset_saved);
*block_rv = block_saved;
*offset_rv = offset_saved;
brelse(bh);
return 1;
}
}
brelse(bh);
return 0;
}
struct dentry *isofs_lookup(struct inode *dir, struct dentry *dentry, struct nameidata *nd)
{
int found;
unsigned long uninitialized_var(block);
unsigned long uninitialized_var(offset);
struct inode *inode;
struct page *page;
page = alloc_page(GFP_USER);
if (!page)
return ERR_PTR(-ENOMEM);
found = isofs_find_entry(dir, dentry,
&block, &offset,
page_address(page),
1024 + page_address(page));
__free_page(page);
inode = found ? isofs_iget(dir->i_sb, block, offset) : NULL;
return d_splice_alias(inode, dentry);
}
| {
"pile_set_name": "Github"
} |
# /* Copyright (C) 2001
# * Housemarque Oy
# * http://www.housemarque.com
# *
# * 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)
# */
#
# /* Revised by Paul Mensonides (2002) */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_CAT_HPP
# define BOOST_PREPROCESSOR_CAT_HPP
#
# include <boost/preprocessor/config/config.hpp>
#
# /* BOOST_PP_CAT */
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_MWCC()
# define BOOST_PP_CAT(a, b) BOOST_PP_CAT_I(a, b)
# else
# define BOOST_PP_CAT(a, b) BOOST_PP_CAT_OO((a, b))
# define BOOST_PP_CAT_OO(par) BOOST_PP_CAT_I ## par
# endif
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_MSVC()
# define BOOST_PP_CAT_I(a, b) a ## b
# else
# define BOOST_PP_CAT_I(a, b) BOOST_PP_CAT_II(~, a ## b)
# define BOOST_PP_CAT_II(p, res) res
# endif
#
# endif
| {
"pile_set_name": "Github"
} |
// @flow
import o from "ospec/ospec.js"
import n from '../../nodemocker'
import {CryptoError} from "../../../../src/api/common/error/CryptoError"
import {uint8ArrayToBitArray} from "../../../../src/api/worker/crypto/CryptoUtils"
o.spec("DesktopAlarmStorageTest", () => {
n.startGroup({
group: __filename, allowables: [
"./TutanotaError",
"../error/CryptoError",
"../../api/common/utils/Encoding",
"../../api/common/error/CryptoError",
"./StringUtils",
"./EntityConstants",
"./Utils",
"../../api/common/utils/Utils",
"./utils/Utils",
"../TutanotaConstants",
"./utils/ArrayUtils",
"./MapUtils",
]
})
const electron = {}
const keytar = {
findPassword: () => Promise.resolve("password")
}
const crypto = {
aes256DecryptKeyToB64: (pw, data) => {
if (data !== "user3pw=") {
throw new CryptoError("nope")
}
return "decryptedKey"
},
aes256EncryptKeyToB64: (pw, data) => "password"
}
const entityFunctions = {
elementIdPart: (tuple) => tuple[1]
}
const wm = {}
const cryptoUtils = {
uint8ArrayToBitArray
}
const conf = {
getVar: (key: string) => {
switch (key) {
case "pushEncSessionKeys":
return {
"user1": "user1pw=",
"user2": "user2pw=",
"twoId": "user3pw=",
"fourId": "user4pw=",
}
default:
throw new Error(`unexpected getVar key ${key}`)
}
},
setVar: () => {}
}
const aes = {}
const standardMocks = () => {
// node modules
const electronMock = n.mock("electron", electron).set()
const keytarMock = n.mock("keytar", keytar).set()
// our modules
const entityFunctionMock = n.mock("../EntityFunctions", entityFunctions).set()
n.mock('../../api/common/EntityFunctions', entityFunctions).set()
const aesMock = n.mock('../../api/worker/crypto/Aes', aes).set()
const cryptoMock = n.mock("../DesktopCryptoFacade", crypto).set()
const cryptoUtilsMock = n.mock("../../api/worker/crypto/CryptoUtils", cryptoUtils).set()
// instances
const wmMock = n.mock('__wm', wm).set()
const confMock = n.mock("__conf", conf).set()
return {
electronMock,
keytarMock,
cryptoMock,
confMock,
wmMock,
aesMock,
entityFunctionMock
}
}
o("init", () => {
const {confMock, cryptoMock} = standardMocks()
const {DesktopAlarmStorage} = n.subject('../../src/desktop/sse/DesktopAlarmStorage.js')
const desktopStorage = new DesktopAlarmStorage(confMock, cryptoMock)
desktopStorage.init().then()
})
o("resolvePushIdentifierSessionKey with uncached sessionKey", done => {
const {confMock, cryptoMock} = standardMocks()
const {DesktopAlarmStorage} = n.subject('../../src/desktop/sse/DesktopAlarmStorage.js')
const desktopStorage = new DesktopAlarmStorage(confMock, cryptoMock)
desktopStorage.init().then(() => desktopStorage.resolvePushIdentifierSessionKey([
{pushIdentifierSessionEncSessionKey: "abc", pushIdentifier: ["oneId", "twoId"]},
{pushIdentifierSessionEncSessionKey: "def", pushIdentifier: ["threeId", "fourId"]}
])
).then(() => {
o(cryptoMock.aes256DecryptKeyToB64.callCount).equals(2)
}).then(() => done())
})
o("resolvePushIdentifierSessionKey with cached sessionKey", done => {
const {cryptoMock} = standardMocks()
const confMock = n.mock("__conf", conf).with({
getVar: key => {}
}).set()
const {DesktopAlarmStorage} = n.subject('../../src/desktop/sse/DesktopAlarmStorage.js')
const desktopStorage = new DesktopAlarmStorage(confMock, cryptoMock)
desktopStorage.init().then(() => {
return desktopStorage.storePushIdentifierSessionKey("fourId", "user4pw=")
}).then(() => desktopStorage.resolvePushIdentifierSessionKey([
{pushIdentifierSessionEncSessionKey: "abc", pushIdentifier: ["oneId", "twoId"]},
{pushIdentifierSessionEncSessionKey: "def", pushIdentifier: ["threeId", "fourId"]}
])
).then(() => {
o(cryptoMock.aes256DecryptKeyToB64.callCount).equals(0)
o(confMock.setVar.callCount).equals(1)
o(confMock.setVar.args.length).equals(2)
o(confMock.setVar.args[0]).equals("pushEncSessionKeys")
o(confMock.setVar.args[1]).deepEquals({fourId: "password"})
}).then(() => done())
})
})
| {
"pile_set_name": "Github"
} |
<?php
/**
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cloud
* @subpackage QueueService
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* Common interface for queue services in the cloud. This interface supports
* most queue services and provides some flexibility for vendor-specific
* features and requirements via an optional $options array in each method
* signature. Classes implementing this interface should implement URI
* construction for queues from the parameters given in each method and the
* account data passed in to the constructor. Classes implementing this
* interface are also responsible for security; access control isn't currently
* supported in this interface, although we are considering access control
* support in future versions of the interface.
*
* @category Zend
* @package Zend_Cloud
* @subpackage QueueService
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Cloud_QueueService_Adapter
{
/** Ctor HTTP adapter option */
const HTTP_ADAPTER = 'http_adapter';
/** Message visibility timeout option */
const VISIBILITY_TIMEOUT = 'visibility_timeout';
/** Default visibility timeout */
const DEFAULT_TIMEOUT = 30;
/**
* Create a queue. Returns the ID of the created queue (typically the URL).
* It may take some time to create the queue. Check your vendor's
* documentation for details.
*
* Name constraints: Maximum 80 characters
* Only alphanumeric characters, hyphens (-), and underscores (_)
*
* @param string $name
* @param array $options
* @return string Queue ID (typically URL)
*/
public function createQueue($name, $options = null);
/**
* Delete a queue. All messages in the queue will also be deleted.
*
* @param string $queueId
* @param array $options
* @return boolean true if successful, false otherwise
*/
public function deleteQueue($queueId, $options = null);
/**
* List all queues.
*
* @param array $options
* @return array Queue IDs
*/
public function listQueues($options = null);
/**
* Get a key/value array of metadata for the given queue.
*
* @param string $queueId
* @param array $options
* @return array
*/
public function fetchQueueMetadata($queueId, $options = null);
/**
* Store a key/value array of metadata for the specified queue.
* WARNING: This operation overwrites any metadata that is located at
* $destinationPath. Some adapters may not support this method.
*
* @param string $queueId
* @param array $metadata
* @param array $options
* @return void
*/
public function storeQueueMetadata($queueId, $metadata, $options = null);
/**
* Send a message to the specified queue.
*
* @param string $queueId
* @param string $message
* @param array $options
* @return string Message ID
*/
public function sendMessage($queueId, $message, $options = null);
/**
* Recieve at most $max messages from the specified queue and return the
* message IDs for messages recieved.
*
* @param string $queueId
* @param int $max
* @param array $options
* @return array[Zend_Cloud_QueueService_Message] Array of messages
*/
public function receiveMessages($queueId, $max = 1, $options = null);
/**
* Peek at the messages from the specified queue without removing them.
*
* @param string $queueId
* @param int $num How many messages
* @param array $options
* @return array[Zend_Cloud_QueueService_Message]
*/
public function peekMessages($queueId, $num = 1, $options = null);
/**
* Delete the specified message from the specified queue.
*
* @param string $queueId
* @param Zend_Cloud_QueueService_Message $message Message to delete
* @param array $options
* @return void
*
*/
public function deleteMessage($queueId, $message, $options = null);
/**
* Get the concrete adapter.
*/
public function getClient();
}
| {
"pile_set_name": "Github"
} |
This is test download file.
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2018 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "arm_compute/core/Types.h"
#include "arm_compute/runtime/CL/CLTensor.h"
#include "arm_compute/runtime/CL/CLTensorAllocator.h"
#include "arm_compute/runtime/CL/functions/CLGaussianPyramid.h"
#include "tests/CL/CLAccessor.h"
#include "tests/PaddingCalculator.h"
#include "tests/datasets/BorderModeDataset.h"
#include "tests/datasets/ShapeDatasets.h"
#include "tests/framework/Asserts.h"
#include "tests/framework/Macros.h"
#include "tests/framework/datasets/Datasets.h"
#include "tests/validation/Validation.h"
#include "tests/validation/fixtures/GaussianPyramidHalfFixture.h"
#include "tests/validation/reference/Utils.h"
namespace arm_compute
{
namespace test
{
namespace validation
{
namespace
{
const auto small_gaussian_pyramid_levels = combine(datasets::Medium2DShapes(), datasets::BorderModes()) * framework::dataset::make("numlevels", 2, 4);
const auto large_gaussian_pyramid_levels = combine(datasets::Large2DShapes(), datasets::BorderModes()) * framework::dataset::make("numlevels", 2, 5);
template <typename T>
inline void validate_gaussian_pyramid(const CLPyramid &target, const std::vector<SimpleTensor<T>> &reference, BorderMode border_mode)
{
ValidRegion prev_valid_region = shape_to_valid_region(reference[0].shape());
for(size_t i = 1; i < reference.size(); ++i)
{
const ValidRegion valid_region = shape_to_valid_region_gaussian_pyramid_half(reference[i - 1].shape(), prev_valid_region, (border_mode == BorderMode::UNDEFINED));
// Validate outputs
validate(CLAccessor(*(target.get_pyramid_level(i))), reference[i], valid_region);
// Keep the valid region for the next level
prev_valid_region = valid_region;
}
}
} // namespace
TEST_SUITE(CL)
TEST_SUITE(GaussianPyramid)
TEST_SUITE(Half)
DATA_TEST_CASE(Configuration, framework::DatasetMode::ALL, large_gaussian_pyramid_levels,
shape, border_mode, num_levels)
{
CLTensor src = create_tensor<CLTensor>(shape, DataType::U8);
// Create pyramid
PyramidInfo pyramid_info(num_levels, SCALE_PYRAMID_HALF, shape, Format::U8);
CLPyramid dst;
dst.init(pyramid_info);
CLGaussianPyramidHalf gaussian_pyramid_half;
gaussian_pyramid_half.configure(&src, &dst, border_mode, 0);
ARM_COMPUTE_EXPECT(src.info()->is_resizable(), framework::LogLevel::ERRORS);
for(size_t level = 0; level < pyramid_info.num_levels(); ++level)
{
ARM_COMPUTE_EXPECT(dst.get_pyramid_level(level)->info()->is_resizable(), framework::LogLevel::ERRORS);
}
}
template <typename T>
using CLGaussianPyramidHalfFixture = GaussianPyramidHalfValidationFixture<CLTensor, CLAccessor, CLGaussianPyramidHalf, T, CLPyramid>;
FIXTURE_DATA_TEST_CASE(RunSmallGaussianPyramidHalf, CLGaussianPyramidHalfFixture<uint8_t>, framework::DatasetMode::ALL, small_gaussian_pyramid_levels)
{
validate_gaussian_pyramid(_target, _reference, _border_mode);
}
FIXTURE_DATA_TEST_CASE(RunLargeGaussianPyramidHalf, CLGaussianPyramidHalfFixture<uint8_t>, framework::DatasetMode::NIGHTLY, large_gaussian_pyramid_levels)
{
validate_gaussian_pyramid(_target, _reference, _border_mode);
}
TEST_SUITE_END()
TEST_SUITE_END()
TEST_SUITE_END()
} // namespace validation
} // namespace test
} // namespace arm_compute
| {
"pile_set_name": "Github"
} |
## Written 2006 by Martin Bartosch for the OpenXPKI project
## Copyright (C) 2005-2011 by The OpenXPKI Project
TOPDIR=../../..
# Makefile.local may be used locally to override settings (not checked in)
-include ../Makefile.local
# Makefile.inc contains common settings for all packages (checked in)
include ../Makefile.inc
PACKAGE=myperl-openxpki-enroll
SRCBASE=$(TOPDIR)/clients/perl/OpenXPKI-Client-Enrollment
SRCNAME=$(PACKAGE)
OXI_TARBALL = $(shell rpm --eval '%{_topdir}')/SOURCES/$(PACKAGE)-$(OXI_VERSION).tar.gz
OXI_TARBALL_DIR = $(shell rpm --eval '%{_topdir}')/BUILD/tmp/$(PACKAGE)-$(OXI_VERSION)
all: clean package
$(PACKAGE).spec: $(PACKAGE).spec.template
package: $(PACKAGE).spec $(OXI_TARBALL)
PERL_LOCAL_LIB_ROOT= PERL_MB_OPT= PERL_MM_OPT= rpmbuild -ba $(PACKAGE).spec
collect:
mv $(RPMBASE)/SRPMS/$(PACKAGE)-*.rpm .
mv $(RPMBASE)/RPMS/*/$(PACKAGE)-*.rpm .
clean:
rm -f $(PACKAGE)-*.rpm $(PACKAGE).spec $(OXI_TARBALL)
$(OXI_TARBALL):
rm -rf $(OXI_TARBALL_DIR)
mkdir -p $(OXI_TARBALL_DIR)
(cd ../../.. && tar cf - \
ISSUES LICENSE README.pod clients config core doc package qatest tools) \
| tar xf - -C $(OXI_TARBALL_DIR)
echo $(OXI_VERSION) > $(OXI_TARBALL_DIR)/VERSION
tar czf $@ -C $(OXI_TARBALL_DIR)/.. .
| {
"pile_set_name": "Github"
} |
import * as THREE from 'three';
class PointCloudNode extends THREE.EventDispatcher {
constructor(numPoints = 0, layer) {
super();
this.numPoints = numPoints;
this.layer = layer;
this.children = [];
this.bbox = new THREE.Box3();
this.sse = -1;
}
add(node, indexChild) {
this.children.push(node);
node.parent = this;
this.createChildAABB(node, indexChild);
}
load() {
// Query octree/HRC if we don't have children potreeNode yet.
if (!this.octreeIsLoaded) {
this.loadOctree();
}
return this.layer.source.fetcher(this.url, this.layer.source.networkOptions).then(this.layer.source.parse);
}
findCommonAncestor(node) {
if (node.depth == this.depth) {
if (node.id == this.id) {
return node;
} else if (node.depth != 0) {
return this.parent.findCommonAncestor(node.parent);
}
} else if (node.depth < this.depth) {
return this.parent.findCommonAncestor(node);
} else {
return this.findCommonAncestor(node.parent);
}
}
}
export default PointCloudNode;
| {
"pile_set_name": "Github"
} |
// Open Shading Language : Copyright (c) 2009-2017 Sony Pictures Imageworks Inc., et al.
// https://github.com/imageworks/OpenShadingLanguage/blob/master/LICENSE
//
// MaterialX specification (c) 2017 Lucasfilm Ltd.
// http://www.materialx.org/
#include "mx_funcs.h"
shader mx_smoothstep_float_color
[[ string help = "outputs a smooth (hermite-interpolated) remapping of input values from low-high to output 0-1." ]]
(
color in = 0
[[ string help = "input" ]],
float low = 0
[[ string help = "input value of this or lower will return 0" ]],
float high = 1
[[ string help = " an input value of this or higher will result in an output value of 1" ]],
output color out = 0
)
{
out = smoothstep(low, high, in);
}
| {
"pile_set_name": "Github"
} |
-- | Unit and property tests for our custom parsing monad.
module Main (main) where
import Control.Applicative (liftA2)
import qualified Data.ByteString as B
import Data.Either (isLeft)
import Test.QuickCheck
import Test.Tasty (defaultMain, testGroup, TestTree)
import Test.Tasty.QuickCheck (testProperty)
import Data.ProtoLens.Encoding.Bytes
import Data.ProtoLens.Encoding.Parser
main :: IO ()
main = defaultMain $ testGroup "tests"
[ testGroup "Parser" testParser
, testGroup "getWord8" testGetWord8
, testGroup "getBytes" testGetBytes
, testGroup "getWord32le" testGetWord32le
, testGroup "failure" testFailure
, testGroup "isolate" testIsolate
]
testParser :: [TestTree]
testParser =
-- Test out the Applicative instance by using "traverse" to read the same number of bytes
-- as in the input.
-- "traverse (const f) g" runs f once for every element of g.
[ testProperty "traverse" $ \ws -> runParser (traverse (const getWord8) ws)
(B.pack ws)
=== Right ws
]
testGetWord8 :: [TestTree]
testGetWord8 =
[ testProperty "atEnd" $ \ws -> runParser atEnd (B.pack ws) === Right (null ws)
, testProperty "manyTillEnd"
$ \ws -> runParser (manyTillEnd getWord8) (B.pack ws) === Right ws
]
testGetBytes :: [TestTree]
testGetBytes =
[ testProperty "many"
$ \ws -> let
packed = map B.pack ws
in runParser (mapM (getBytes . B.length) packed) (B.concat packed)
=== Right packed
, testProperty "negative length"
$ \n ws -> n < 0 ==> counterexampleF isLeft
(runParser (getBytes n) $ B.pack ws)
]
testGetWord32le :: [TestTree]
testGetWord32le =
[ testProperty "align"
$ \ws -> length ws `mod` 4 /= 0 ==>
counterexampleF isLeft (runParser (manyTillEnd getWord32le) (B.pack ws))
, testProperty "manyTillEnd" $ \ws ->
runParser (manyTillEnd getWord32le) (runBuilder $ foldMap putFixed32 ws)
=== Right ws
]
testFailure :: [TestTree]
testFailure =
[ testProperty "fail-fast" $ \bs ->
runParser (fail "abcde") (B.pack bs)
=== (Left "abcde" :: Either String ())
, testProperty "<?>" $ \bs ->
runParser (fail "abcde" <?> "fghij") (B.pack bs)
=== (Left "fghij: abcde" :: Either String ())
]
testIsolate :: [TestTree]
testIsolate =
[ testProperty "many" $ \bs bs' ->
runParser (liftA2 (,) (isolate (length bs) $ manyTillEnd getWord8)
(manyTillEnd getWord8))
(B.pack (bs ++ bs'))
== Right (bs, bs')
, testProperty "negative length" $ \n ws ->
n < 0 ==> counterexampleF isLeft $ runParser (isolate n getWord8) $ B.pack ws
]
-- Since this is a test, just implement the slow stack-heavy way.
manyTillEnd :: Parser a -> Parser [a]
manyTillEnd p = do
end <- atEnd
if end
then return []
else do
x <- p
xs <- manyTillEnd p
return $ x : xs
counterexampleF :: (Testable prop, Show a) => (a -> prop) -> a -> Property
counterexampleF f x = counterexample (show x) $ f x
| {
"pile_set_name": "Github"
} |
' Copyright © Microsoft Corporation. All Rights Reserved.
' This code released under the terms of the
' Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Windows.Navigation
Imports System.Windows.Shapes
Namespace EmployeeTracker
''' <summary>
''' Interaction logic for Banner.xaml
''' </summary>
Partial Public Class Banner
Inherits UserControl
Public Sub New()
InitializeComponent()
End Sub
End Class
End Namespace
| {
"pile_set_name": "Github"
} |
config CLKDEV_LOOKUP
bool
select HAVE_CLK
config HAVE_CLK_PREPARE
bool
config COMMON_CLK
bool
select HAVE_CLK_PREPARE
select CLKDEV_LOOKUP
select SRCU
select RATIONAL
---help---
The common clock framework is a single definition of struct
clk, useful across many platforms, as well as an
implementation of the clock API in include/linux/clk.h.
Architectures utilizing the common struct clk should select
this option.
menu "Common Clock Framework"
depends on COMMON_CLK
config COMMON_CLK_WM831X
tristate "Clock driver for WM831x/2x PMICs"
depends on MFD_WM831X
---help---
Supports the clocking subsystem of the WM831x/2x series of
PMICs from Wolfson Microelectronics.
source "drivers/clk/versatile/Kconfig"
config CLK_HSDK
bool "PLL Driver for HSDK platform"
depends on OF || COMPILE_TEST
---help---
This driver supports the HSDK core, system, ddr, tunnel and hdmi PLLs
control.
config COMMON_CLK_MAX77686
tristate "Clock driver for Maxim 77620/77686/77802 MFD"
depends on MFD_MAX77686 || MFD_MAX77620 || COMPILE_TEST
---help---
This driver supports Maxim 77620/77686/77802 crystal oscillator
clock.
config COMMON_CLK_RK808
tristate "Clock driver for RK805/RK808/RK818"
depends on MFD_RK808
---help---
This driver supports RK805, RK808 and RK818 crystal oscillator clock. These
multi-function devices have two fixed-rate oscillators,
clocked at 32KHz each. Clkout1 is always on, Clkout2 can off
by control register.
config COMMON_CLK_HI655X
tristate "Clock driver for Hi655x"
depends on MFD_HI655X_PMIC || COMPILE_TEST
---help---
This driver supports the hi655x PMIC clock. This
multi-function device has one fixed-rate oscillator, clocked
at 32KHz.
config COMMON_CLK_SCPI
tristate "Clock driver controlled via SCPI interface"
depends on ARM_SCPI_PROTOCOL || COMPILE_TEST
---help---
This driver provides support for clocks that are controlled
by firmware that implements the SCPI interface.
This driver uses SCPI Message Protocol to interact with the
firmware providing all the clock controls.
config COMMON_CLK_SI5351
tristate "Clock driver for SiLabs 5351A/B/C"
depends on I2C
select REGMAP_I2C
select RATIONAL
---help---
This driver supports Silicon Labs 5351A/B/C programmable clock
generators.
config COMMON_CLK_SI514
tristate "Clock driver for SiLabs 514 devices"
depends on I2C
depends on OF
select REGMAP_I2C
help
---help---
This driver supports the Silicon Labs 514 programmable clock
generator.
config COMMON_CLK_SI570
tristate "Clock driver for SiLabs 570 and compatible devices"
depends on I2C
depends on OF
select REGMAP_I2C
help
---help---
This driver supports Silicon Labs 570/571/598/599 programmable
clock generators.
config COMMON_CLK_CDCE706
tristate "Clock driver for TI CDCE706 clock synthesizer"
depends on I2C
select REGMAP_I2C
select RATIONAL
---help---
This driver supports TI CDCE706 programmable 3-PLL clock synthesizer.
config COMMON_CLK_CDCE925
tristate "Clock driver for TI CDCE913/925/937/949 devices"
depends on I2C
depends on OF
select REGMAP_I2C
help
---help---
This driver supports the TI CDCE913/925/937/949 programmable clock
synthesizer. Each chip has different number of PLLs and outputs.
For example, the CDCE925 contains two PLLs with spread-spectrum
clocking support and five output dividers. The driver only supports
the following setup, and uses a fixed setting for the output muxes.
Y1 is derived from the input clock
Y2 and Y3 derive from PLL1
Y4 and Y5 derive from PLL2
Given a target output frequency, the driver will set the PLL and
divider to best approximate the desired output.
config COMMON_CLK_CS2000_CP
tristate "Clock driver for CS2000 Fractional-N Clock Synthesizer & Clock Multiplier"
depends on I2C
help
If you say yes here you get support for the CS2000 clock multiplier.
config COMMON_CLK_GEMINI
bool "Clock driver for Cortina Systems Gemini SoC"
depends on ARCH_GEMINI || COMPILE_TEST
select MFD_SYSCON
select RESET_CONTROLLER
---help---
This driver supports the SoC clocks on the Cortina Systems Gemini
platform, also known as SL3516 or CS3516.
config COMMON_CLK_ASPEED
bool "Clock driver for Aspeed BMC SoCs"
depends on ARCH_ASPEED || COMPILE_TEST
default ARCH_ASPEED
select MFD_SYSCON
select RESET_CONTROLLER
---help---
This driver supports the SoC clocks on the Aspeed BMC platforms.
The G4 and G5 series, including the ast2400 and ast2500, are supported
by this driver.
config COMMON_CLK_S2MPS11
tristate "Clock driver for S2MPS1X/S5M8767 MFD"
depends on MFD_SEC_CORE || COMPILE_TEST
---help---
This driver supports S2MPS11/S2MPS14/S5M8767 crystal oscillator
clock. These multi-function devices have two (S2MPS14) or three
(S2MPS11, S5M8767) fixed-rate oscillators, clocked at 32KHz each.
config CLK_TWL6040
tristate "External McPDM functional clock from twl6040"
depends on TWL6040_CORE
---help---
Enable the external functional clock support on OMAP4+ platforms for
McPDM. McPDM module is using the external bit clock on the McPDM bus
as functional clock.
config COMMON_CLK_AXI_CLKGEN
tristate "AXI clkgen driver"
depends on ARCH_ZYNQ || MICROBLAZE || COMPILE_TEST
help
---help---
Support for the Analog Devices axi-clkgen pcore clock generator for Xilinx
FPGAs. It is commonly used in Analog Devices' reference designs.
config CLK_QORIQ
bool "Clock driver for Freescale QorIQ platforms"
depends on (PPC_E500MC || ARM || ARM64 || COMPILE_TEST) && OF
---help---
This adds the clock driver support for Freescale QorIQ platforms
using common clock framework.
config COMMON_CLK_XGENE
bool "Clock driver for APM XGene SoC"
default y
depends on ARM64 || COMPILE_TEST
---help---
Sypport for the APM X-Gene SoC reference, PLL, and device clocks.
config COMMON_CLK_NXP
def_bool COMMON_CLK && (ARCH_LPC18XX || ARCH_LPC32XX)
select REGMAP_MMIO if ARCH_LPC32XX
select MFD_SYSCON if ARCH_LPC18XX
---help---
Support for clock providers on NXP platforms.
config COMMON_CLK_PALMAS
tristate "Clock driver for TI Palmas devices"
depends on MFD_PALMAS
---help---
This driver supports TI Palmas devices 32KHz output KG and KG_AUDIO
using common clock framework.
config COMMON_CLK_PWM
tristate "Clock driver for PWMs used as clock outputs"
depends on PWM
---help---
Adapter driver so that any PWM output can be (mis)used as clock signal
at 50% duty cycle.
config COMMON_CLK_PXA
def_bool COMMON_CLK && ARCH_PXA
---help---
Support for the Marvell PXA SoC.
config COMMON_CLK_PIC32
def_bool COMMON_CLK && MACH_PIC32
config COMMON_CLK_OXNAS
bool "Clock driver for the OXNAS SoC Family"
depends on ARCH_OXNAS || COMPILE_TEST
select MFD_SYSCON
---help---
Support for the OXNAS SoC Family clocks.
config COMMON_CLK_VC5
tristate "Clock driver for IDT VersaClock 5,6 devices"
depends on I2C
depends on OF
select REGMAP_I2C
help
---help---
This driver supports the IDT VersaClock 5 and VersaClock 6
programmable clock generators.
source "drivers/clk/bcm/Kconfig"
source "drivers/clk/hisilicon/Kconfig"
source "drivers/clk/imgtec/Kconfig"
source "drivers/clk/keystone/Kconfig"
source "drivers/clk/mediatek/Kconfig"
source "drivers/clk/meson/Kconfig"
source "drivers/clk/mvebu/Kconfig"
source "drivers/clk/qcom/Kconfig"
source "drivers/clk/renesas/Kconfig"
source "drivers/clk/samsung/Kconfig"
source "drivers/clk/sprd/Kconfig"
source "drivers/clk/sunxi-ng/Kconfig"
source "drivers/clk/tegra/Kconfig"
source "drivers/clk/ti/Kconfig"
source "drivers/clk/uniphier/Kconfig"
endmenu
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:ns1="urn:oasis:names:tc:xliff:document:1.2">
<string msgid="4600421777120114993" name="abc_action_bar_home_description">"Vai alla home page"</string>
<string msgid="1594238315039666878" name="abc_action_bar_up_description">"Vai in alto"</string>
<string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"Altre opzioni"</string>
<string msgid="4076576682505996667" name="abc_action_mode_done">"Fine"</string>
<string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"Visualizza tutte"</string>
<string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"Scegli un\'applicazione"</string>
<string msgid="121134116657445385" name="abc_capital_off">"OFF"</string>
<string msgid="3405795526292276155" name="abc_capital_on">"ON"</string>
<string msgid="7723749260725869598" name="abc_search_hint">"Cerca…"</string>
<string msgid="3691816814315814921" name="abc_searchview_description_clear">"Cancella query"</string>
<string msgid="2550479030709304392" name="abc_searchview_description_query">"Query di ricerca"</string>
<string msgid="8264924765203268293" name="abc_searchview_description_search">"Cerca"</string>
<string msgid="8928215447528550784" name="abc_searchview_description_submit">"Invia query"</string>
<string msgid="893419373245838918" name="abc_searchview_description_voice">"Ricerca vocale"</string>
<string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"Condividi con"</string>
<string msgid="3300176832234831527" name="abc_shareactionprovider_share_with_application">"Condividi tramite <ns1:g id="APPLICATION_NAME">%s</ns1:g>"</string>
<string msgid="1603543279005712093" name="abc_toolbar_collapse_description">"Comprimi"</string>
<string msgid="146198913615257606" name="search_menu_title">"Ricerca"</string>
<string msgid="7988687684186075107" name="status_bar_notification_info_overflow">"999+"</string>
</resources> | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Converter.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="Logs/converter.log"/>
<appendToFile value="false"/>
<maximumFileSize value="1000KB"/>
<maxSizeRollBackups value="4"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%5level %date (%file:%line) - %message%newline"/>
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingFile"/>
</root>
</log4net>
<applicationSettings>
<Converter.Properties.Settings>
<setting name="SQLServerAddress" serializeAs="String">
<value />
</setting>
<setting name="DatabasePath" serializeAs="String">
<value />
</setting>
</Converter.Properties.Settings>
</applicationSettings>
</configuration> | {
"pile_set_name": "Github"
} |
/**
* 下拉筛选框的选项,统一使用该接口,同时这个作为枚举的复杂类型。
*/
import SelectionOption from "./SelectionOption";
export default interface ColorSelectionOption extends SelectionOption {
color: string,
}
| {
"pile_set_name": "Github"
} |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package gen contains common code for the various code generation tools in the
// text repository. Its usage ensures consistency between tools.
//
// This package defines command line flags that are common to most generation
// tools. The flags allow for specifying specific Unicode and CLDR versions
// in the public Unicode data repository (http://www.unicode.org/Public).
//
// A local Unicode data mirror can be set through the flag -local or the
// environment variable UNICODE_DIR. The former takes precedence. The local
// directory should follow the same structure as the public repository.
//
// IANA data can also optionally be mirrored by putting it in the iana directory
// rooted at the top of the local mirror. Beware, though, that IANA data is not
// versioned. So it is up to the developer to use the right version.
package gen // import "golang.org/x/text/internal/gen"
import (
"bytes"
"flag"
"fmt"
"go/build"
"go/format"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"sync"
"unicode"
"golang.org/x/text/unicode/cldr"
)
var (
url = flag.String("url",
"http://www.unicode.org/Public",
"URL of Unicode database directory")
iana = flag.String("iana",
"http://www.iana.org",
"URL of the IANA repository")
unicodeVersion = flag.String("unicode",
getEnv("UNICODE_VERSION", unicode.Version),
"unicode version to use")
cldrVersion = flag.String("cldr",
getEnv("CLDR_VERSION", cldr.Version),
"cldr version to use")
)
func getEnv(name, def string) string {
if v := os.Getenv(name); v != "" {
return v
}
return def
}
// Init performs common initialization for a gen command. It parses the flags
// and sets up the standard logging parameters.
func Init() {
log.SetPrefix("")
log.SetFlags(log.Lshortfile)
flag.Parse()
}
const header = `// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT.
`
// UnicodeVersion reports the requested Unicode version.
func UnicodeVersion() string {
return *unicodeVersion
}
// CLDRVersion reports the requested CLDR version.
func CLDRVersion() string {
return *cldrVersion
}
var tags = []struct{ version, buildTags string }{
{"10.0.0", "go1.10"},
{"", "!go1.10"},
}
// buildTags reports the build tags used for the current Unicode version.
func buildTags() string {
v := UnicodeVersion()
for _, x := range tags {
// We should do a numeric comparison, but including the collate package
// would create an import cycle. We approximate it by assuming that
// longer version strings are later.
if len(x.version) <= len(v) {
return x.buildTags
}
if len(x.version) == len(v) && x.version <= v {
return x.buildTags
}
}
return tags[0].buildTags
}
// IsLocal reports whether data files are available locally.
func IsLocal() bool {
dir, err := localReadmeFile()
if err != nil {
return false
}
if _, err = os.Stat(dir); err != nil {
return false
}
return true
}
// OpenUCDFile opens the requested UCD file. The file is specified relative to
// the public Unicode root directory. It will call log.Fatal if there are any
// errors.
func OpenUCDFile(file string) io.ReadCloser {
return openUnicode(path.Join(*unicodeVersion, "ucd", file))
}
// OpenCLDRCoreZip opens the CLDR core zip file. It will call log.Fatal if there
// are any errors.
func OpenCLDRCoreZip() io.ReadCloser {
return OpenUnicodeFile("cldr", *cldrVersion, "core.zip")
}
// OpenUnicodeFile opens the requested file of the requested category from the
// root of the Unicode data archive. The file is specified relative to the
// public Unicode root directory. If version is "", it will use the default
// Unicode version. It will call log.Fatal if there are any errors.
func OpenUnicodeFile(category, version, file string) io.ReadCloser {
if version == "" {
version = UnicodeVersion()
}
return openUnicode(path.Join(category, version, file))
}
// OpenIANAFile opens the requested IANA file. The file is specified relative
// to the IANA root, which is typically either http://www.iana.org or the
// iana directory in the local mirror. It will call log.Fatal if there are any
// errors.
func OpenIANAFile(path string) io.ReadCloser {
return Open(*iana, "iana", path)
}
var (
dirMutex sync.Mutex
localDir string
)
const permissions = 0755
func localReadmeFile() (string, error) {
p, err := build.Import("golang.org/x/text", "", build.FindOnly)
if err != nil {
return "", fmt.Errorf("Could not locate package: %v", err)
}
return filepath.Join(p.Dir, "DATA", "README"), nil
}
func getLocalDir() string {
dirMutex.Lock()
defer dirMutex.Unlock()
readme, err := localReadmeFile()
if err != nil {
log.Fatal(err)
}
dir := filepath.Dir(readme)
if _, err := os.Stat(readme); err != nil {
if err := os.MkdirAll(dir, permissions); err != nil {
log.Fatalf("Could not create directory: %v", err)
}
ioutil.WriteFile(readme, []byte(readmeTxt), permissions)
}
return dir
}
const readmeTxt = `Generated by golang.org/x/text/internal/gen. DO NOT EDIT.
This directory contains downloaded files used to generate the various tables
in the golang.org/x/text subrepo.
Note that the language subtag repo (iana/assignments/language-subtag-registry)
and all other times in the iana subdirectory are not versioned and will need
to be periodically manually updated. The easiest way to do this is to remove
the entire iana directory. This is mostly of concern when updating the language
package.
`
// Open opens subdir/path if a local directory is specified and the file exists,
// where subdir is a directory relative to the local root, or fetches it from
// urlRoot/path otherwise. It will call log.Fatal if there are any errors.
func Open(urlRoot, subdir, path string) io.ReadCloser {
file := filepath.Join(getLocalDir(), subdir, filepath.FromSlash(path))
return open(file, urlRoot, path)
}
func openUnicode(path string) io.ReadCloser {
file := filepath.Join(getLocalDir(), filepath.FromSlash(path))
return open(file, *url, path)
}
// TODO: automatically periodically update non-versioned files.
func open(file, urlRoot, path string) io.ReadCloser {
if f, err := os.Open(file); err == nil {
return f
}
r := get(urlRoot, path)
defer r.Close()
b, err := ioutil.ReadAll(r)
if err != nil {
log.Fatalf("Could not download file: %v", err)
}
os.MkdirAll(filepath.Dir(file), permissions)
if err := ioutil.WriteFile(file, b, permissions); err != nil {
log.Fatalf("Could not create file: %v", err)
}
return ioutil.NopCloser(bytes.NewReader(b))
}
func get(root, path string) io.ReadCloser {
url := root + "/" + path
fmt.Printf("Fetching %s...", url)
defer fmt.Println(" done.")
resp, err := http.Get(url)
if err != nil {
log.Fatalf("HTTP GET: %v", err)
}
if resp.StatusCode != 200 {
log.Fatalf("Bad GET status for %q: %q", url, resp.Status)
}
return resp.Body
}
// TODO: use Write*Version in all applicable packages.
// WriteUnicodeVersion writes a constant for the Unicode version from which the
// tables are generated.
func WriteUnicodeVersion(w io.Writer) {
fmt.Fprintf(w, "// UnicodeVersion is the Unicode version from which the tables in this package are derived.\n")
fmt.Fprintf(w, "const UnicodeVersion = %q\n\n", UnicodeVersion())
}
// WriteCLDRVersion writes a constant for the CLDR version from which the
// tables are generated.
func WriteCLDRVersion(w io.Writer) {
fmt.Fprintf(w, "// CLDRVersion is the CLDR version from which the tables in this package are derived.\n")
fmt.Fprintf(w, "const CLDRVersion = %q\n\n", CLDRVersion())
}
// WriteGoFile prepends a standard file comment and package statement to the
// given bytes, applies gofmt, and writes them to a file with the given name.
// It will call log.Fatal if there are any errors.
func WriteGoFile(filename, pkg string, b []byte) {
w, err := os.Create(filename)
if err != nil {
log.Fatalf("Could not create file %s: %v", filename, err)
}
defer w.Close()
if _, err = WriteGo(w, pkg, "", b); err != nil {
log.Fatalf("Error writing file %s: %v", filename, err)
}
}
func insertVersion(filename, version string) string {
suffix := ".go"
if strings.HasSuffix(filename, "_test.go") {
suffix = "_test.go"
}
return fmt.Sprint(filename[:len(filename)-len(suffix)], version, suffix)
}
// WriteVersionedGoFile prepends a standard file comment, adds build tags to
// version the file for the current Unicode version, and package statement to
// the given bytes, applies gofmt, and writes them to a file with the given
// name. It will call log.Fatal if there are any errors.
func WriteVersionedGoFile(filename, pkg string, b []byte) {
tags := buildTags()
if tags != "" {
filename = insertVersion(filename, UnicodeVersion())
}
w, err := os.Create(filename)
if err != nil {
log.Fatalf("Could not create file %s: %v", filename, err)
}
defer w.Close()
if _, err = WriteGo(w, pkg, tags, b); err != nil {
log.Fatalf("Error writing file %s: %v", filename, err)
}
}
// WriteGo prepends a standard file comment and package statement to the given
// bytes, applies gofmt, and writes them to w.
func WriteGo(w io.Writer, pkg, tags string, b []byte) (n int, err error) {
src := []byte(header)
if tags != "" {
src = append(src, fmt.Sprintf("// +build %s\n\n", tags)...)
}
src = append(src, fmt.Sprintf("package %s\n\n", pkg)...)
src = append(src, b...)
formatted, err := format.Source(src)
if err != nil {
// Print the generated code even in case of an error so that the
// returned error can be meaningfully interpreted.
n, _ = w.Write(src)
return n, err
}
return w.Write(formatted)
}
// Repackage rewrites a Go file from belonging to package main to belonging to
// the given package.
func Repackage(inFile, outFile, pkg string) {
src, err := ioutil.ReadFile(inFile)
if err != nil {
log.Fatalf("reading %s: %v", inFile, err)
}
const toDelete = "package main\n\n"
i := bytes.Index(src, []byte(toDelete))
if i < 0 {
log.Fatalf("Could not find %q in %s.", toDelete, inFile)
}
w := &bytes.Buffer{}
w.Write(src[i+len(toDelete):])
WriteGoFile(outFile, pkg, w.Bytes())
}
| {
"pile_set_name": "Github"
} |
<script src="app/view/ppTopov/ppTopov.js"></script>
<script src="app/view/ppTopov/ppTopovOverlay.js"></script> | {
"pile_set_name": "Github"
} |
<?php
/**
* @see https://github.com/phly/keep-a-changelog for the canonical source repository
* @copyright Copyright (c) 2019 Matthew Weier O'Phinney
* @license https://github.com/phly/keep-a-changelog/blob/master/LICENSE.md New BSD License
*/
declare(strict_types=1);
namespace Phly\KeepAChangelog\Provider\Exception;
use Phly\KeepAChangelog\Exception\MissingTagException as BaseException;
use Throwable;
use function sprintf;
class MissingTagException extends BaseException implements ExceptionInterface
{
public static function forPackageOnGithub(string $package, string $version, Throwable $e): self
{
return new self(sprintf(
'When verifying that the tag %s for package %s is present on GitHub,'
. ' no corresponding tag was found',
$version,
$package
), $e->getCode(), $e);
}
public static function forTagOnGithub(string $package, string $version, Throwable $e): self
{
return new self(sprintf(
'When verifying that the tag %s for package %s is present on GitHub,'
. ' an error occurred fetching tag details: %s',
$version,
$package,
$e->getMessage()
), $e->getCode(), $e);
}
public static function forUnverifiedTagOnGithub(string $package, string $version): self
{
return new self(sprintf(
'When verifying that the tag %s for package %s is present on GitHub,'
. ' the tag found was unsigned. Please recreate the tag using the'
. ' -s flag.',
$version,
$package
));
}
}
| {
"pile_set_name": "Github"
} |
package credential
import (
"errors"
"fmt"
"sync"
"koding/kites/kloud/stack"
"koding/klientctl/ctlcli"
"koding/klientctl/endpoint/kloud"
)
var DefaultClient = &Client{}
func init() {
ctlcli.CloseOnExit(DefaultClient)
}
type ListOptions struct {
Team string
Provider string
}
type CreateOptions struct {
Team string
Provider string
Title string
Data []byte
}
// Valid implements the stack.Validator interface.
func (opts *CreateOptions) Valid() error {
if opts == nil {
return errors.New("credential: arguments are missing")
}
if len(opts.Data) == 0 {
return errors.New("credential: data is missing")
}
return nil
}
type Client struct {
Kloud *kloud.Client
once sync.Once // for c.init()
cached stack.Credentials
used map[string]string
describe map[string]*stack.Description
}
func (c *Client) List(opts *ListOptions) (stack.Credentials, error) {
c.init()
var req = &stack.CredentialListRequest{}
var resp stack.CredentialListResponse
if opts != nil {
req = &stack.CredentialListRequest{
Team: opts.Team,
Provider: opts.Provider,
}
}
if err := c.kloud().Call("credential.list", req, &resp); err != nil {
return nil, err
}
c.cache(resp.Credentials)
return resp.Credentials, nil
}
func (c *Client) Create(opts *CreateOptions) (*stack.CredentialItem, error) {
c.init()
if err := opts.Valid(); err != nil {
return nil, err
}
req := &stack.CredentialAddRequest{
Provider: opts.Provider,
Team: opts.Team,
Title: opts.Title,
Data: opts.Data,
}
var resp stack.CredentialAddResponse
if err := c.kloud().Call("credential.add", req, &resp); err != nil {
return nil, err
}
c.cached[opts.Provider] = append(c.cached[opts.Provider], stack.CredentialItem{
Identifier: resp.Identifier,
Title: resp.Title,
Team: opts.Team,
Provider: opts.Provider,
})
if _, ok := c.used[opts.Provider]; !ok {
c.used[opts.Provider] = resp.Identifier
}
return &stack.CredentialItem{
Title: resp.Title,
Team: req.Team,
Identifier: resp.Identifier,
}, nil
}
func (c *Client) Use(identifier string) error {
c.init()
provider, err := c.Provider(identifier)
if err != nil {
return err
}
c.used[provider] = identifier
return nil
}
func (c *Client) Used() map[string]string {
c.init()
return c.used
}
func (c *Client) Provider(identifier string) (provider string, err error) {
c.init()
if cred, ok := c.cached.Find(identifier); ok {
return cred.Provider, nil
}
creds, err := c.List(nil)
if err != nil {
return "", err
}
c.cache(creds)
if cred, ok := c.cached.Find(identifier); ok {
return cred.Provider, nil
}
return "", fmt.Errorf("credential: %q does not exist or is not shared with the user", identifier)
}
func (c *Client) Describe() (stack.Descriptions, error) {
c.init()
var req stack.CredentialDescribeRequest
var resp stack.CredentialDescribeResponse
if err := c.kloud().Call("credential.describe", &req, &resp); err != nil {
return nil, err
}
c.describe = resp.Description
return c.describe, nil
}
func (c *Client) Close() (err error) {
if len(c.cached) != 0 {
err = c.kloud().Cache().ReadWrite().SetValue("credential", c.cached)
}
if len(c.used) != 0 {
err = nonil(err, c.kloud().Cache().ReadWrite().SetValue("credential.used", c.used))
}
if len(c.describe) != 0 {
err = nonil(err, c.kloud().Cache().ReadWrite().SetValue("credential.describe", c.describe))
}
return err
}
func (c *Client) cache(credentials stack.Credentials) {
c.init()
for provider, creds := range credentials {
if len(creds) == 0 {
continue
}
if identifier, ok := c.used[provider]; !ok || identifier == "" {
c.used[provider] = creds[0].Identifier
}
if _, ok := c.cached[provider]; !ok {
c.cached[provider] = creds
continue
}
for _, cred := range creds {
if _, ok := c.cached.Find(cred.Identifier); ok {
continue
}
c.cached[provider] = append(c.cached[provider], cred)
}
}
}
func (c *Client) init() {
c.once.Do(c.readCache)
}
func (c *Client) readCache() {
c.cached = make(stack.Credentials)
c.used = make(map[string]string)
c.describe = make(map[string]*stack.Description)
// Ignoring read error, if it's non-nil then empty cache is going to
// be used instead.
_ = c.kloud().Cache().ReadOnly().GetValue("credential", &c.cached)
_ = c.kloud().Cache().ReadOnly().GetValue("credential.used", &c.used)
_ = c.kloud().Cache().ReadOnly().GetValue("credential.describe", &c.describe)
}
func (c *Client) kloud() *kloud.Client {
if c.Kloud != nil {
return c.Kloud
}
return kloud.DefaultClient
}
func nonil(err ...error) error {
for _, e := range err {
if e != nil {
return e
}
}
return nil
}
func List(opts *ListOptions) (stack.Credentials, error) { return DefaultClient.List(opts) }
func Create(opts *CreateOptions) (*stack.CredentialItem, error) { return DefaultClient.Create(opts) }
func Describe() (stack.Descriptions, error) { return DefaultClient.Describe() }
func Use(identifier string) error { return DefaultClient.Use(identifier) }
func Used() map[string]string { return DefaultClient.Used() }
func Provider(identifier string) (string, error) { return DefaultClient.Provider(identifier) }
| {
"pile_set_name": "Github"
} |
# Python Examples
## Python-2.7 not supported
[](https://pepy.tech/project/pysinric) [](https://pepy.tech/project/pysinric/week) []() []() [](https://github.com/imdhanush)
### Install sinric python package
pip3 install pysinric --user
### Pysinric
[pysinric](https://pypi.org/project/pysinric/)
### Upgrade Pysinric to lastest version
python3 -m pip install pysinric --upgrade --user | {
"pile_set_name": "Github"
} |
import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper';
import { Module } from '@nestjs/core/injector/module';
import { flattenDeep, groupBy, identity, isEmpty, mapValues } from 'lodash';
import { ResolverMetadata } from '../interfaces/resolver-metadata.interface';
export class BaseExplorerService {
getModules(
modulesContainer: Map<string, Module>,
include: Function[],
): Module[] {
if (!include || isEmpty(include)) {
return [...modulesContainer.values()];
}
const whitelisted = this.includeWhitelisted(modulesContainer, include);
return whitelisted;
}
includeWhitelisted(
modulesContainer: Map<string, Module>,
include: Function[],
): Module[] {
const modules = [...modulesContainer.values()];
return modules.filter(({ metatype }) =>
include.some(item => item === metatype),
);
}
flatMap<T = ResolverMetadata>(
modules: Module[],
callback: (instance: InstanceWrapper, moduleRef: Module) => T | T[],
): T[] {
const invokeMap = () => {
return modules.map(moduleRef => {
const providers = [...moduleRef.providers.values()];
return providers.map(wrapper => callback(wrapper, moduleRef));
});
};
return flattenDeep(invokeMap()).filter(identity);
}
groupMetadata(resolvers: ResolverMetadata[]) {
const groupByType = groupBy(
resolvers,
(metadata: ResolverMetadata) => metadata.type,
);
const groupedMetadata = mapValues(
groupByType,
(resolversArr: ResolverMetadata[]) =>
resolversArr.reduce(
(prev, curr) => ({
...prev,
[curr.name]: curr.callback,
}),
{},
),
);
return groupedMetadata;
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2016, Texas Instruments Incorporated
* 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 Texas Instruments Incorporated 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.
*/
/** ============================================================================
* @file UDMACC32XX.h
*
* @brief uDMA driver implementation for CC32XX.
*
* This driver is intended for use only by TI-RTOS drivers that use the uDMA
* peripheral (e.g., SPI and I2S). This driver is mainly used for Power
* management of the UDMA peripheral.
*
* The application should only define the memory for the control table and
* set up the UDMACC32XX_HWAttrs and UDMACC32XX_Config structures.
*
* The UDMACC32XX header file should be included in an application as follows:
* @code
* #include <ti/drivers/dma/UDMACC32XX.h>
* @endcode
*
* ============================================================================
*/
#ifndef ti_drivers_dma_UDMACC32XX__include
#define ti_drivers_dma_UDMACC32XX__include
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdbool.h>
#include <ti/drivers/dpl/HwiP.h>
/*!
* @brief UDMA error function pointer
*/
typedef void (*UDMACC32XX_ErrorFxn)(uintptr_t arg);
/*!
* @brief UDMACC32XX Hardware attributes
*
* This structure contains the base address of the uDMA control
* table, and uDMA error interrupt attributes.
*
* The control table is used by the uDMA controller to store channel
* control structures. The control table can be located anywhere in
* system memory, but must be contiguous and aligned on a 1024-byte boundary.
*
* dmaErrorFxn is the uDMA peripheral's error interrupt handler.
*
* intPriority is priority of the uDMA peripheral's error interrupt, as
* defined by the underlying OS. It is passed unmodified to the
* underlying OS's interrupt handler creation code, so you need to
* refer to the OS documentation for usage. For example, for
* SYS/BIOS applications, refer to the ti.sysbios.family.arm.m3.Hwi
* documentation for SYS/BIOS usage of interrupt priorities. If the
* driver uses the ti.dpl interface instead of making OS
* calls directly, then the HwiP port handles the interrupt priority
* in an OS specific way. In the case of the SYS/BIOS port,
* intPriority is passed unmodified to Hwi_create().
*
* A sample structure is shown below:
* @code
*
* #include <ti/devices/cc32xx/driverlib/udma.h>
*
* #if defined(__TI_COMPILER_VERSION__)
* #pragma DATA_ALIGN(dmaControlTable, 1024)
* #elif defined(__IAR_SYSTEMS_ICC__)
* #pragma data_alignment=1024
* #elif defined(__GNUC__)
* __attribute__ ((aligned (1024)))
* #endif
*
* static tDMAControlTable dmaControlTable[64];
*
* #include <ti/drivers/dma/UDMACC32XX.h>
*
* UDMACC32XX_Object udmaCC32XXObject;
*
* const UDMACC32XX_HWAttrs udmaCC32XXHWAttrs = {
* .controlBaseAddr = (void *)dmaControlTable,
* .dmaErrorFxn = UDMACC32XX_errorFxn,
* .intNum = INT_UDMAERR,
* .intPriority = (~0)
* };
* @endcode
*
*/
typedef struct UDMACC32XX_HWAttrs {
void *controlBaseAddr; /*!< uDMA control registers base address */
UDMACC32XX_ErrorFxn dmaErrorFxn; /*!< uDMA error interrupt handler */
uint8_t intNum; /*!< uDMA error interrupt number */
uint8_t intPriority; /*!< uDMA error interrupt priority. */
} UDMACC32XX_HWAttrs;
/*!
* @brief UDMACC32XX Global configuration
*
* The UDMACC32XX_Config structure contains pointers used by the UDMACC32XX
* driver.
*
* This structure needs to be defined before calling UDMACC32XX_init() and
* it must not be changed thereafter.
*/
typedef struct UDMACC32XX_Config {
void *object; /*!< Pointer to UDMACC32XX object */
void const *hwAttrs; /*!< Pointer to hardware attributes */
} UDMACC32XX_Config;
/*!
* @brief A handle that is returned from a UDMACC32XX_open() call.
*/
typedef struct UDMACC32XX_Config *UDMACC32XX_Handle;
/*!
* @brief UDMACC32XX object
*
* The application must not access any member variables of this structure!
*/
typedef struct UDMACC32XX_Object {
bool isOpen; /* Flag for open/close status */
HwiP_Handle hwiHandle; /* DMA error Hwi */
} UDMACC32XX_Object;
/*!
* @brief Function to close the DMA driver.
*
* This function releases Power dependency on UDMA that was previously
* set with a call to UDMACC32XX_open(). If there is only one outstanding
* UDMACC32XX_open() call (i.e. all but one UDMACC32XX_open() calls have
* been matched by a corresponding call to UDMACC32XX_close()), this
* function will disable the UDMA.
*
* @pre UDMACC32XX_open() has to be called first.
* Calling context: Task
*
* @param handle A UDMACC32XX_Handle returned from UDMACC32XX_open()
*
* @return none
*
* @sa UDMACC32XX_open
*/
extern void UDMACC32XX_close(UDMACC32XX_Handle handle);
/*!
* @brief Function to initialize the CC32XX DMA driver
*
* The function will set the isOpen flag to false, and should be called prior
* to opening the DMA driver.
*
* @return none
*
* @sa UDMACC32XX_open()
*/
extern void UDMACC32XX_init();
/*!
* @brief Function to initialize the CC32XX DMA peripheral
*
* UDMACC32XX_open() can be called multiple times. Each time the
* function is called, it will set a dependency on the peripheral and
* enable the clock. The Power dependency count on the UDMA will be
* equal to the number of outstanding calls to UDMACC32XX_open().
* Calling UDMACC32XX_close() will decrement the Power dependency count,
* and the last call to UDMACC32XX_close() will disable the UDMA.
*
* @pre UDMACC32XX_init() has to be called first.
* Calling context: Task
*
* @return UDMACC32XX_Handle on success or NULL if an error has occurred.
*
* @sa UDMACC32XX_close()
*/
extern UDMACC32XX_Handle UDMACC32XX_open();
#ifdef __cplusplus
}
#endif
#endif /* ti_drivers_dma_UDMACC32XX__include */
| {
"pile_set_name": "Github"
} |
<?php
namespace Analogue\ORM\Relationships;
class HasMany extends HasOneOrMany
{
/**
* Lazy-Load the results of the relationship.
*
* @param $relation
*
* @return mixed
*/
public function getResults($relation)
{
$results = $this->query->get();
$this->cacheRelation($results, $relation);
return $results;
}
/**
* Match the eagerly loaded results to their parents.
*
* @param array $results
* @param string $relation
*
* @return array
*/
public function match(array $results, $relation)
{
return $this->matchMany($results, $relation);
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ArtifactsWorkspaceSettings">
<artifacts-to-build>
<artifact name="loginProject:war exploded" />
</artifacts-to-build>
</component>
<component name="ChangeListManager">
<list default="true" id="206d8ed4-c136-4a6f-bc5a-f623c851a0ec" name="Default" comment="" />
<ignored path="$PROJECT_DIR$/out/" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300" />
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Interface" />
<option value="Class" />
<option value="Jsp File" />
</list>
</option>
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/src/com/mashibing/PageServlet.java" />
<option value="$PROJECT_DIR$/src/com/mashibing/LoginServlet.java" />
<option value="$PROJECT_DIR$/README" />
<option value="$PROJECT_DIR$/src/com/mashibing/po/User.java" />
<option value="$PROJECT_DIR$/src/com/mashibing/control/Test.java" />
<option value="$PROJECT_DIR$/src/com/mashibing/control/Servlet.java" />
<option value="$PROJECT_DIR$/src/com/mashibing/service/UserService.java" />
<option value="$PROJECT_DIR$/src/com/mashibing/dao/UserDao.java" />
<option value="$PROJECT_DIR$/src/com/mashibing/entity/User.java" />
<option value="$PROJECT_DIR$/src/com/mashibing/service/impl/UserServiceImpl.java" />
<option value="$PROJECT_DIR$/src/com/mashibing/dao/impl/UserDaoImpl.java" />
<option value="$PROJECT_DIR$/src/com/mashibing/control/PageServlet.java" />
<option value="$PROJECT_DIR$/web/WEB-INF/web.xml" />
<option value="$PROJECT_DIR$/src/com/mashibing/control/HelloServlet.java" />
<option value="$PROJECT_DIR$/src/com/mashibing/control/LoginServlet.java" />
<option value="$PROJECT_DIR$/web/1.jsp" />
</list>
</option>
</component>
<component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsGulpfileManager">
<detection-done>true</detection-done>
<sorting>DEFINITION_ORDER</sorting>
</component>
<component name="LogFilters">
<option name="FILTER_ERRORS" value="false" />
<option name="FILTER_WARNINGS" value="false" />
<option name="FILTER_INFO" value="true" />
<option name="FILTER_DEBUG" value="true" />
<option name="CUSTOM_FILTER" />
</component>
<component name="ProjectFrameBounds" extendedState="7">
<option name="x" value="535" />
<option name="y" value="17" />
<option name="width" value="1400" />
<option name="height" value="786" />
</component>
<component name="ProjectView">
<navigator proportions="" version="1">
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="PackagesPane" />
<pane id="AndroidView" />
<pane id="Scope" />
<pane id="ProjectPane">
<subPane>
<expand>
<path>
<item name="loginProject" type="b2602c69:ProjectViewProjectNode" />
<item name="loginProject" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="loginProject" type="b2602c69:ProjectViewProjectNode" />
<item name="loginProject" type="462c0819:PsiDirectoryNode" />
<item name="out" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="loginProject" type="b2602c69:ProjectViewProjectNode" />
<item name="loginProject" type="462c0819:PsiDirectoryNode" />
<item name="out" type="462c0819:PsiDirectoryNode" />
<item name="artifacts" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="loginProject" type="b2602c69:ProjectViewProjectNode" />
<item name="loginProject" type="462c0819:PsiDirectoryNode" />
<item name="out" type="462c0819:PsiDirectoryNode" />
<item name="artifacts" type="462c0819:PsiDirectoryNode" />
<item name="loginProject_war_exploded" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="loginProject" type="b2602c69:ProjectViewProjectNode" />
<item name="loginProject" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="loginProject" type="b2602c69:ProjectViewProjectNode" />
<item name="loginProject" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
<item name="mashibing" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="loginProject" type="b2602c69:ProjectViewProjectNode" />
<item name="loginProject" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
<item name="mashibing" type="462c0819:PsiDirectoryNode" />
<item name="control" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="loginProject" type="b2602c69:ProjectViewProjectNode" />
<item name="loginProject" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
<item name="mashibing" type="462c0819:PsiDirectoryNode" />
<item name="entity" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="loginProject" type="b2602c69:ProjectViewProjectNode" />
<item name="loginProject" type="462c0819:PsiDirectoryNode" />
<item name="web" type="462c0819:PsiDirectoryNode" />
</path>
</expand>
<select />
</subPane>
</pane>
</panes>
</component>
<component name="PropertiesComponent">
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="aspect.path.notification.shown" value="true" />
<property name="last_opened_file_path" value="E:/lib/mysql-connector-java-5.1.32-bin.jar!/" />
<property name="nodejs_interpreter_path.stuck_in_default_project" value="undefined stuck path" />
<property name="nodejs_npm_path_reset_for_default_project" value="true" />
<property name="project.structure.last.edited" value="Problems" />
<property name="project.structure.proportion" value="0.15" />
<property name="project.structure.side.proportion" value="0.2" />
<property name="settings.editor.selected.configurable" value="project.propVCSSupport.Mappings" />
</component>
<component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS">
<recent name="E:\idea_workspace\loginProject\web\WEB-INF\lib" />
<recent name="E:\idea_workspace\loginProject\lib" />
</key>
<key name="MoveFile.RECENT_KEYS">
<recent name="E:\idea_workspace\loginProject\web\WEB-INF" />
</key>
</component>
<component name="RunDashboard">
<option name="ruleStates">
<list>
<RuleState>
<option name="name" value="ConfigurationTypeDashboardGroupingRule" />
</RuleState>
<RuleState>
<option name="name" value="StatusDashboardGroupingRule" />
</RuleState>
</list>
</option>
</component>
<component name="RunManager">
<configuration default="true" type="Application" factoryName="Application">
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
</configuration>
<configuration default="true" type="JUnit" factoryName="JUnit">
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" value="-ea" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" value="%MODULE_WORKING_DIR%" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<patterns />
</configuration>
<configuration default="true" type="TestNG" factoryName="TestNG">
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="SUITE_NAME" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="GROUP_NAME" />
<option name="TEST_OBJECT" value="CLASS" />
<option name="VM_PARAMETERS" value="-ea" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" value="%MODULE_WORKING_DIR%" />
<option name="OUTPUT_DIRECTORY" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<option name="USE_DEFAULT_REPORTERS" value="false" />
<option name="PROPERTIES_FILE" />
<properties />
<listeners />
</configuration>
<configuration name="loginproject" type="#com.intellij.j2ee.web.tomcat.TomcatRunConfigurationFactory" factoryName="Local" APPLICATION_SERVER_NAME="Tomcat 7.0.56" ALTERNATIVE_JRE_ENABLED="false">
<option name="UPDATE_ON_FRAME_DEACTIVATION" value="true" />
<option name="UPDATE_CLASSES_ON_FRAME_DEACTIVATION" value="true" />
<option name="UPDATING_POLICY" value="restart-server" />
<deployment>
<artifact name="loginProject:war exploded">
<settings>
<option name="CONTEXT_PATH" value="/loginproject" />
</settings>
</artifact>
</deployment>
<server-settings>
<option name="BASE_DIRECTORY_NAME" value="Unnamed_loginProject" />
</server-settings>
<predefined_log_file id="Tomcat" enabled="true" />
<predefined_log_file id="Tomcat Catalina" enabled="true" />
<predefined_log_file id="Tomcat Manager" enabled="false" />
<predefined_log_file id="Tomcat Host Manager" enabled="false" />
<predefined_log_file id="Tomcat Localhost Access" enabled="false" />
<RunnerSettings RunnerId="Debug">
<option name="DEBUG_PORT" value="53197" />
</RunnerSettings>
<ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Cover">
<option name="USE_ENV_VARIABLES" value="true" />
<STARTUP>
<option name="USE_DEFAULT" value="true" />
<option name="SCRIPT" value="" />
<option name="VM_PARAMETERS" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
</STARTUP>
<SHUTDOWN>
<option name="USE_DEFAULT" value="true" />
<option name="SCRIPT" value="" />
<option name="VM_PARAMETERS" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
</SHUTDOWN>
</ConfigurationWrapper>
<ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Debug">
<option name="USE_ENV_VARIABLES" value="true" />
<STARTUP>
<option name="USE_DEFAULT" value="true" />
<option name="SCRIPT" value="" />
<option name="VM_PARAMETERS" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
</STARTUP>
<SHUTDOWN>
<option name="USE_DEFAULT" value="true" />
<option name="SCRIPT" value="" />
<option name="VM_PARAMETERS" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
</SHUTDOWN>
</ConfigurationWrapper>
<ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Run">
<option name="USE_ENV_VARIABLES" value="true" />
<STARTUP>
<option name="USE_DEFAULT" value="true" />
<option name="SCRIPT" value="" />
<option name="VM_PARAMETERS" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
</STARTUP>
<SHUTDOWN>
<option name="USE_DEFAULT" value="true" />
<option name="SCRIPT" value="" />
<option name="VM_PARAMETERS" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
</SHUTDOWN>
</ConfigurationWrapper>
<method>
<option name="BuildArtifacts" enabled="true">
<artifact name="loginProject:war exploded" />
</option>
</method>
</configuration>
</component>
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="206d8ed4-c136-4a6f-bc5a-f623c851a0ec" name="Default" comment="" />
<created>1561384344466</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1561384344466</updated>
<workItem from="1561384350874" duration="4162000" />
<workItem from="1561443390073" duration="1217000" />
<workItem from="1561445953068" duration="3619000" />
<workItem from="1561513884621" duration="1673000" />
<workItem from="1561518337324" duration="50000" />
<workItem from="1561518392741" duration="4223000" />
<workItem from="1561525445014" duration="843000" />
<workItem from="1561526457792" duration="6360000" />
<workItem from="1561684666037" duration="10000" />
<workItem from="1561811524842" duration="3978000" />
<workItem from="1561857909454" duration="459000" />
<workItem from="1561859740557" duration="1971000" />
</task>
<servers />
</component>
<component name="TimeTrackingManager">
<option name="totallyTimeSpent" value="28565000" />
</component>
<component name="ToolWindowManager">
<frame x="-8" y="-8" width="1936" height="1056" extended-state="7" />
<layout>
<window_info anchor="right" id="Palette" order="3" />
<window_info anchor="bottom" id="Event Log" order="7" side_tool="true" />
<window_info anchor="bottom" id="Application Servers" order="7" weight="0.32897604" />
<window_info anchor="right" id="Maven Projects" order="3" />
<window_info anchor="bottom" id="Database Changes" order="7" show_stripe_button="false" />
<window_info id="Capture Tool" order="2" />
<window_info id="Designer" order="2" />
<window_info anchor="right" id="Database" order="3" />
<window_info id="Structure" order="1" side_tool="true" weight="0.25" />
<window_info anchor="right" id="Ant Build" order="1" weight="0.25" />
<window_info id="UI Designer" order="2" />
<window_info anchor="bottom" id="Debug" order="3" weight="0.4" />
<window_info anchor="bottom" id="TODO" order="6" />
<window_info anchor="bottom" id="Messages" order="7" weight="0.32897604" />
<window_info anchor="right" id="Palette	" order="3" />
<window_info id="Image Layers" order="2" />
<window_info anchor="bottom" id="Java Enterprise" order="7" />
<window_info anchor="right" id="Capture Analysis" order="3" />
<window_info anchor="bottom" id="Version Control" order="7" show_stripe_button="false" />
<window_info anchor="bottom" id="Run" order="2" weight="0.42701524" />
<window_info anchor="bottom" id="Terminal" order="7" />
<window_info active="true" content_ui="combo" id="Project" order="0" sideWeight="0.8616558" visible="true" weight="0.114605546" />
<window_info id="Web" order="2" sideWeight="0.13834423" side_tool="true" weight="0.15671642" />
<window_info anchor="right" id="Theme Preview" order="3" />
<window_info id="Favorites" order="2" side_tool="true" />
<window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
<window_info anchor="right" id="Commander" internal_type="SLIDING" order="0" type="SLIDING" weight="0.4" />
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
<window_info anchor="bottom" id="Message" order="0" />
<window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" />
<window_info anchor="bottom" id="Find" order="1" />
</layout>
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="1" />
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/web/WEB-INF/web.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="850">
<caret line="34" column="22" selection-start-line="6" selection-start-column="3" selection-end-line="34" selection-end-column="22" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/PageServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="475">
<caret line="19" column="16" selection-start-line="19" selection-start-column="16" selection-end-line="19" selection-end-column="16" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/web/WEB-INF/web.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="850">
<caret line="34" column="22" selection-start-line="6" selection-start-column="3" selection-end-line="34" selection-end-column="22" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/PageServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="350">
<caret line="19" column="16" selection-start-line="19" selection-start-column="16" selection-end-line="19" selection-end-column="16" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/LoginServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="650">
<caret line="35" column="20" selection-start-line="35" selection-start-column="20" selection-end-line="35" selection-end-column="20" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/HelloServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="425">
<caret line="22" column="28" selection-start-line="22" selection-start-column="28" selection-end-line="22" selection-end-column="28" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/web/WEB-INF/web.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="850">
<caret line="34" column="22" lean-forward="true" selection-start-line="6" selection-start-column="2" selection-end-line="34" selection-end-column="22" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/PageServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="400">
<caret line="21" column="28" selection-start-line="21" selection-start-column="28" selection-end-line="21" selection-end-column="28" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/LoginServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="350">
<caret line="22" column="49" selection-start-line="22" selection-start-column="49" selection-end-line="22" selection-end-column="49" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/PageServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="475">
<caret line="24" column="49" lean-forward="true" selection-start-line="24" selection-start-column="49" selection-end-line="24" selection-end-column="49" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/LoginServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="375">
<caret line="23" column="33" lean-forward="true" selection-start-line="23" selection-start-column="33" selection-end-line="23" selection-end-column="33" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/web/WEB-INF/web.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="375">
<caret line="15" column="10" lean-forward="true" selection-start-line="15" selection-start-column="10" selection-end-line="15" selection-end-column="10" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/PageServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="625">
<caret line="25" column="52" selection-start-line="25" selection-start-column="50" selection-end-line="25" selection-end-column="52" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/web/WEB-INF/web.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="550">
<caret line="22" column="27" selection-start-line="22" selection-start-column="27" selection-end-line="22" selection-end-column="27" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/PageServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="625">
<caret line="25" column="52" lean-forward="true" selection-start-line="25" selection-start-column="50" selection-end-line="25" selection-end-column="52" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/entity/User.java" />
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/LoginServlet.java" />
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/Servlet.java" />
<entry file="file://$PROJECT_DIR$/web/WEB-INF/web.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="100">
<caret line="4" column="23" lean-forward="true" selection-start-line="4" selection-start-column="23" selection-end-line="4" selection-end-column="23" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/README">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="275">
<caret line="11" column="11" selection-start-line="11" selection-start-column="4" selection-end-line="11" selection-end-column="11" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/web/WEB-INF/web.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="450">
<caret line="18" column="42" selection-start-line="18" selection-start-column="42" selection-end-line="18" selection-end-column="42" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/LoginServlet.java" />
<entry file="file://$PROJECT_DIR$/src/com/mashibing/service/UserService.java" />
<entry file="file://$PROJECT_DIR$/src/com/mashibing/service/impl/UserServiceImpl.java" />
<entry file="file://$PROJECT_DIR$/src/com/mashibing/dao/UserDao.java" />
<entry file="file://$PROJECT_DIR$/src/com/mashibing/po/User.java" />
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/PageServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="325">
<caret line="18" column="20" lean-forward="true" selection-start-line="18" selection-start-column="20" selection-end-line="18" selection-end-column="20" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/dao/impl/UserDaoImpl.java" />
<entry file="file://$PROJECT_DIR$/README">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="275">
<caret line="11" column="11" selection-start-line="11" selection-start-column="4" selection-end-line="11" selection-end-column="11" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/po/User.java" />
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/Test.java" />
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/Servlet.java" />
<entry file="file://$PROJECT_DIR$/src/com/mashibing/service/UserService.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="150">
<caret line="6" column="27" selection-start-line="6" selection-start-column="27" selection-end-line="6" selection-end-column="27" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/dao/UserDao.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="150">
<caret line="6" column="28" selection-start-line="6" selection-start-column="28" selection-end-line="6" selection-end-column="28" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/entity/User.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="343">
<caret line="16" column="15" selection-start-line="13" selection-start-column="10" selection-end-line="16" selection-end-column="15" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/service/impl/UserServiceImpl.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="225">
<caret line="9" column="40" selection-start-line="9" selection-start-column="40" selection-end-line="9" selection-end-column="40" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/dao/impl/UserDaoImpl.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="543">
<caret line="28" column="45" lean-forward="true" selection-start-line="28" selection-start-column="45" selection-end-line="28" selection-end-column="45" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/HelloServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="425">
<caret line="22" column="28" selection-start-line="22" selection-start-column="28" selection-end-line="22" selection-end-column="28" />
</state>
</provider>
</entry>
<entry file="jar://C:/apache-tomcat-7.0.56/lib/servlet-api.jar!/javax/servlet/ServletRequest.class">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="297">
<caret line="21" column="9" selection-start-line="21" selection-start-column="9" selection-end-line="21" selection-end-column="9" />
</state>
</provider>
</entry>
<entry file="jar://C:/apache-tomcat-7.0.56/lib/servlet-api.jar!/javax/servlet/http/HttpServletRequest.class">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="280">
<caret line="60" column="16" selection-start-line="60" selection-start-column="16" selection-end-line="60" selection-end-column="16" />
</state>
</provider>
</entry>
<entry file="jar://C:/apache-tomcat-7.0.56/lib/servlet-api.jar!/javax/servlet/http/HttpServletRequestWrapper.class">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="280">
<caret line="103" column="23" selection-start-line="103" selection-start-column="23" selection-end-line="103" selection-end-column="23" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/LoginServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="350">
<caret line="23" column="16" lean-forward="true" selection-start-line="23" selection-start-column="16" selection-end-line="23" selection-end-column="16" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/web/1.jsp">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="325">
<caret line="13" column="12" selection-start-line="13" selection-start-column="12" selection-end-line="13" selection-end-column="12" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/mashibing/control/PageServlet.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="318">
<caret line="21" column="20" lean-forward="true" selection-start-line="21" selection-start-column="20" selection-end-line="21" selection-end-column="20" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/web/WEB-INF/web.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="176">
<caret line="24" column="41" lean-forward="true" selection-start-line="24" selection-start-column="41" selection-end-line="24" selection-end-column="41" />
</state>
</provider>
</entry>
</component>
<component name="masterDetails">
<states>
<state key="ArtifactsStructureConfigurable.UI">
<settings>
<artifact-editor />
<last-edited>loginProject:war exploded</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
<option value="0.5" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
<state key="FacetStructureConfigurable.UI">
<settings>
<last-edited>Web</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
<state key="GlobalLibrariesConfigurable.UI">
<settings>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
<state key="JdkListConfigurable.UI">
<settings>
<last-edited>1.8</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
<state key="ModuleStructureConfigurable.UI">
<settings>
<last-edited>loginProject</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
<state key="ProjectJDKs.UI">
<settings>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
<state key="ProjectLibrariesConfigurable.UI">
<settings>
<last-edited>mysql-connector-java-5.1.32-bin</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project> | {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License") + you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openmeetings.service.quartz.scheduler;
import static org.apache.openmeetings.core.rss.LoadAtomRssFeed.getFeedConnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.apache.openmeetings.db.util.XmlHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.openjson.JSONArray;
import com.github.openjson.JSONObject;
public class AtomReader {
private static final Logger log = LoggerFactory.getLogger(AtomReader.class);
private static final String ATTR_CONTENT = "content";
private static final String ATTR_PUBLISHED = "published";
private static final int MAX_ITEM_COUNT = 5;
private static final Map<String, Spec> specs = new HashMap<>();
private static final XMLInputFactory inputFactory = XmlHelper.createInputFactory();
static {
add("item")
.add(new Field("title"))
.add(new Field("link"))
.add(new Field("description", ATTR_CONTENT, true))
.add(new Field("pubDate", ATTR_PUBLISHED))
.add(new Field("author"));
add("entry")
.add(new Field("title"))
.add(new Field("link", "link", "href", false))
.add(new Field(ATTR_CONTENT, ATTR_CONTENT, true))
.add(new Field("updated", ATTR_PUBLISHED))
.add(new Field(ATTR_PUBLISHED))
.add(new Field("author"));
}
private AtomReader() {
// denied
}
private static Spec add(String name) {
Spec s = new Spec(name);
specs.put(name, s);
return s;
}
public static void load(String url, JSONArray feed) {
HttpURLConnection con = null;
try {
con = getFeedConnection(url);
try (InputStream is = con.getInputStream()) {
XMLEventReader reader = inputFactory.createXMLEventReader(is);
int i = 0;
JSONObject obj = null;
StringBuilder val = null;
Spec spec = null;
Field f = null;
while (reader.hasNext()) {
XMLEvent evt = reader.nextEvent();
if (obj == null && evt.isStartElement()) {
StartElement start = (StartElement)evt;
String name = start.getName().getLocalPart();
if (specs.containsKey(name)) {
spec = specs.get(name);
obj = new JSONObject();
i++;
}
} else if (obj != null) {
if (evt.isStartElement()) {
StartElement start = (StartElement)evt;
String name = start.getName().getLocalPart();
if (spec.contains(name)) {
f = spec.get(name);
val = new StringBuilder();
if (f.getAttr() != null) {
Attribute a = start.getAttributeByName(new QName(f.getAttr()));
if (a != null) {
val.append(a.getValue());
}
}
}
} else if (f != null && evt.isCharacters()) {
val.append(((Characters)evt).getData());
} else if (f != null && evt.isEndElement() && f.getName().equals(((EndElement)evt).getName().getLocalPart())) {
if (!obj.has(f.getAlias())) {
obj.put(f.getAlias(), val.toString());
}
f = null;
} else if (evt.isEndElement() && spec.getName().equals(((EndElement)evt).getName().getLocalPart())) {
feed.put(obj);
obj = null;
}
}
if (i > MAX_ITEM_COUNT) {
break;
}
}
}
} catch (IOException|XMLStreamException e) {
log.error("Unexpected error while getting RSS", e);
} finally {
if (con != null) {
con.disconnect();
}
}
}
public static class Spec {
private final String name;
private final Map<String, Field> fields = new LinkedHashMap<>();
public Spec(final String name) {
this.name = name;
}
public Spec add(Field f) {
fields.put(f.getName(), f);
return this;
}
public String getName() {
return name;
}
public boolean contains(String f) {
return fields.containsKey(f);
}
public Field get(String f) {
return fields.get(f);
}
}
public static class Field {
private final String name;
private final String alias;
private final String attr;
private final boolean xml;
public Field(String name) {
this(name, name);
}
public Field(String name, String alias) {
this(name, alias, false);
}
public Field(String name, String alias, boolean xml) {
this(name, alias, null, xml);
}
public Field(String name, String alias, String attr, boolean xml) {
this.name= name;
this.alias = alias;
this.attr = attr;
this.xml = xml;
}
public String getName() {
return name;
}
public String getAlias() {
return alias;
}
public String getAttr() {
return attr;
}
public boolean isXml() {
return xml;
}
}
}
| {
"pile_set_name": "Github"
} |
1 spanish; castilian x-vnd.Haiku-Bluetooth 3550394259
Positioning DeviceClass Posicionamiento
Controller DeviceClass Controlador
Common ISDN access DeviceClass Acceso común de ISDN
Unknown (reserved) minor device class DeviceClass Clase de dispositivo menor desconocida (reservada)
Uncategorized DeviceClass Sin categoría
Keyboard DeviceClass Teclado
Smart phone DeviceClass Teléfono inteligente
VCR DeviceClass VCR
Cellular DeviceClass Celular
Audio DeviceClass Audio
Audio/Video DeviceClass Audio/Vídeo
Car audio DeviceClass Audio de coche
Major class: DeviceClass Clase mayor:
HiFi audio device DeviceClass Dispositivo de audio HiFi
Microphone DeviceClass Micrófono
Capturing DeviceClass Capturando
Jacket DeviceClass Conexión
50-67% utilized DeviceClass 50-67% utilizada
Headphones DeviceClass Audífonos
Imaging DeviceClass Imágenes
Device conforms to the headset profile DeviceClass El dispositivo cumple con el perfil auricular
Remote control DeviceClass Control remoto
Fully available DeviceClass Plenamente disponible
#CommandFailed#Not Valid name RemoteDevice #ComandoFalló#nombre no válido
Server DeviceClass Servidor
No service available DeviceClass Sin servicio disponible
Printer DeviceClass Impresora
Card reader DeviceClass Lector de tarjetas
Wired modem or voice gateway DeviceClass Módem con conexión de cable o gateway de voz
#ServerNotReady#Not Valid name RemoteDevice #ServidorNoListo#Nombre no válido
#NoOwnerError#Not Valid name RemoteDevice #Errorsindueño#Nombre no válido
Camcorder DeviceClass Videocámara
#NotCompletedRequest#Not Valid name RemoteDevice #SolicitudNoCompleta#Nombre no válido
17-33% utilized DeviceClass 17-33% utilizada
Desktop workstation DeviceClass Estación de trabajo de escritorio
Unspecified DeviceClass Sin especificar
Miscellaneous DeviceClass Diverso
Robot DeviceClass Robot
Vehicle DeviceClass Vehículo
LAN access DeviceClass Acceso a LAN
Glasses DeviceClass Lentes
Phone DeviceClass Teléfono
Laptop DeviceClass Ordenador portátil
67-83% utilized DeviceClass 67-83% utilizada
Cordless DeviceClass Sin cable
Invalid device class!\n DeviceClass Clase de dispositivo inválida\n
Minor class: DeviceClass Clase menor:
Doll/Action figure DeviceClass Muñeco/Figura de Acción
Not implemented RemoteDevice Sin implementar
33-50% utilized DeviceClass 33-50% utilizada
Gaming/Toy DeviceClass Juego/Juguete
Video camera DeviceClass Videocámara
Handheld DeviceClass Computadora de mano
Service classes: DeviceClass Clases de servicios
Loudspeaker DeviceClass Altavoz
83-99% utilized DeviceClass 83-99% utilizada
SIM card reader DeviceClass Lector de tarjetas SIM
Computer DeviceClass Computadora
Scanner DeviceClass Escáner
Wearable DeviceClass A wearable computer Utilizable
Display DeviceClass Visualización
Gamepad DeviceClass Palanca de control
Video monitor DeviceClass Monitor de vídeo
Palm DeviceClass A palm-held device Palm
Joystick DeviceClass Palanca de control
Networking DeviceClass Redes
Telephony DeviceClass Telefonía
Game DeviceClass Juego
Video display and loudspeaker DeviceClass Pantalla de vídeo y altavoz
Wrist watch DeviceClass Reloj de pulsera
Sensing device DeviceClass Dispositivo de dirección
Pointing device DeviceClass Dispositivo apuntador
(reserved) DeviceClass (reservado)
Rendering DeviceClass Renderizado
Information DeviceClass Información
Helmet DeviceClass Casco
Pager DeviceClass A small radio device to receive short text messages Buscapersonas
Hands-free DeviceClass Manos libres
Digitizer tablet DeviceClass Tableta digitalizadora
Portable audio DeviceClass Audio portátil
Camera DeviceClass Cámara
1-17% utilized DeviceClass 1-17% utilizada
Combo keyboard/pointing device DeviceClass Combinación teclado/dispositivo apuntador
Video conferencing DeviceClass Videoconferencia
Peripheral DeviceClass Periférico
Object transfer DeviceClass Transferencia de objeto
Set-top box DeviceClass Modulo de conexión
| {
"pile_set_name": "Github"
} |
' TEST_MODE : COMPILE_ONLY_FAIL
type T
as integer i
private:
declare constructor( )
end type
constructor T( )
end constructor
dim as T x(0 to 1)
| {
"pile_set_name": "Github"
} |
#
# Copyright 2014 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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.
#
# translate 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, see <http://www.gnu.org/licenses/>.
"""Takes an IDML template file and a PO file containing translations of
strings in the IDML template. It creates a new IDML file using the translations
of the PO file.
"""
from io import BytesIO
from zipfile import ZIP_DEFLATED, ZipFile
import lxml.etree as etree
from translate.convert import convert
from translate.storage import factory
from translate.storage.idml import (INLINE_ELEMENTS, NO_TRANSLATE_ELEMENTS,
copy_idml, open_idml)
from translate.storage.xml_extract.extract import (ParseState,
process_idml_translatable)
from translate.storage.xml_extract.generate import (apply_translations,
replace_dom_text)
from translate.storage.xml_extract.unit_tree import XPathTree, build_unit_tree
def translate_idml(template, input_file, translatable_files):
def load_dom_trees(template):
"""Return a dict with translatable files in the template IDML package.
The keys are the filenames inside the IDML package, and the values are
the etrees for each of those translatable files.
"""
idml_data = open_idml(template)
parser = etree.XMLParser(strip_cdata=False, resolve_entities=False)
return dict((filename, etree.fromstring(data, parser).getroottree())
for filename, data in idml_data.items())
def load_unit_tree(input_file):
"""Return a dict with the translations grouped by files IDML package.
The keys are the filenames inside the template IDML package, and the
values are XPathTree instances for each of those files.
"""
store = factory.getobject(input_file)
def extract_unit_tree(filename, root_dom_element_name):
"""Find the subtree in 'tree' which corresponds to the data in XML
file 'filename'
"""
tree = build_unit_tree(store, filename)
try:
file_tree = tree.children[root_dom_element_name, 0]
except KeyError:
file_tree = XPathTree()
return (filename, file_tree)
return dict(extract_unit_tree(filename, 'idPkg:Story')
for filename in translatable_files)
def translate_dom_trees(unit_trees, dom_trees):
"""Return a dict with the translated files for the IDML package.
The keys are the filenames for the translatable files inside the
template IDML package, and the values are etree ElementTree instances
for each of those files.
"""
def get_po_doms(unit):
"""Return a tuple with unit source and target DOM objects.
This method is method is meant to provide a way to retrieve the DOM
objects for the unit source and target for PO stores.
Since POunit doesn't have any source_dom nor target_dom attributes,
it is necessary to craft those objects.
"""
def add_node_content(string, node):
"""Append the translatable content to the node.
The string is going to have XLIFF placeables, so we have to
parse it as XML in order to get the right nodes to append to
the node.
"""
# Add a wrapper "whatever" tag to avoid problems when parsing
# several sibling tags at the root level.
fake_string = "<whatever>" + string + "</whatever>"
# Copy the children to the XLIFF unit's source or target node.
fake_node = etree.fromstring(fake_string)
node.extend(fake_node.getchildren())
return node
source_dom = etree.Element("source")
source_dom = add_node_content(unit.source, source_dom)
target_dom = etree.Element("target")
if unit.target:
target_dom = add_node_content(unit.target, target_dom)
else:
target_dom = add_node_content(unit.source, target_dom)
return (source_dom, target_dom)
make_parse_state = lambda: ParseState(NO_TRANSLATE_ELEMENTS,
INLINE_ELEMENTS)
for filename, dom_tree in dom_trees.items():
file_unit_tree = unit_trees[filename]
apply_translations(dom_tree.getroot(), file_unit_tree,
replace_dom_text(make_parse_state,
dom_retriever=get_po_doms,
process_translatable=process_idml_translatable))
return dom_trees
dom_trees = load_dom_trees(template)
unit_trees = load_unit_tree(input_file)
return translate_dom_trees(unit_trees, dom_trees)
def write_idml(template_zip, output_file, dom_trees):
"""Write the translated IDML package."""
output_zip = ZipFile(output_file, 'w', compression=ZIP_DEFLATED)
# Copy the IDML package.
output_zip = copy_idml(template_zip, output_zip, dom_trees.keys())
# Replace the translated files in the IDML package.
for filename, dom_tree in dom_trees.items():
output_zip.writestr(filename, etree.tostring(dom_tree,
encoding='UTF-8',
xml_declaration=True,
standalone='yes'))
def convertpo(input_file, output_file, template):
"""Create a translated IDML using an IDML template and a PO file."""
# Now proceed with the conversion.
template_zip = ZipFile(template, 'r')
translatable_files = [filename for filename in template_zip.namelist()
if filename.startswith('Stories/')]
po_data = input_file.read()
dom_trees = translate_idml(template, BytesIO(po_data), translatable_files)
write_idml(template_zip, output_file, dom_trees)
output_file.close()
return True
def main(argv=None):
formats = {
('po', 'idml'): ("idml", convertpo),
}
parser = convert.ConvertOptionParser(formats, usetemplates=True,
description=__doc__)
parser.run(argv)
if __name__ == '__main__':
main()
| {
"pile_set_name": "Github"
} |
//
// GPUImagePicture+TextureSubimage.h
// GPUImage
//
// Created by Jack Wu on 2014-05-28.
// Copyright (c) 2014 Brad Larson. All rights reserved.
//
#import "GPUImagePicture.h"
@interface GPUImagePicture (TextureSubimage)
- (void)replaceTextureWithSubimage:(UIImage*)subimage;
- (void)replaceTextureWithSubCGImage:(CGImageRef)subimageSource;
- (void)replaceTextureWithSubimage:(UIImage*)subimage inRect:(CGRect)subRect;
- (void)replaceTextureWithSubCGImage:(CGImageRef)subimageSource inRect:(CGRect)subRect;
@end
| {
"pile_set_name": "Github"
} |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { UserReportComponent } from './user-report.component';
describe('UserReportComponent', () => {
let component: UserReportComponent;
let fixture: ComponentFixture<UserReportComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ UserReportComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserReportComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| {
"pile_set_name": "Github"
} |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Threading;
using StarkPlatform.Compiler;
using StarkPlatform.Compiler.CodeActions;
using StarkPlatform.Compiler.Stark.Extensions;
using StarkPlatform.Compiler.Stark.Symbols;
using StarkPlatform.Compiler.Stark.Syntax;
using StarkPlatform.Compiler.Formatting;
using StarkPlatform.Compiler.Shared.Utilities;
namespace StarkPlatform.Compiler.Stark.CodeRefactorings.LambdaSimplifier
{
internal partial class LambdaSimplifierCodeRefactoringProvider
{
private class Rewriter : CSharpSyntaxRewriter
{
private readonly LambdaSimplifierCodeRefactoringProvider _codeIssueProvider;
private readonly SemanticDocument _document;
private readonly Func<SyntaxNode, bool> _predicate;
private readonly CancellationToken _cancellationToken;
public Rewriter(
LambdaSimplifierCodeRefactoringProvider codeIssueProvider,
SemanticDocument document,
Func<SyntaxNode, bool> predicate,
CancellationToken cancellationToken)
{
_codeIssueProvider = codeIssueProvider;
_document = document;
_predicate = predicate;
_cancellationToken = cancellationToken;
}
private ExpressionSyntax SimplifyInvocation(InvocationExpressionSyntax invocation)
{
var expression = invocation.Expression;
if (expression is MemberAccessExpressionSyntax memberAccess)
{
var symbolMap = SemanticMap.From(_document.SemanticModel, memberAccess.Expression, _cancellationToken);
var anySideEffects = symbolMap.AllReferencedSymbols.Any(s =>
s.Kind == SymbolKind.Method || s.Kind == SymbolKind.Property);
if (anySideEffects)
{
var annotation = WarningAnnotation.Create("Warning: Expression may have side effects. Code meaning may change.");
expression = expression.ReplaceNode(memberAccess.Expression, memberAccess.Expression.WithAdditionalAnnotations(annotation));
}
}
return expression.Parenthesize()
.WithAdditionalAnnotations(Formatter.Annotation);
}
public override SyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node)
{
if (_predicate(node) && CanSimplify(_document, node, _cancellationToken))
{
var invocation = TryGetInvocationExpression(node.Body);
if (invocation != null)
{
return SimplifyInvocation(invocation);
}
}
return base.VisitSimpleLambdaExpression(node);
}
public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node)
{
if (_predicate(node) && CanSimplify(_document, node, _cancellationToken))
{
var invocation = TryGetInvocationExpression(node.Body);
if (invocation != null)
{
return SimplifyInvocation(invocation);
}
}
return base.VisitParenthesizedLambdaExpression(node);
}
}
}
}
| {
"pile_set_name": "Github"
} |
libavformat/cinedec.o: libavformat/cinedec.c libavutil/intreadwrite.h \
libavutil/avconfig.h libavutil/attributes.h libavutil/bswap.h config.h \
libavcodec/bmp.h libavcodec/avcodec.h libavutil/samplefmt.h \
libavutil/avutil.h libavutil/common.h libavutil/macros.h \
libavutil/version.h libavutil/intmath.h libavutil/mem.h \
libavutil/error.h libavutil/internal.h libavutil/timer.h libavutil/log.h \
libavutil/cpu.h libavutil/dict.h libavutil/pixfmt.h libavutil/libm.h \
libavutil/intfloat.h libavutil/mathematics.h libavutil/rational.h \
libavutil/attributes.h libavutil/avutil.h libavutil/buffer.h \
libavutil/cpu.h libavutil/channel_layout.h libavutil/dict.h \
libavutil/frame.h libavutil/buffer.h libavutil/samplefmt.h \
libavutil/log.h libavutil/pixfmt.h libavutil/rational.h \
libavcodec/version.h libavutil/version.h libavutil/intfloat.h \
libavformat/avformat.h libavcodec/avcodec.h libavformat/avio.h \
libavutil/common.h libavformat/version.h libavformat/internal.h \
libavutil/bprint.h libavutil/avstring.h libavformat/os_support.h
| {
"pile_set_name": "Github"
} |
#!/system/bin/sh
ANDROID_SDK=`getprop ro.build.version.sdk`
if [[ "$ANDROID_SDK" -gt 28 ]]
then
echo 1
else
echo 0
fi
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<title>Connect</title>
<meta http-equiv="content-type" value="text/html; charset=utf-8">
<style type="text/css">
body {
font: 13px "Helvetica Neue", "Lucida Grande", "Arial";
text-align: center;
color: #555;
-webkit-text-stroke: 1px rgba(255, 255, 255, 0.1);
}
h1, h2, h3 {
margin: 0;
font-size: 22px;
font-weight: normal;
color: #343434;
}
h2#Connect {
margin-bottom: 25px;
font-size: 60px;
font-weight: bold;
}
h2#Connect + p {
display: none;
}
h3 {
margin: 35px 0;
padding-left: 10px;
font-size: 16px;
border-left: 15px solid #eee;
}
h2 {
margin-top: 35px;
text-shadow: 1px 2px 2px #ddd;
}
ul {
margin: 10px 35px;
padding: 0;
}
ul li .path {
padding-left: 5px;
font-weight: bold;
}
ul li .line {
padding-right: 5px;
font-style: italic;
}
ul li:first-child .path {
padding-left: 0;
}
p {
line-height: 1.5;
}
p code {
padding: 2px 4px;
border: 1px solid #ddd;
}
p em, li em {
font-weight: bold;
}
pre {
margin: 25px 0 25px 15px;
padding: 15px;
border: 1px solid #ddd;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-webkit-box-shadow: 1px 1px 6px #ddd;
-moz-box-shadow: 1px 1px 6px #ddd;
}
table {
margin-bottom: 35px;
width: 100%;
border-collapse: collapse;
}
table td {
padding: 5px 10px;
font-size: 14px;
}
table tr {
border-bottom: 1px solid #fff;
}
table tr:last-child {
border-bottom: none;
}
table td:first-child {
width: 150px;
color: #343434;
}
#wrapper {
margin: 50px auto;
width: 750px;
text-align: left;
}
#menu {
position: fixed;
top: 15px;
right: 15px;
margin: 0;
padding: 0;
list-style: none;
text-align: right;
}
#menu li.title {
padding: 20px 0 5px 0;
font-size: 12px;
}
code.js { color: #111; }
code.js .comment { color: #999; }
code.js .string { color: #cc0000; }
code.js .number { color: #0000ee; }
code.js .keyword { color: #000; font-weight: bold; }
a {
text-decoration: none;
color: #000;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div id="wrapper">
<ul id="menu">
<li class="title">API</li>
<li><a href="api.html">extended api docs</a></li>
<li class="title">Middleware</li>
<li><a href="lint.html">lint</a></li>
<li><a href="logger.html">logger</a></li>
<li><a href="format.html">format</a></li>
<li><a href="router.html">router</a></li>
<li><a href="jsonrpc.html">jsonrpc</a></li>
<li><a href="session.html">session</a></li>
<li><a href="compiler.html">compiler</a></li>
<li><a href="errorHandler.html">errorHandler</a></li>
<li><a href="bodyDecoder.html">bodyDecoder</a></li>
<li><a href="responseTime.html">responseTime</a></li>
<li><a href="cookieDecoder.html">cookieDecoder</a></li>
<li><a href="conditionalGet.html">conditionalGet</a></li>
<li><a href="methodOverride.html">methodOverride</a></li>
<li><a href="staticProvider.html">staticProvider</a></li>
</ul> | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2014-2017, Siemens AG. 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 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 HOLDER 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.
*/
#ifndef EMBB_ALGORITHMS_INVOKE_H_
#define EMBB_ALGORITHMS_INVOKE_H_
#include <embb/base/function.h>
#include <embb/mtapi/mtapi.h>
namespace embb {
namespace algorithms {
/**
* \defgroup CPP_ALGORITHMS_INVOKE Invoke
* Parallel invocation of functions.
* \ingroup CPP_ALGORITHMS
*/
/**
* Function type used by Invoke.
* \ingroup CPP_ALGORITHMS_INVOKE
*/
typedef embb::base::Function<void> InvokeFunctionType;
#ifdef DOXYGEN
/**
* Spawns two to ten function objects or embb::mtapi::Job at once and runs
* them in parallel.
*
* Blocks until all of them are done.
*
* \ingroup CPP_ALGORITHMS_INVOKE
*/
template<typename Function1, typename Function2, ...>
void Invoke(
Function1 func1,
/**< [in] First function object to invoke */
Function2 func2,
/**< [in] Second function object to invoke */
...);
/**
* Spawns two to ten function objects or embb::mtapi::Job at once and runs
* them in parallel using the given embb::mtapi::ExecutionPolicy.
*
* Blocks until all of them are done.
*
* \ingroup CPP_ALGORITHMS_INVOKE
*/
template<typename Function1, typename Function2, ...>
void Invoke(
Function1 func1,
/**< [in] Function object to invoke */
Function2 func2,
/**< [in] Second function object to invoke */
...,
const embb::mtapi::ExecutionPolicy & policy
/**< [in] embb::mtapi::ExecutionPolicy to use */
);
#else // DOXYGEN
namespace internal {
/**
* Spawns an MTAPI task on construction and waits for it on destruction.
*/
template<typename Function>
class TaskWrapper {
public:
/**
* Wraps the function into an embb::tasks::Action and spawns an
* embb::tasks::Task.
*/
explicit TaskWrapper(
Function function,
const embb::mtapi::ExecutionPolicy& policy)
: function_(function), task_() {
task_ = embb::mtapi::Node::GetInstance().Start(
embb::base::MakeFunction(*this, &TaskWrapper::Run),
policy);
}
/**
* Waits until the task has finished execution.
*/
~TaskWrapper() {
task_.Wait(MTAPI_INFINITE);
}
private:
Function function_;
embb::mtapi::Task task_;
void Run(embb::mtapi::TaskContext&) {
function_();
}
};
/**
* Spawns an MTAPI task on construction and waits for it on destruction.
*/
template<>
class TaskWrapper<embb::mtapi::Job> {
public:
/**
* Wraps the function into an embb::tasks::Action and spawns an
* embb::tasks::Task.
*/
explicit TaskWrapper(
embb::mtapi::Job function,
const embb::mtapi::ExecutionPolicy& policy)
: function_(function), task_() {
embb::mtapi::TaskAttributes attr;
attr.SetPolicy(policy);
task_ = embb::mtapi::Node::GetInstance().Start(
function,
static_cast<void const *>(MTAPI_NULL),
static_cast<void *>(MTAPI_NULL),
attr);
}
/**
* Waits until the task has finished execution.
*/
~TaskWrapper() {
task_.Wait(MTAPI_INFINITE);
}
private:
embb::mtapi::Job function_;
embb::mtapi::Task task_;
};
} // namespace internal
template<typename Function1, typename Function2>
void Invoke(
Function1 func1,
Function2 func2,
const embb::mtapi::ExecutionPolicy& policy) {
internal::TaskWrapper<Function1> wrap1(func1, policy);
internal::TaskWrapper<Function2> wrap2(func2, policy);
}
template<typename Function1, typename Function2, typename Function3>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
const embb::mtapi::ExecutionPolicy& policy) {
internal::TaskWrapper<Function1> wrap1(func1, policy);
internal::TaskWrapper<Function2> wrap2(func2, policy);
internal::TaskWrapper<Function3> wrap3(func3, policy);
}
template<typename Function1, typename Function2, typename Function3,
typename Function4>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
const embb::mtapi::ExecutionPolicy& policy) {
internal::TaskWrapper<Function1> wrap1(func1, policy);
internal::TaskWrapper<Function2> wrap2(func2, policy);
internal::TaskWrapper<Function3> wrap3(func3, policy);
internal::TaskWrapper<Function4> wrap4(func4, policy);
}
template<typename Function1, typename Function2, typename Function3,
typename Function4, typename Function5>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
Function5 func5,
const embb::mtapi::ExecutionPolicy& policy) {
internal::TaskWrapper<Function1> wrap1(func1, policy);
internal::TaskWrapper<Function2> wrap2(func2, policy);
internal::TaskWrapper<Function3> wrap3(func3, policy);
internal::TaskWrapper<Function4> wrap4(func4, policy);
internal::TaskWrapper<Function5> wrap5(func5, policy);
}
template<typename Function1, typename Function2, typename Function3,
typename Function4, typename Function5, typename Function6>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
Function5 func5,
Function6 func6,
const embb::mtapi::ExecutionPolicy& policy) {
internal::TaskWrapper<Function1> wrap1(func1, policy);
internal::TaskWrapper<Function2> wrap2(func2, policy);
internal::TaskWrapper<Function3> wrap3(func3, policy);
internal::TaskWrapper<Function4> wrap4(func4, policy);
internal::TaskWrapper<Function5> wrap5(func5, policy);
internal::TaskWrapper<Function6> wrap6(func6, policy);
}
template<typename Function1, typename Function2, typename Function3,
typename Function4, typename Function5, typename Function6,
typename Function7>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
Function5 func5,
Function6 func6,
Function7 func7,
const embb::mtapi::ExecutionPolicy& policy) {
internal::TaskWrapper<Function1> wrap1(func1, policy);
internal::TaskWrapper<Function2> wrap2(func2, policy);
internal::TaskWrapper<Function3> wrap3(func3, policy);
internal::TaskWrapper<Function4> wrap4(func4, policy);
internal::TaskWrapper<Function5> wrap5(func5, policy);
internal::TaskWrapper<Function6> wrap6(func6, policy);
internal::TaskWrapper<Function7> wrap7(func7, policy);
}
template<typename Function1, typename Function2, typename Function3,
typename Function4, typename Function5, typename Function6,
typename Function7, typename Function8>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
Function5 func5,
Function6 func6,
Function7 func7,
Function8 func8,
const embb::mtapi::ExecutionPolicy& policy) {
internal::TaskWrapper<Function1> wrap1(func1, policy);
internal::TaskWrapper<Function2> wrap2(func2, policy);
internal::TaskWrapper<Function3> wrap3(func3, policy);
internal::TaskWrapper<Function4> wrap4(func4, policy);
internal::TaskWrapper<Function5> wrap5(func5, policy);
internal::TaskWrapper<Function6> wrap6(func6, policy);
internal::TaskWrapper<Function7> wrap7(func7, policy);
internal::TaskWrapper<Function8> wrap8(func8, policy);
}
template<typename Function1, typename Function2, typename Function3,
typename Function4, typename Function5, typename Function6,
typename Function7, typename Function8, typename Function9>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
Function5 func5,
Function6 func6,
Function7 func7,
Function8 func8,
Function9 func9,
const embb::mtapi::ExecutionPolicy& policy) {
internal::TaskWrapper<Function1> wrap1(func1, policy);
internal::TaskWrapper<Function2> wrap2(func2, policy);
internal::TaskWrapper<Function3> wrap3(func3, policy);
internal::TaskWrapper<Function4> wrap4(func4, policy);
internal::TaskWrapper<Function5> wrap5(func5, policy);
internal::TaskWrapper<Function6> wrap6(func6, policy);
internal::TaskWrapper<Function7> wrap7(func7, policy);
internal::TaskWrapper<Function8> wrap8(func8, policy);
internal::TaskWrapper<Function9> wrap9(func9, policy);
}
template<typename Function1, typename Function2, typename Function3,
typename Function4, typename Function5, typename Function6,
typename Function7, typename Function8, typename Function9,
typename Function10>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
Function5 func5,
Function6 func6,
Function7 func7,
Function8 func8,
Function9 func9,
Function10 func10,
const embb::mtapi::ExecutionPolicy& policy) {
internal::TaskWrapper<Function1> wrap1(func1, policy);
internal::TaskWrapper<Function2> wrap2(func2, policy);
internal::TaskWrapper<Function3> wrap3(func3, policy);
internal::TaskWrapper<Function4> wrap4(func4, policy);
internal::TaskWrapper<Function5> wrap5(func5, policy);
internal::TaskWrapper<Function6> wrap6(func6, policy);
internal::TaskWrapper<Function7> wrap7(func7, policy);
internal::TaskWrapper<Function8> wrap8(func8, policy);
internal::TaskWrapper<Function9> wrap9(func9, policy);
internal::TaskWrapper<Function10> wrap10(func10, policy);
}
template<typename Function1, typename Function2>
void Invoke(
Function1 func1,
Function2 func2) {
Invoke(func1, func2, embb::mtapi::ExecutionPolicy());
}
template<typename Function1, typename Function2, typename Function3>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3) {
Invoke(func1, func2, func3, embb::mtapi::ExecutionPolicy());
}
template<typename Function1, typename Function2, typename Function3,
typename Function4>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4) {
Invoke(func1, func2, func3, func4, embb::mtapi::ExecutionPolicy());
}
template<typename Function1, typename Function2, typename Function3,
typename Function4, typename Function5>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
Function5 func5) {
Invoke(func1, func2, func3, func4, func5, embb::mtapi::ExecutionPolicy());
}
template<typename Function1, typename Function2, typename Function3,
typename Function4, typename Function5, typename Function6>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
Function5 func5,
Function6 func6) {
Invoke(func1, func2, func3, func4, func5, func6,
embb::mtapi::ExecutionPolicy());
}
template<typename Function1, typename Function2, typename Function3,
typename Function4, typename Function5, typename Function6,
typename Function7>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
Function5 func5,
Function6 func6,
Function7 func7) {
Invoke(func1, func2, func3, func4, func5, func6, func7,
embb::mtapi::ExecutionPolicy());
}
template<typename Function1, typename Function2, typename Function3,
typename Function4, typename Function5, typename Function6,
typename Function7, typename Function8>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
Function5 func5,
Function6 func6,
Function7 func7,
Function8 func8) {
Invoke(func1, func2, func3, func4, func5, func6, func7, func8,
embb::mtapi::ExecutionPolicy());
}
template<typename Function1, typename Function2, typename Function3,
typename Function4, typename Function5, typename Function6,
typename Function7, typename Function8, typename Function9>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
Function5 func5,
Function6 func6,
Function7 func7,
Function8 func8,
Function9 func9) {
Invoke(func1, func2, func3, func4, func5, func6, func7, func8, func9,
embb::mtapi::ExecutionPolicy());
}
template<typename Function1, typename Function2, typename Function3,
typename Function4, typename Function5, typename Function6,
typename Function7, typename Function8, typename Function9,
typename Function10>
void Invoke(
Function1 func1,
Function2 func2,
Function3 func3,
Function4 func4,
Function5 func5,
Function6 func6,
Function7 func7,
Function8 func8,
Function9 func9,
Function10 func10) {
Invoke(func1, func2, func3, func4, func5, func6, func7, func8, func9, func10,
embb::mtapi::ExecutionPolicy());
}
#endif // else DOXYGEN
} // namespace algorithms
} // namespace embb
#endif // EMBB_ALGORITHMS_INVOKE_H_
| {
"pile_set_name": "Github"
} |
167 - 两数之和II(two-sum-ii-input-array-is-sorted)
===
> Create by **jsliang** on **2019-07-04 17:17:39**
> Recently revised in **2019-09-18 10:41:20**
## <a name="chapter-one" id="chapter-one">一 目录</a>
**不折腾的前端,和咸鱼有什么区别**
| 目录 |
| --- |
| [一 目录](#chapter-one) |
| <a name="catalog-chapter-two" id="catalog-chapter-two"></a>[二 前言](#chapter-two) |
| <a name="catalog-chapter-three" id="catalog-chapter-three"></a>[三 解题](#chapter-three) |
|  [3.1 解法 - 双指针](#chapter-three-one) |
|  [3.2 解法 - Map()](#chapter-three-two) |
## <a name="chapter-two" id="chapter-two">二 前言</a>
> [返回目录](#chapter-one)
* **难度**:简单
* **涉及知识**:数组、双指针、二分查找
* **题目地址**:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
* **题目内容**:
```
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
```
## <a name="chapter-three" id="chapter-three">三 解题</a>
> [返回目录](#chapter-one)
小伙伴可以先自己在本地尝试解题,再回来看看 **jsliang** 的解题思路。
### <a name="chapter-three-one" id="chapter-three-one">3.1 解法 - 双指针</a>
> [返回目录](#chapter-one)
* **解题代码**:
```js
var twoSum = function(numbers, target) {
for (let i = 0; i < numbers.length - 1; i++) {
for (let j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] === target) {
return [i + 1, j + 1];
}
}
}
return [];
};
```
* **执行测试**:
1. `numbers`:`[2, 7, 11, 15]`
2. `target`:`9`
3. `return`:`[1, 2]`
* **LeetCode Submit**:
```js
✔ Accepted
✔ 17/17 cases passed (436 ms)
✔ Your runtime beats 13.64 % of javascript submissions
✔ Your memory usage beats 94.19 % of javascript submissions (34.6 MB)
```
* **解题思路**:
拿到题,看下题目,想 1 分钟思路,敲 1 分钟代码,提交,完事……
**我变强了,还好没那么快秃!**
**首先**,想到的就是双指针法,思路很简单:
1. 当 `i` 遍历到 `2` 的时候,`j` 依次遍历 `7`、`11`、`15`
2. 当 `i` 遍历到 `7` 的时候,`j` 依次遍历 `11`、`15`
3. 当 `i` 遍历到 `11` 的时候,`j` 依次遍历 `15`
4. 当 `i` 为 `15` 的时候,不遍历。
当然,这是正常情况下,`i` 指针和 `j` 指针指向不同的位置。
**然后**:
```js
if (numbers[i] + numbers[j] === target) {
return [i + 1, j + 1];
}
```
判断这两者相加是否为 `target` 的值,相同则 `return` 出去就行了。
**最后**,如果小伙伴们还是没看懂这解题思路,建议多看两道双指针的题目,原理都是十分简单的。
### <a name="chapter-three-two" id="chapter-three-two">3.2 解法 - Map()</a>
> [返回目录](#chapter-one)
* **解题代码**:
```js
var twoSum = function(numbers, target) {
let map = new Map();
for (let i = 0; i < numbers.length; i++) {
if (map.get(numbers[i]) !== undefined) {
return [map.get(numbers[i]), i + 1];
} else {
map.set(target - numbers[i], i + 1);
}
}
return [];
};
```
* **执行测试**:
1. `numbers`:`[2, 7, 11, 15]`
2. `target`:`9`
3. `return`:`[1, 2]`
* **LeetCode Submit**:
```js
✔ Accepted
✔ 17/17 cases passed (68 ms)
✔ Your runtime beats 98.53 % of javascript submissions
✔ Your memory usage beats 6.77 % of javascript submissions (35.5 MB)
```
* **知识点**:
1. `Map`:保存键值对。任何值(对象或者原始值) 都可以作为一个键或一个值。[`Map` 详细介绍](https://github.com/LiangJunrong/document-library/blob/master/JavaScript-library/JavaScript/%E5%86%85%E7%BD%AE%E5%AF%B9%E8%B1%A1/Map/README.md)
* **解题思路**:
**回头想了一下,杀它个回马枪**
在双指针解法中,我们花费了大量的时间,因为进行了双重 `for` 遍历。
那么,我们可不可以压缩下呢?
于是,咱想到了 `Map`,使用哈希算法来解题。
让我们看看,将遍历中的数据,都进行 `Map` 存储,是怎样子的:
```js
Map { 7 => 0 }
undefined
Map { 7 => 0, 2 => 1 }
0
Map { 7 => 0, 2 => 1, -2 => 2 }
undefined
Map { 7 => 0, 2 => 1, -2 => 2, -6 => 3 }
undefined
```
看到这里,小伙伴们心里是不是异常清晰了?
是的,我们将每个数字的差值,作为 `key` 存储起来,然后将每个数字的索引(`index`),作为 `value` 存储起来。
这样,当我们获取不存在的值的时候,返回 `undefined`;
获取 `9 - 2 = 7` 的时候,它就不是 `undefined` 了,而是告诉我们它的 `value` 为 `0`
最终,通过判断取到的 `value` 是否为 `undefined`,我们成功通过 `Map` 破解了这道题。
---
**不折腾的前端,和咸鱼有什么区别!**

**jsliang** 会每天更新一道 LeetCode 题解,从而帮助小伙伴们夯实原生 JS 基础,了解与学习算法与数据结构。
扫描上方二维码,关注 **jsliang** 的公众号,让我们一起折腾!
> <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="知识共享许可协议" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">jsliang 的文档库</span> 由 <a xmlns:cc="http://creativecommons.org/ns#" href="https://github.com/LiangJunrong/document-library" property="cc:attributionName" rel="cc:attributionURL">梁峻荣</a> 采用 <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议</a>进行许可。<br />基于<a xmlns:dct="http://purl.org/dc/terms/" href="https://github.com/LiangJunrong/document-library" rel="dct:source">https://github.com/LiangJunrong/document-library</a>上的作品创作。<br />本许可协议授权之外的使用权限可以从 <a xmlns:cc="http://creativecommons.org/ns#" href="https://creativecommons.org/licenses/by-nc-sa/2.5/cn/" rel="cc:morePermissions">https://creativecommons.org/licenses/by-nc-sa/2.5/cn/</a> 处获得。 | {
"pile_set_name": "Github"
} |
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Class VisualBasicCodeGenerationService
Inherits AbstractCodeGenerationService
Public Sub New(provider As HostLanguageServices)
MyBase.New(provider.GetService(Of ISymbolDeclarationService)())
End Sub
Public Overloads Overrides Function GetDestination(containerNode As SyntaxNode) As CodeGenerationDestination
Return VisualBasicCodeGenerationHelpers.GetDestination(containerNode)
End Function
Protected Overrides Function CreateImportsAdder(document As Document) As AbstractImportsAdder
Return New ImportsStatementsAdder(document)
End Function
Protected Overrides Function GetAvailableInsertionIndices(destination As SyntaxNode, cancellationToken As CancellationToken) As IList(Of Boolean)
' NOTE(cyrusn): We know that the destination overlaps some hidden regions.
If TypeOf destination Is TypeBlockSyntax Then
Return DirectCast(destination, TypeBlockSyntax).GetInsertionIndices(cancellationToken)
End If
If TypeOf destination Is CompilationUnitSyntax Then
Return GetAvailableInsertionIndices(DirectCast(destination, CompilationUnitSyntax), cancellationToken)
End If
' TODO(cyrusn): This will exclude all non-type-blocks if they overlap a hidden region.
' For example, for enums or namespaces. We could consider relaxing that and actually
' attempting to determine where in the destination are viable, if we think it's worth
' it.
Return Nothing
End Function
Private Overloads Function GetAvailableInsertionIndices(destination As CompilationUnitSyntax, cancellationToken As CancellationToken) As IList(Of Boolean)
Dim members = destination.Members
Dim indices = New List(Of Boolean)
If members.Count >= 1 Then
' First, see if we can insert between the start of the typeblock, and it's first
' member.
indices.Add(Not destination.OverlapsHiddenPosition(TextSpan.FromBounds(0, destination.Members.First.SpanStart), cancellationToken))
' Now, walk between each member and see if something can be inserted between it and
' the next member
For i = 0 To members.Count - 2
Dim member1 = members(i)
Dim member2 = members(i + 1)
indices.Add(Not destination.OverlapsHiddenPosition(member1, member2, cancellationToken))
Next
' Last, see if we can insert between the last member and the end of the typeblock
indices.Add(Not destination.OverlapsHiddenPosition(
TextSpan.FromBounds(destination.Members.Last.Span.End, destination.EndOfFileToken.SpanStart), cancellationToken))
End If
Return indices
End Function
Protected Overrides Function AddEvent(Of TDeclarationNode As SyntaxNode)(
destinationType As TDeclarationNode,
[event] As IEventSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TDeclarationNode
CheckDeclarationNode(Of TypeBlockSyntax)(destinationType)
Return Cast(Of TDeclarationNode)(EventGenerator.AddEventTo(Cast(Of TypeBlockSyntax)(destinationType), [event], options, availableIndices))
End Function
Protected Overrides Function AddField(Of TDeclarationNode As SyntaxNode)(
destinationType As TDeclarationNode,
field As IFieldSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TDeclarationNode
CheckDeclarationNode(Of EnumBlockSyntax, TypeBlockSyntax, CompilationUnitSyntax)(destinationType)
If TypeOf destinationType Is EnumBlockSyntax Then
Return Cast(Of TDeclarationNode)(EnumMemberGenerator.AddEnumMemberTo(Cast(Of EnumBlockSyntax)(destinationType), field, options))
ElseIf TypeOf destinationType Is TypeBlockSyntax Then
Return Cast(Of TDeclarationNode)(FieldGenerator.AddFieldTo(Cast(Of TypeBlockSyntax)(destinationType), field, options, availableIndices))
Else
Return Cast(Of TDeclarationNode)(FieldGenerator.AddFieldTo(Cast(Of CompilationUnitSyntax)(destinationType), field, options, availableIndices))
End If
End Function
Protected Overrides Function AddProperty(Of TDeclarationNode As SyntaxNode)(
destinationType As TDeclarationNode,
[property] As IPropertySymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TDeclarationNode
CheckDeclarationNode(Of TypeBlockSyntax, CompilationUnitSyntax)(destinationType)
If TypeOf destinationType Is TypeBlockSyntax Then
Return Cast(Of TDeclarationNode)(PropertyGenerator.AddPropertyTo(Cast(Of TypeBlockSyntax)(destinationType), [property], options, availableIndices))
Else
Return Cast(Of TDeclarationNode)(PropertyGenerator.AddPropertyTo(Cast(Of CompilationUnitSyntax)(destinationType), [property], options, availableIndices))
End If
End Function
Protected Overrides Function AddMethod(Of TDeclarationNode As SyntaxNode)(
destination As TDeclarationNode,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TDeclarationNode
CheckDeclarationNode(Of TypeBlockSyntax, CompilationUnitSyntax, NamespaceBlockSyntax)(destination)
' Synthesized methods for properties/events are not things we actually generate
' declarations for.
If method.AssociatedSymbol IsNot Nothing Then
Return destination
End If
Dim typeDeclaration As TypeBlockSyntax = TryCast(destination, TypeBlockSyntax)
If typeDeclaration IsNot Nothing Then
If method.IsConstructor() Then
Return Cast(Of TDeclarationNode)(ConstructorGenerator.AddConstructorTo(typeDeclaration, method, options, availableIndices))
End If
If method.MethodKind = MethodKind.UserDefinedOperator Then
Return Cast(Of TDeclarationNode)(OperatorGenerator.AddOperatorTo(typeDeclaration, method, options, availableIndices))
End If
If method.MethodKind = MethodKind.Conversion Then
Return Cast(Of TDeclarationNode)(ConversionGenerator.AddConversionTo(typeDeclaration, method, options, availableIndices))
End If
Return Cast(Of TDeclarationNode)(MethodGenerator.AddMethodTo(typeDeclaration, method, options, availableIndices))
End If
If method.IsConstructor() Then
Return destination
End If
Dim compilationUnit = TryCast(destination, CompilationUnitSyntax)
If compilationUnit IsNot Nothing Then
Return Cast(Of TDeclarationNode)(MethodGenerator.AddMethodTo(compilationUnit, method, options, availableIndices))
End If
Dim ns = Cast(Of NamespaceBlockSyntax)(destination)
Return Cast(Of TDeclarationNode)(MethodGenerator.AddMethodTo(ns, method, options, availableIndices))
End Function
Protected Overloads Overrides Function AddNamedType(Of TDeclarationNode As SyntaxNode)(
destination As TDeclarationNode,
namedType As INamedTypeSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TDeclarationNode
CheckDeclarationNode(Of TypeBlockSyntax, NamespaceBlockSyntax, CompilationUnitSyntax)(destination)
options = If(options, CodeGenerationOptions.Default)
If TypeOf destination Is TypeBlockSyntax Then
Return Cast(Of TDeclarationNode)(NamedTypeGenerator.AddNamedTypeTo(Me, Cast(Of TypeBlockSyntax)(destination), namedType, options, availableIndices))
ElseIf TypeOf destination Is NamespaceBlockSyntax Then
Return Cast(Of TDeclarationNode)(NamedTypeGenerator.AddNamedTypeTo(Me, Cast(Of NamespaceBlockSyntax)(destination), namedType, options, availableIndices))
Else
Return Cast(Of TDeclarationNode)(NamedTypeGenerator.AddNamedTypeTo(Me, Cast(Of CompilationUnitSyntax)(destination), namedType, options, availableIndices))
End If
End Function
Protected Overrides Function AddNamespace(Of TDeclarationNode As SyntaxNode)(
destination As TDeclarationNode,
[namespace] As INamespaceSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TDeclarationNode
CheckDeclarationNode(Of CompilationUnitSyntax, NamespaceBlockSyntax)(destination)
If TypeOf destination Is CompilationUnitSyntax Then
Return Cast(Of TDeclarationNode)(NamespaceGenerator.AddNamespaceTo(Me, Cast(Of CompilationUnitSyntax)(destination), [namespace], options, availableIndices))
Else
Return Cast(Of TDeclarationNode)(NamespaceGenerator.AddNamespaceTo(Me, Cast(Of NamespaceBlockSyntax)(destination), [namespace], options, availableIndices))
End If
End Function
Public Overrides Function AddParameters(Of TDeclarationNode As SyntaxNode)(
destinationMember As TDeclarationNode,
parameters As IEnumerable(Of IParameterSymbol),
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As TDeclarationNode
Dim methodBlock = TryCast(destinationMember, MethodBlockBaseSyntax)
Dim methodStatement = If(methodBlock IsNot Nothing,
methodBlock.BlockStatement,
TryCast(destinationMember, MethodBaseSyntax))
If methodStatement IsNot Nothing Then
Select Case methodStatement.Kind
Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement
' Don't allow adding parameters to Property Getter/Setter
Return destinationMember
Case Else
Return AddParametersToMethod(Of TDeclarationNode)(methodStatement, methodBlock, parameters, options)
End Select
Else
Dim propertyBlock = TryCast(destinationMember, PropertyBlockSyntax)
If propertyBlock IsNot Nothing Then
Return AddParametersToProperty(Of TDeclarationNode)(propertyBlock, parameters, options)
End If
End If
Return destinationMember
End Function
Protected Overrides Function AddMembers(Of TDeclarationNode As SyntaxNode)(destination As TDeclarationNode, members As IEnumerable(Of SyntaxNode)) As TDeclarationNode
CheckDeclarationNode(Of EnumBlockSyntax, TypeBlockSyntax, NamespaceBlockSyntax, CompilationUnitSyntax)(destination)
If TypeOf destination Is EnumBlockSyntax Then
Return Cast(Of TDeclarationNode)(Cast(Of EnumBlockSyntax)(destination).AddMembers(members.Cast(Of EnumMemberDeclarationSyntax).ToArray()))
ElseIf TypeOf destination Is TypeBlockSyntax Then
Return Cast(Of TDeclarationNode)(Cast(Of TypeBlockSyntax)(destination).AddMembers(members.Cast(Of StatementSyntax).ToArray()))
ElseIf TypeOf destination Is NamespaceBlockSyntax Then
Return Cast(Of TDeclarationNode)(Cast(Of NamespaceBlockSyntax)(destination).AddMembers(members.Cast(Of StatementSyntax).ToArray()))
Else
Return Cast(Of TDeclarationNode)(Cast(Of CompilationUnitSyntax)(destination).AddMembers(members.Cast(Of StatementSyntax).ToArray()))
End If
End Function
Private Overloads Shared Function AddParametersToMethod(Of TDeclarationNode As SyntaxNode)(methodStatement As MethodBaseSyntax,
methodBlock As MethodBlockBaseSyntax,
parameters As IEnumerable(Of IParameterSymbol),
options As CodeGenerationOptions) As TDeclarationNode
Dim newParameterList = AddParameters(methodStatement.ParameterList, parameters, options)
Dim finalStatement = methodStatement.WithParameterList(newParameterList)
Dim result As Object
If methodBlock IsNot Nothing Then
Select Case methodBlock.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
result = DirectCast(methodBlock, MethodBlockSyntax).WithBlockStatement(DirectCast(finalStatement, MethodStatementSyntax))
Case SyntaxKind.ConstructorBlock
result = DirectCast(methodBlock, ConstructorBlockSyntax).WithBlockStatement(DirectCast(finalStatement, SubNewStatementSyntax))
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
result = DirectCast(methodBlock, AccessorBlockSyntax).WithBlockStatement(DirectCast(finalStatement, AccessorStatementSyntax))
Case Else
result = DirectCast(methodBlock, OperatorBlockSyntax).WithBlockStatement(DirectCast(finalStatement, OperatorStatementSyntax))
End Select
Else
result = finalStatement
End If
Return DirectCast(DirectCast(result, Object), TDeclarationNode)
End Function
Private Overloads Shared Function AddParametersToProperty(Of TDeclarationNode As SyntaxNode)(
propertyBlock As PropertyBlockSyntax,
parameters As IEnumerable(Of IParameterSymbol),
options As CodeGenerationOptions) As TDeclarationNode
Dim propertyStatement = propertyBlock.PropertyStatement
Dim newParameterList = AddParameters(propertyStatement.ParameterList, parameters, options)
Dim newPropertyStatement = propertyStatement.WithParameterList(newParameterList)
Dim newPropertyBlock As SyntaxNode = propertyBlock.WithPropertyStatement(newPropertyStatement)
Return DirectCast(newPropertyBlock, TDeclarationNode)
End Function
Private Overloads Shared Function AddParameters(parameterList As ParameterListSyntax, parameters As IEnumerable(Of IParameterSymbol), options As CodeGenerationOptions) As ParameterListSyntax
Dim nodesAndTokens = If(parameterList IsNot Nothing,
New List(Of SyntaxNodeOrToken)(parameterList.Parameters.GetWithSeparators()),
New List(Of SyntaxNodeOrToken))
Dim currentParamsCount = If(parameterList IsNot Nothing, parameterList.Parameters.Count, 0)
Dim seenOptional = currentParamsCount > 0 AndAlso parameterList.Parameters(currentParamsCount - 1).Default IsNot Nothing
For Each parameter In parameters
If nodesAndTokens.Count > 0 AndAlso nodesAndTokens.Last().Kind() <> SyntaxKind.CommaToken Then
nodesAndTokens.Add(SyntaxFactory.Token(SyntaxKind.CommaToken))
End If
Dim parameterSyntax = ParameterGenerator.GenerateParameter(parameter, seenOptional, options)
nodesAndTokens.Add(parameterSyntax)
seenOptional = seenOptional OrElse parameterSyntax.Default IsNot Nothing
Next
Return If(parameterList IsNot Nothing,
SyntaxFactory.ParameterList(parameterList.OpenParenToken, SyntaxFactory.SeparatedList(Of ParameterSyntax)(nodesAndTokens), parameterList.CloseParenToken),
SyntaxFactory.ParameterList(parameters:=SyntaxFactory.SeparatedList(Of ParameterSyntax)(nodesAndTokens)))
End Function
Public Overrides Function AddAttributes(Of TDeclarationNode As SyntaxNode)(
destination As TDeclarationNode,
attributes As IEnumerable(Of AttributeData),
target As SyntaxToken?,
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As TDeclarationNode
If target.HasValue AndAlso Not target.Value.IsValidAttributeTarget() Then
Throw New ArgumentException("target")
End If
Dim attributeSyntaxList = AttributeGenerator.GenerateAttributeBlocks(attributes.ToImmutableArray(), options, target)
' Handle most cases
Dim member = TryCast(destination, StatementSyntax)
If member IsNot Nothing Then
Return Cast(Of TDeclarationNode)(member.AddAttributeLists(attributeSyntaxList.ToArray()))
End If
' Handle global attributes
Dim compilationUnit = TryCast(destination, CompilationUnitSyntax)
If compilationUnit IsNot Nothing Then
Return Cast(Of TDeclarationNode)(compilationUnit.AddAttributes(SyntaxFactory.AttributesStatement(attributeSyntaxList)))
End If
' Handle parameters
Dim parameter = TryCast(destination, ParameterSyntax)
If parameter IsNot Nothing Then
Return Cast(Of TDeclarationNode)(parameter.AddAttributeLists(attributeSyntaxList.ToArray()))
End If
Return destination
End Function
Public Overrides Function RemoveAttribute(Of TDeclarationNode As SyntaxNode)(destination As TDeclarationNode, attributeToRemove As AttributeData, options As CodeGenerationOptions, cancellationToken As CancellationToken) As TDeclarationNode
If attributeToRemove.ApplicationSyntaxReference Is Nothing Then
Throw New ArgumentException("attributeToRemove")
End If
Dim attributeSyntaxToRemove = attributeToRemove.ApplicationSyntaxReference.GetSyntax(cancellationToken)
Return RemoveAttribute(destination, attributeSyntaxToRemove, options, cancellationToken)
End Function
Public Overrides Function RemoveAttribute(Of TDeclarationNode As SyntaxNode)(destination As TDeclarationNode, attributeToRemove As SyntaxNode, options As CodeGenerationOptions, cancellationToken As CancellationToken) As TDeclarationNode
If attributeToRemove Is Nothing Then
Throw New ArgumentException("attributeToRemove")
End If
' Removed node could be AttributeSyntax or AttributeListSyntax.
Dim attributeRemoved As Boolean = False
Dim positionOfRemovedNode As Integer = -1
Dim triviaOfRemovedNode As SyntaxTriviaList = Nothing
' Handle most cases
Dim member = TryCast(destination, StatementSyntax)
If member IsNot Nothing Then
Dim newAttributeLists = RemoveAttributeFromAttributeLists(member.GetAttributes(), attributeToRemove, options, attributeRemoved, positionOfRemovedNode, triviaOfRemovedNode)
VerifyAttributeRemoved(attributeRemoved)
Dim newMember = member.WithAttributeLists(newAttributeLists)
Return Cast(Of TDeclarationNode)(AppendTriviaAtPosition(newMember, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode))
End If
' Handle global attributes
Dim compilationUnit = TryCast(destination, CompilationUnitSyntax)
If compilationUnit IsNot Nothing Then
Dim attributeStatements = compilationUnit.Attributes
Dim newAttributeStatements = RemoveAttributeFromAttributeStatements(attributeStatements, attributeToRemove, options, attributeRemoved, positionOfRemovedNode, triviaOfRemovedNode)
VerifyAttributeRemoved(attributeRemoved)
Dim newCompilationUnit = compilationUnit.WithAttributes(newAttributeStatements)
Return Cast(Of TDeclarationNode)(AppendTriviaAtPosition(newCompilationUnit, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode))
End If
' Handle parameters
Dim parameter = TryCast(destination, ParameterSyntax)
If parameter IsNot Nothing Then
Dim newAttributeLists = RemoveAttributeFromAttributeLists(parameter.AttributeLists, attributeToRemove, options, attributeRemoved, positionOfRemovedNode, triviaOfRemovedNode)
VerifyAttributeRemoved(attributeRemoved)
Dim newParameter = parameter.WithAttributeLists(newAttributeLists)
Return Cast(Of TDeclarationNode)(AppendTriviaAtPosition(newParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode))
End If
Return destination
End Function
Private Shared Function RemoveAttributeFromAttributeLists(attributeLists As SyntaxList(Of AttributeListSyntax), attributeToRemove As SyntaxNode, options As CodeGenerationOptions,
<Out> ByRef attributeRemoved As Boolean, <Out> ByRef positionOfRemovedNode As Integer, <Out> ByRef triviaOfRemovedNode As SyntaxTriviaList) As SyntaxList(Of AttributeListSyntax)
For Each attributeList In attributeLists
Dim attributes = attributeList.Attributes
If attributes.Any(Function(a) a Is attributeToRemove) Then
attributeRemoved = True
Dim trivia As IEnumerable(Of SyntaxTrivia) = Nothing
Dim newAttributeLists As IEnumerable(Of AttributeListSyntax) = Nothing
If attributes.Count = 1 Then
' Remove the entire attribute list.
ComputePositionAndTriviaForRemoveAttributeList(attributeList, Function(t As SyntaxTrivia) t.IsKind(SyntaxKind.EndOfLineTrivia), positionOfRemovedNode, trivia)
newAttributeLists = attributeLists.Where(Function(aList) aList IsNot attributeList)
Else
' Remove just the given attribute from the attribute list.
ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, Function(t As SyntaxToken) t.IsKind(SyntaxKind.CommaToken), positionOfRemovedNode, trivia)
Dim newAttributes = SyntaxFactory.SeparatedList(attributes.Where(Function(a) a IsNot attributeToRemove))
Dim newAttributeList = attributeList.WithAttributes(newAttributes)
newAttributeLists = attributeLists.Select(Function(attrList) If(attrList Is attributeList, newAttributeList, attrList))
End If
triviaOfRemovedNode = trivia.ToSyntaxTriviaList()
Return SyntaxFactory.List(newAttributeLists)
End If
Next
attributeRemoved = False
Return attributeLists
End Function
Private Shared Function RemoveAttributeFromAttributeStatements(attributeStatements As SyntaxList(Of AttributesStatementSyntax), attributeToRemove As SyntaxNode, options As CodeGenerationOptions,
<Out> ByRef attributeRemoved As Boolean, <Out> ByRef positionOfRemovedNode As Integer, <Out> ByRef triviaOfRemovedNode As SyntaxTriviaList) As SyntaxList(Of AttributesStatementSyntax)
For Each attributeStatement In attributeStatements
Dim attributeLists = attributeStatement.AttributeLists
Dim newAttributeLists = RemoveAttributeFromAttributeLists(attributeLists, attributeToRemove, options, attributeRemoved, positionOfRemovedNode, triviaOfRemovedNode)
If attributeRemoved Then
Dim newAttributeStatement = attributeStatement.WithAttributeLists(newAttributeLists)
Return SyntaxFactory.List(attributeStatements.Select(Function(attrStatement) If(attrStatement Is attributeStatement, newAttributeStatement, attrStatement)))
End If
Next
attributeRemoved = False
Return attributeStatements
End Function
Private Shared Sub VerifyAttributeRemoved(attributeRemoved As Boolean)
If Not attributeRemoved Then
Throw New ArgumentException("attributeToRemove")
End If
End Sub
Public Overrides Function AddStatements(Of TDeclarationNode As SyntaxNode)(
destinationMember As TDeclarationNode,
statements As IEnumerable(Of SyntaxNode),
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As TDeclarationNode
Dim methodBlock = TryCast(destinationMember, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
Dim allStatements = methodBlock.Statements.Concat(StatementGenerator.GenerateStatements(statements))
Dim result As Object
Select Case methodBlock.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
result = DirectCast(methodBlock, MethodBlockSyntax).WithStatements(SyntaxFactory.List(allStatements))
Case SyntaxKind.ConstructorBlock
result = DirectCast(methodBlock, ConstructorBlockSyntax).WithStatements(SyntaxFactory.List(allStatements))
Case SyntaxKind.OperatorBlock
result = DirectCast(methodBlock, OperatorBlockSyntax).WithStatements(SyntaxFactory.List(allStatements))
Case Else
result = DirectCast(methodBlock, AccessorBlockSyntax).WithStatements(SyntaxFactory.List(allStatements))
End Select
Return DirectCast(DirectCast(result, Object), TDeclarationNode)
Else
Return AddStatementsWorker(destinationMember, statements, options, cancellationToken)
End If
End Function
Private Function AddStatementsWorker(Of TDeclarationNode As SyntaxNode)(
destinationMember As TDeclarationNode,
statements As IEnumerable(Of SyntaxNode),
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As TDeclarationNode
Dim location = options.BestLocation
CheckLocation(destinationMember, location)
Dim token = location.FindToken(cancellationToken)
Dim oldBlock = token.Parent.GetContainingMultiLineExecutableBlocks().First
Dim oldBlockStatements = oldBlock.GetExecutableBlockStatements()
Dim oldBlockStatementsSet = oldBlockStatements.ToSet()
Dim oldStatement = token.Parent.GetAncestorsOrThis(Of StatementSyntax)().First(AddressOf oldBlockStatementsSet.Contains)
Dim oldStatementIndex = oldBlockStatements.IndexOf(oldStatement)
Dim statementArray = statements.OfType(Of StatementSyntax).ToArray()
Dim newBlock As SyntaxNode
If options.BeforeThisLocation IsNot Nothing Then
Dim strippedTrivia As IEnumerable(Of SyntaxTrivia) = Nothing
Dim newStatement = oldStatement.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(strippedTrivia)
statementArray(0) = statementArray(0).WithLeadingTrivia(strippedTrivia)
newBlock = oldBlock.ReplaceNode(oldStatement, newStatement)
newBlock = newBlock.ReplaceStatements(newBlock.GetExecutableBlockStatements().InsertRange(oldStatementIndex, statementArray))
Else
newBlock = oldBlock.ReplaceStatements(oldBlockStatements.InsertRange(oldStatementIndex + 1, statementArray))
End If
Return destinationMember.ReplaceNode(oldBlock, newBlock)
End Function
Public Overrides Function CreateMethodDeclaration(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxNode
If method.IsConstructor() Then
Return ConstructorGenerator.GenerateConstructorDeclaration(method, destination, options)
Else
Return MethodGenerator.GenerateMethodDeclaration(method, destination, options)
End If
End Function
Public Overrides Function CreateEventDeclaration([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxNode
Return EventGenerator.GenerateEventDeclaration([event], destination, options)
End Function
Public Overrides Function CreateFieldDeclaration(field As IFieldSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxNode
If destination = CodeGenerationDestination.EnumType Then
Return EnumMemberGenerator.GenerateEnumMemberDeclaration(field, Nothing, options)
Else
Return FieldGenerator.GenerateFieldDeclaration(field, destination, options)
End If
End Function
Public Overrides Function CreatePropertyDeclaration([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxNode
Return PropertyGenerator.GeneratePropertyDeclaration([property], destination, options)
End Function
Public Overrides Function CreateNamedTypeDeclaration(namedType As INamedTypeSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxNode
Return NamedTypeGenerator.GenerateNamedTypeDeclaration(Me, namedType, options)
End Function
Public Overrides Function CreateNamespaceDeclaration([namespace] As INamespaceSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxNode
Return NamespaceGenerator.GenerateNamespaceDeclaration(Me, [namespace], options)
End Function
Private Overloads Shared Function UpdateDeclarationModifiers(Of TDeclarationNode As SyntaxNode)(declaration As TDeclarationNode, computeNewModifiersList As Func(Of SyntaxTokenList, SyntaxTokenList), options As CodeGenerationOptions, cancellationToken As CancellationToken) As TDeclarationNode
' Handle type declarations
Dim typeStatementSyntax = TryCast(declaration, TypeStatementSyntax)
If typeStatementSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(typeStatementSyntax.WithModifiers(computeNewModifiersList(typeStatementSyntax.Modifiers)))
End If
' Handle enum declarations
Dim enumStatementSyntax = TryCast(declaration, EnumStatementSyntax)
If enumStatementSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(enumStatementSyntax.WithModifiers(computeNewModifiersList(enumStatementSyntax.Modifiers)))
End If
' Handle methods
Dim methodBaseSyntax = TryCast(declaration, MethodBaseSyntax)
If methodBaseSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(methodBaseSyntax.WithModifiers(computeNewModifiersList(methodBaseSyntax.Modifiers)))
End If
' Handle Incomplete Members
Dim incompleteMemberSyntax = TryCast(declaration, IncompleteMemberSyntax)
If incompleteMemberSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(incompleteMemberSyntax.WithModifiers(computeNewModifiersList(incompleteMemberSyntax.Modifiers)))
End If
' Handle fields
Dim fieldDeclarationSyntax = TryCast(declaration, FieldDeclarationSyntax)
If fieldDeclarationSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(fieldDeclarationSyntax.WithModifiers(computeNewModifiersList(fieldDeclarationSyntax.Modifiers)))
End If
' Handle parameters
Dim parameterSyntax = TryCast(declaration, ParameterSyntax)
If parameterSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(parameterSyntax.WithModifiers(computeNewModifiersList(parameterSyntax.Modifiers)))
End If
' Handle local declarations
Dim localDeclarationStatementSyntax = TryCast(declaration, LocalDeclarationStatementSyntax)
If localDeclarationStatementSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(localDeclarationStatementSyntax.WithModifiers(computeNewModifiersList(localDeclarationStatementSyntax.Modifiers)))
End If
Return declaration
End Function
Public Overrides Function UpdateDeclarationModifiers(Of TDeclarationNode As SyntaxNode)(declaration As TDeclarationNode, newModifiers As IEnumerable(Of SyntaxToken), options As CodeGenerationOptions, cancellationToken As CancellationToken) As TDeclarationNode
Dim computeNewModifiersList As Func(Of SyntaxTokenList, SyntaxTokenList) = Function(modifiersList As SyntaxTokenList)
Return SyntaxFactory.TokenList(newModifiers)
End Function
Return UpdateDeclarationModifiers(declaration, computeNewModifiersList, options, cancellationToken)
End Function
Public Overrides Function UpdateDeclarationAccessibility(Of TDeclarationNode As SyntaxNode)(declaration As TDeclarationNode, newAccesibility As Accessibility, options As CodeGenerationOptions, cancellationToken As CancellationToken) As TDeclarationNode
Dim computeNewModifiersList As Func(Of SyntaxTokenList, SyntaxTokenList) = Function(modifiersList As SyntaxTokenList)
Return UpdateDeclarationAccessibility(modifiersList, newAccesibility, options)
End Function
Return UpdateDeclarationModifiers(declaration, computeNewModifiersList, options, cancellationToken)
End Function
Private Overloads Shared Function UpdateDeclarationAccessibility(modifiersList As SyntaxTokenList, newAccesibility As Accessibility, options As CodeGenerationOptions) As SyntaxTokenList
Dim newModifierTokens = New List(Of SyntaxToken)()
VisualBasicCodeGenerationHelpers.AddAccessibilityModifiers(newAccesibility, newModifierTokens, CodeGenerationDestination.Unspecified, options, Accessibility.NotApplicable)
If newModifierTokens.Count = 0 Then
Return modifiersList
End If
Return SyntaxFactory.TokenList(GetUpdatedDeclarationAccessibilityModifiers(newModifierTokens, modifiersList, Function(modifier As SyntaxToken) SyntaxFacts.IsAccessibilityModifier(modifier.Kind())))
End Function
Private Function UpdateSimpleAsClause(asClause As SimpleAsClauseSyntax, newType As ITypeSymbol) As SimpleAsClauseSyntax
Dim newTypeSyntax = newType.GenerateTypeSyntax().
WithLeadingTrivia(asClause.GetLeadingTrivia()).
WithTrailingTrivia(asClause.GetTrailingTrivia())
Return DirectCast(asClause, SimpleAsClauseSyntax).WithType(newTypeSyntax)
End Function
Private Function UpdateAsClause(asClause As AsClauseSyntax, newType As ITypeSymbol) As AsClauseSyntax
Dim newTypeSyntax = newType.GenerateTypeSyntax().
WithLeadingTrivia(asClause.GetLeadingTrivia()).
WithTrailingTrivia(asClause.GetTrailingTrivia())
Select Case asClause.Kind
Case SyntaxKind.SimpleAsClause
Return DirectCast(asClause, SimpleAsClauseSyntax).WithType(newTypeSyntax)
Case Else
Dim asNewClause = DirectCast(asClause, AsNewClauseSyntax)
Dim newExpression = asNewClause.NewExpression
Dim updatedNewExpression As NewExpressionSyntax
Select Case newExpression.Kind
Case SyntaxKind.ArrayCreationExpression
updatedNewExpression = DirectCast(newExpression, ArrayCreationExpressionSyntax).WithType(newTypeSyntax)
Case SyntaxKind.ObjectCreationExpression
updatedNewExpression = DirectCast(newExpression, ObjectCreationExpressionSyntax).WithType(newTypeSyntax)
Case Else
Return asClause
End Select
Return asNewClause.WithNewExpression(updatedNewExpression)
End Select
End Function
Public Overrides Function UpdateDeclarationType(Of TDeclarationNode As SyntaxNode)(declaration As TDeclarationNode, newType As ITypeSymbol, options As CodeGenerationOptions, cancellationToken As CancellationToken) As TDeclarationNode
Dim syntaxNode = TryCast(declaration, VisualBasicSyntaxNode)
If syntaxNode Is Nothing Then
Return declaration
End If
Select Case syntaxNode.Kind
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim methodStatementSyntax = DirectCast(syntaxNode, MethodStatementSyntax)
Dim newAsClause = UpdateSimpleAsClause(methodStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(methodStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement
Dim declareStatementSyntax = DirectCast(syntaxNode, DeclareStatementSyntax)
Dim newAsClause = UpdateSimpleAsClause(declareStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(declareStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement
Dim delegateStatementSyntax = DirectCast(syntaxNode, DelegateStatementSyntax)
Dim newAsClause = UpdateSimpleAsClause(delegateStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(delegateStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.EventStatement
Dim eventStatementSyntax = DirectCast(syntaxNode, EventStatementSyntax)
Dim newAsClause = UpdateSimpleAsClause(eventStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(eventStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.OperatorStatement
Dim operatorStatementSyntax = DirectCast(syntaxNode, OperatorStatementSyntax)
Dim newAsClause = UpdateSimpleAsClause(operatorStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(operatorStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.PropertyStatement
Dim propertyStatementSyntax = DirectCast(syntaxNode, PropertyStatementSyntax)
Dim newAsClause = UpdateAsClause(propertyStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(propertyStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.VariableDeclarator
Dim variableDeclaratorSyntax = DirectCast(syntaxNode, VariableDeclaratorSyntax)
Dim newAsClause = UpdateAsClause(variableDeclaratorSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(variableDeclaratorSyntax.WithAsClause(newAsClause))
Case SyntaxKind.Parameter
Dim parameterSyntax = DirectCast(syntaxNode, ParameterSyntax)
Dim newAsClause = UpdateSimpleAsClause(parameterSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(parameterSyntax.WithAsClause(newAsClause))
Case SyntaxKind.CatchStatement
Dim catchStatementSyntax = DirectCast(syntaxNode, CatchStatementSyntax)
Dim newAsClause = UpdateSimpleAsClause(catchStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(catchStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.FunctionLambdaHeader, SyntaxKind.SubLambdaHeader
Dim lambdaHeaderSyntax = DirectCast(syntaxNode, LambdaHeaderSyntax)
Dim newAsClause = UpdateSimpleAsClause(lambdaHeaderSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(lambdaHeaderSyntax.WithAsClause(newAsClause))
Case Else
Return declaration
End Select
End Function
Public Overrides Function UpdateDeclarationMembers(Of TDeclarationNode As SyntaxNode)(declaration As TDeclarationNode, newMembers As IList(Of ISymbol), Optional options As CodeGenerationOptions = Nothing, Optional cancellationToken As CancellationToken = Nothing) As TDeclarationNode
Dim syntaxNode = TryCast(declaration, VisualBasicSyntaxNode)
If syntaxNode IsNot Nothing Then
Select Case syntaxNode.Kind
Case SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock
Return Cast(Of TDeclarationNode)(NamedTypeGenerator.UpdateNamedTypeDeclaration(Me, DirectCast(syntaxNode, StatementSyntax), newMembers, options, cancellationToken))
Case SyntaxKind.CompilationUnit, SyntaxKind.NamespaceBlock
Return Cast(Of TDeclarationNode)(NamespaceGenerator.UpdateCompilationUnitOrNamespaceDeclaration(Me, syntaxNode, newMembers, options, cancellationToken))
End Select
End If
Return declaration
End Function
End Class
End Namespace
| {
"pile_set_name": "Github"
} |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Management.Automation;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Azure.PowerShell.Cmdlets.DedicatedHsm.Runtime
{
using NextDelegate = Func<HttpRequestMessage, CancellationToken, Action, Func<string, CancellationToken, Func<EventArgs>, Task>, Task<HttpResponseMessage>>;
using SignalDelegate = Func<string, CancellationToken, Func<EventArgs>, Task>;
public class CmdInfoHandler
{
private readonly string processRecordId;
private readonly string parameterSetName;
private readonly InvocationInfo invocationInfo;
public CmdInfoHandler(string processRecordId, InvocationInfo invocationInfo, string parameterSetName)
{
this.processRecordId = processRecordId;
this.parameterSetName = parameterSetName;
this.invocationInfo = invocationInfo;
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token, Action cancel, SignalDelegate signal, NextDelegate next)
{
request.Headers.Add("x-ms-client-request-id", processRecordId);
request.Headers.Add("CommandName", invocationInfo?.InvocationName);
request.Headers.Add("FullCommandName", invocationInfo?.MyCommand?.Name);
request.Headers.Add("ParameterSetName", parameterSetName);
// continue with pipeline.
return next(request, token, cancel, signal);
}
}
}
| {
"pile_set_name": "Github"
} |
package com.thirtydegreesray.openhub.ui.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.thirtydegreesray.openhub.AppData;
import com.thirtydegreesray.openhub.R;
import com.thirtydegreesray.openhub.common.GlideApp;
import com.thirtydegreesray.openhub.inject.component.AppComponent;
import com.thirtydegreesray.openhub.inject.component.DaggerActivityComponent;
import com.thirtydegreesray.openhub.inject.module.ActivityModule;
import com.thirtydegreesray.openhub.mvp.contract.IIssueDetailContract;
import com.thirtydegreesray.openhub.mvp.model.Issue;
import com.thirtydegreesray.openhub.mvp.model.IssueEvent;
import com.thirtydegreesray.openhub.mvp.presenter.IssueDetailPresenter;
import com.thirtydegreesray.openhub.ui.activity.base.BaseActivity;
import com.thirtydegreesray.openhub.ui.fragment.IssueTimelineFragment;
import com.thirtydegreesray.openhub.ui.fragment.base.ListFragment;
import com.thirtydegreesray.openhub.ui.widget.ZoomAbleFloatingActionButton;
import com.thirtydegreesray.openhub.util.AppOpener;
import com.thirtydegreesray.openhub.util.AppUtils;
import com.thirtydegreesray.openhub.util.BundleHelper;
import com.thirtydegreesray.openhub.util.PrefUtils;
import butterknife.BindView;
import butterknife.OnClick;
/**
* Created by ThirtyDegreesRay on 2017/9/26 19:27:11
*/
public class IssueDetailActivity extends BaseActivity<IssueDetailPresenter>
implements IIssueDetailContract.View,
ListFragment.ListScrollListener{
public static void show(@NonNull Activity activity, @NonNull View avatarView,
@NonNull View titleView, @NonNull Issue issue) {
Intent intent = new Intent(activity, IssueDetailActivity.class);
Pair<View, String> avatarPair = Pair.create(avatarView, "userAvatar");
Pair<View, String> titlePair = Pair.create(titleView, "issueTitle");
ActivityOptionsCompat optionsCompat = ActivityOptionsCompat
.makeSceneTransitionAnimation(activity, avatarPair, titlePair);
intent.putExtras(BundleHelper.builder().put("issue", issue).build());
activity.startActivity(intent, optionsCompat.toBundle());
}
public static void show(@NonNull Activity activity, @NonNull Issue issue) {
Intent intent = new Intent(activity, IssueDetailActivity.class);
intent.putExtras(BundleHelper.builder().put("issue", issue).build());
activity.startActivity(intent);
}
public static void show(@NonNull Activity activity, @NonNull String issueUrl) {
Intent intent = new Intent(activity, IssueDetailActivity.class);
intent.putExtras(BundleHelper.builder().put("issueUrl", issueUrl).build());
activity.startActivity(intent);
}
public static void show(@NonNull Activity activity, @NonNull String owner,
@NonNull String repoName, int issueNumber) {
Intent intent = createIntent(activity, owner, repoName, issueNumber);
activity.startActivity(intent);
}
public static Intent createIntent(@NonNull Activity activity, @NonNull String owner,
@NonNull String repoName, int issueNumber) {
return new Intent(activity, IssueDetailActivity.class)
.putExtras(BundleHelper.builder()
.put("owner", owner)
.put("repoName", repoName)
.put("issueNumber", issueNumber).build());
}
@BindView(R.id.user_avatar) ImageView userImageView;
@BindView(R.id.issue_title) TextView issueTitle;
@BindView(R.id.issue_state_img) ImageView issueStateImg;
@BindView(R.id.issue_state_text) TextView issueStateText;
@BindView(R.id.comment_bn) ZoomAbleFloatingActionButton commentBn;
@BindView(R.id.edit_bn) FloatingActionButton editBn;
@BindView(R.id.loader) ProgressBar loader;
private IssueTimelineFragment issueTimelineFragment;
private final int ADD_COMMENT_REQUEST_CODE = 100;
public static final int EDIT_COMMENT_REQUEST_CODE = 101;
public static final int EDIT_ISSUE_REQUEST_CODE = 102;
@Override
protected void setupActivityComponent(AppComponent appComponent) {
DaggerActivityComponent.builder()
.appComponent(appComponent)
.activityModule(new ActivityModule(this))
.build()
.inject(this);
}
@Override
protected int getContentView() {
return R.layout.activity_issue_detail;
}
@Override
protected void initView(Bundle savedInstanceState) {
super.initView(savedInstanceState);
setToolbarBackEnable();
setToolbarTitle(getString(R.string.issue));
commentBn.setVisibility(View.GONE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (mPresenter.getIssue() != null) {
getMenuInflater().inflate(R.menu.menu_issue_detail, menu);
boolean isCanToggle = AppData.INSTANCE.getLoggedUser().getLogin()
.equals(mPresenter.getIssue().getUser().getLogin()) ||
AppData.INSTANCE.getLoggedUser().getLogin()
.equals(mPresenter.getIssue().getRepoAuthorName());
boolean isOpen = mPresenter.getIssue().getState().equals(Issue.IssueState.open);
if (isCanToggle) {
MenuItem item = menu.findItem(R.id.action_issue_toggle);
item.setTitle(isOpen ? R.string.close : R.string.reopen);
} else {
menu.removeItem(R.id.action_issue_toggle);
}
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
editBn.setVisibility(View.GONE);
supportFinishAfterTransition();
return true;
case R.id.action_open_in_browser:
AppOpener.openInCustomTabsOrBrowser(getActivity(), mPresenter.getIssue().getHtmlUrl());
return true;
case R.id.action_share:
AppOpener.shareText(getActivity(), mPresenter.getIssue().getHtmlUrl());
return true;
case R.id.action_copy_url:
AppUtils.copyToClipboard(getActivity(), mPresenter.getIssue().getHtmlUrl());
return true;
case R.id.action_issue_toggle:
showToggleIssueWarning();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void showIssue(final Issue issue) {
setToolbarTitle(getString(R.string.issue).concat(" #").concat(String.valueOf(issue.getNumber())));
GlideApp.with(getActivity())
.load(issue.getUser().getAvatarUrl())
.onlyRetrieveFromCache(!PrefUtils.isLoadImageEnable())
.into(userImageView);
issueTitle.setText(issue.getTitle());
commentBn.setVisibility(issue.isLocked() ? View.GONE : View.VISIBLE);
String commentStr = String.valueOf(issue.getCommentNum()).concat(" ")
.concat(getString(R.string.comments).toLowerCase());
if (Issue.IssueState.open.equals(issue.getState())) {
issueStateImg.setImageResource(R.drawable.ic_issues);
issueStateText.setText(getString(R.string.open).concat(" ").concat(commentStr));
} else {
issueStateImg.setImageResource(R.drawable.ic_issues_closed);
issueStateText.setText(getString(R.string.closed).concat(" ").concat(commentStr));
}
invalidateOptionsMenu();
if (issueTimelineFragment == null) {
issueTimelineFragment = IssueTimelineFragment.create(issue);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (!isAlive) return;
getSupportFragmentManager()
.beginTransaction()
.add(R.id.container, issueTimelineFragment)
.commitAllowingStateLoss();
}
}, 500);
issueTimelineFragment.setListScrollListener(this);
}
String loggedUser = AppData.INSTANCE.getLoggedUser().getLogin();
boolean editAble = loggedUser.equals(issue.getUser().getLogin()) ||
loggedUser.equals(issue.getRepoAuthorName());
editBn.setVisibility(editAble ? View.VISIBLE : View.GONE);
commentBn.setVisibility(View.VISIBLE);
}
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
if (fragment instanceof IssueTimelineFragment) {
issueTimelineFragment = (IssueTimelineFragment) fragment;
}
}
@Override
public void showAddedComment(@NonNull IssueEvent event) {
issueTimelineFragment.addComment(event);
}
@Override
public void showAddCommentPage(@Nullable String text) {
MarkdownEditorActivity.show(getActivity(), R.string.comment, ADD_COMMENT_REQUEST_CODE,
text, issueTimelineFragment == null ? null : issueTimelineFragment.getIssueUsersExceptMe());
}
@OnClick(R.id.comment_bn)
public void onCommentBnClicked() {
showAddCommentPage(null);
}
@OnClick(R.id.edit_bn)
public void onEditBnClicked() {
EditIssueActivity.showForEdit(getActivity(), mPresenter.getIssue(), EDIT_ISSUE_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == ADD_COMMENT_REQUEST_CODE) {
String text = data.getExtras().getString("text");
mPresenter.addComment(text);
return;
} else if (requestCode == EDIT_COMMENT_REQUEST_CODE) {
String text = data.getExtras().getString("text");
issueTimelineFragment.onEditComment(text);
return;
} else if (requestCode == EDIT_ISSUE_REQUEST_CODE) {
Issue issue = data.getParcelableExtra("issue");
mPresenter.setIssue(issue);
issueTitle.setText(issue.getTitle());
issueTimelineFragment.onEditIssue(issue);
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onBackPressed() {
editBn.setVisibility(View.GONE);
super.onBackPressed();
}
@Override
public void showLoading() {
super.showLoading();
loader.setVisibility(View.VISIBLE);
}
@Override
public void hideLoading() {
super.hideLoading();
loader.setVisibility(View.GONE);
}
@OnClick(R.id.user_avatar)
public void onUserAvatarClick() {
if (mPresenter.getIssue() != null) {
Issue issue = mPresenter.getIssue();
ProfileActivity.show(getActivity(), userImageView,
issue.getUser().getLogin(), issue.getUser().getAvatarUrl());
}
}
@Override
protected void onToolbarDoubleClick() {
super.onToolbarDoubleClick();
if (issueTimelineFragment != null) issueTimelineFragment.scrollToTop();
}
@Override
public void onScrollUp() {
commentBn.zoomIn();
}
@Override
public void onScrollDown() {
commentBn.zoomOut();
}
private void showToggleIssueWarning(){
String msg = String.format(getString(R.string.toggle_issue_warning),
mPresenter.getIssue().getState().equals(Issue.IssueState.open) ?
getString(R.string.close) : getString(R.string.reopen));
new AlertDialog.Builder(getActivity())
.setTitle(R.string.warning_dialog_tile)
.setMessage(msg)
.setPositiveButton(R.string.confirm, (dialog, which) -> mPresenter.toggleIssueState())
.setNegativeButton(R.string.cancel, null)
.show();
}
}
| {
"pile_set_name": "Github"
} |
{
"data": [{
"id": "1",
"type": "foos",
"attributes": {
"string-attribute": "stringAttributeValue",
"integer-attribute": 10,
"float-attribute": 5.5,
"boolean-attribute": true,
"nil-attribute": null,
"date-attribute": "1970-01-01T01:00:00.000+01:00"
},
"links": {
"self": "http://example.com/foos/1"
},
"relationships": {
"to-one-attribute": {
"links": {
"self": "http://example.com/foos/1/relationships/to-one-attribute",
"related": "http://example.com/bars/10"
}
},
"to-many-attribute": {
"links": {
"self": "http://example.com/foos/1/relationships/to-many-attribute",
"related": "http://example.com/bars/11,12"
}
}
}
}, {
"id": "2",
"type": "foos",
"attributes": {
"string-attribute": "stringAttributeValue",
"integer-attribute": 10,
"float-attribute": 5.5,
"boolean-attribute": true,
"nil-attribute": null,
"date-attribute": "1970-01-01T01:00:00.000+01:00"
},
"links": {
"self": "http://example.com/foos/1"
},
"relationships": {
"to-one-attribute": {
"links": {
"self": "http://example.com/foos/1/relationships/to-one-attribute",
"related": "http://example.com/bars/10"
}
},
"to-many-attribute": {
"links": {
"self": "http://example.com/foos/1/relationships/to-many-attribute",
"related": "http://example.com/bars/11,12"
}
}
}
}]
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration> | {
"pile_set_name": "Github"
} |
# @asymmetrik/leaflet-d3
[![Build Status][travis-image]][travis-url]
> Leaflet D3
> Provides a collection of [D3.js](http://d3js.org) based visualization plugins for [Leaflet](http://leafletjs.com/).
> Now supports D3 v5
## Table of Contents
- [Install](#install)
- [Usage](#usage)
- [Hexbins API](#hexbins-api)
- [Pings API](#pings-api)
- [Changelog](#changelog)
- [Contribute](#contribute)
- [License](#license)
- [Credits](#credits)
## Install
Install the package and its peer dependencies via npm:
```
npm install d3 d3-hexbin leaflet
```
If you want to grab the source files directly without using npm, or you want to run the examples, you can build the dist files directly.
Simply check out the repository, and then build it with the following commands:
```
git clone git@github.com:Asymmetrik/leaflet-d3.git
cd leaflet-d3
npm install
npm run build
```
## Usage
### Hexbins
Create dynamic hexbin-based heatmaps on Leaflet maps.
This plugin is based on [the work of Steven Hall](http://www.delimited.io/blog/2013/12/1/hexbins-with-d3-and-leaflet-maps).
The primary difference is that this plugin leverages the data-binding power of d3 to allow you to dynamically update the data and visualize the transitions.
<img src="https://cloud.githubusercontent.com/assets/480701/4594707/d995541a-5091-11e4-9955-5938b1cb977a.png" alt="map with hexbins"/>
Live Demo: [JSFiddle](http://jsfiddle.net/acjnbu8t/embedded/result/)
To use, simply declare a hexbin layer and add it to your map.
You can then add data to the layer.
```js
// Create the hexbin layer and set all of the accessor functions
var hexLayer = L.hexbinLayer().addTo(map);
// Set the data (can be set multiple times)
hexLayer.data([[lng1, lat1], [lng2, lat2], ... [lngN, latN]]);
```
#### Styling
You will likely want to apply your own styles to the hexbin hexagons themselves. To do so, use the ```hexbin-hexagon``` class.
See the following example:
```css
.hexbin-hexagon {
stroke: #000;
stroke-width: .5px;
}
```
#### Tooltips
You have a couple options when it comes to providing tooltips for your users.
First, you can register for the appropriate hover events and manually access/manipulate the dom to show/hide tooltips.
Second, you can leverage the built-in hover handlers, which try to encapsulate a lot of this behavior.
```
var hexLayer = L.hexbinLayer()
.hoverHandler(L.HexbinHoverHandler.tooltip());
```
This handler, combined with CSS, can be used to show a tooltip and highlight the hovered hexbin.
In the following example, we change the stroke color and show a tooltip.
```
.hexbin-container:hover .hexbin-hexagon {
transition: 200ms;
stroke: orange;
stroke-width: 1px;
stroke-opacity: 1;
}
.hexbin-tooltip {
padding: 8px;
border-radius: 4px;
border: 1px solid black;
background-color: white;
}
```
There's more documentation on how to customize the behavior of the hover handlers in the API docs below.
#### Special Notes
**Applying Durations:**
If your data is transforming faster than the transition duration, you may encounter unexpected behavior.
This is an artifact of how transitions interact with and cancel each other.
You should reduce the transition duration or eliminate it entirely if you are going to be using this plugin in a realtime manner.
**Color Scales:**
To use a polylinear color scale, simply provide more than two colors in the range. The domain cardinality will be adjusted automatically.
A minimum of two values is required in the color range, but a single-color range is possible by using `['blue', 'blue']` for example.
See the examples to see how diverging and discrete color scales can be used.
### Pings
Create realtime animated drops/pings/blips on a map.
This plugin can be used to indicate a transient event, such as a real-time occurrance of an event at a specific geographical location.
<img src="https://cloud.githubusercontent.com/assets/480701/4890582/5b6781ae-63a0-11e4-8e45-236eb7c75b85.gif" alt="map with pings"/>
**Live Demo:** [JSFiddle](http://jsfiddle.net/reblace/7jfhLgnq/embedded/result/)
To use, simply declare a ping layer and add it to your map.
You can then add data by calling the ping() method.
```js
// Create the ping layer and add it to the map
var pingLayer = L.pingLayer().addTo(map);
// Submit data so that it shows up as a ping with an optional per-ping css class
pingLayer.ping([ 38.991709, -76.886109 ], 'myCustomCssClass');
```
#### Styling
You will likely want to apply your own styles to the pings themselves. To do so, use the ```ping``` class.
See the following example:
```css
.ping {
fill: steelblue;
stroke: #222;
stroke-width: .5px;
}
```
## Hexbins API
### L.hexbinLayer(options?: {}): L.HexbinLayer
Create a Leaflet map layer for visualizing data using colored/sized hexbin-based bins.
```js
var hexLayer = L.hexbinLayer().addTo(map);
```
### options
Set of options for customizing the appearance/behavior of the hexbin layer.
Example:
```js
var options = {
radius : 12,
opacity: 0.5,
duration: 200,
colorScaleExtent: [ 1, undefined ],
radiusScaleExtent: [ 1, undefined ],
colorDomain: null,
radiusDomain: null,
colorRange: [ '#f7fbff', '#08306b' ],
radiusRange: [ 5, 12 ],
pointerEvents: 'all'
};
```
#### radius
Default: 12 - Sets the radius on the hexbin layer (see below for details).
#### opacity
Default: 0.6 - Sets the opacity on the hexbin layer (see below for details).
#### duration
Default: 200 - Sets the transition duration for the hexbin layer (see below for details).
#### colorScaleExtent
Default: [ 1, undefined ] - Sets the extent of the color scale for the hexbin layer (see below for details).
#### radiusScaleExtent
Default: [ 1, undefined ] - This is the same exact configuration option as ```colorScaleExtent```, only applied to the radius extent.
#### colorDomain
Default: null - This is used to override the default behavior, which is to derive the color domain from the data.
Normally, you can tweak the generation of the color domain using the colorScaleExtent option.
However, if you want to set a completely custom domain, you can provide it as an array of values with this option.
The array of values will be passed directly into the domain of the color scale before rendering.
#### radiusDomain
Default: null - This is used to override the default behavior, which is to derive the radius domain from the data.
Normally, you can tweak the generation of the radius domain using the radiusScaleExtent option.
However, if you want to set a completely custom domain, you can provide it as an array of values with this option.
The array of values will be passed directly into the domain of the radius scale before rendering.
#### colorRange
Default: [ '#f7fbff', '#08306b' ] - Sets the range of the color scale used to fill the hexbins on the layer.
#### radiusRange
Default: [ 4, 12 ] - Sets the range of the radius scale used to size the hexbins on the layer.
#### pointerEvents
Default: 'all' - This value is passed directly to an element-level css style for ```pointer-events```.
You should only modify this config option if you want to change the mouse event behavior on hexbins.
This will modify when the events are propagated based on the visibility state and/or part of the hexbin being hovered.
### L.HexbinLayer
#### hexbinLayer.data(value?: any[])
Setter/getter for the data bound to the hexbin layer.
The default data schema for the hexin layer is:
```[ [ lng1, lat1 ], [ lng2, lat2 ], [ lng3, lat3 ]... [ lngN, latN ] ]```
Where the hexbin size is fixed at the radius and the color is linearly scaled and based on the bin count (the number of points contained in the bin).
#### hexbinLayer.redraw()
Triggers a redraw of the hexbin layer.
You should only need to use this function if you are modifying several aspects of the layer.
The only function in the API that automatically redraws is ```.data()```
#### hexbinLayer.radius(value?: number)
Setter/getter for the radius configuration option.
Radius of the hexagon grid cells in pixels.
This value should be a positive number.
This radius controls the radius of the hexagons used to bin the data but not necessarily to draw each individual hexbin.
#### hexbinLayer.opacity(value?: number)
Setter/getter for the opacity configuration option.
The opacity of the visible hexagons.
This value should be a number between 0 and 1.
Since we are transitioning opacity as part of d3 rendering the hexbins, this is not currently controlled by CSS.
Future iterations may make this purely CSS based with the transitions applied to groups.
#### hexbinLayer.duration(value?: number)
Setter/getter for the durations configuration option. The millisecond duration of d3 transitions between states.
This value should be a non-negative number.
A value of 0 means that transitions will be instantaneous.
*Note:* The transition duration should be set to a value lower than the minimum refresh interval of your data.
What this means is that if you are going to be updating the data for the hexbin layer every 100 ms, you should keep this duration at a value of less than 100ms.
The consequence of not doing this is that hexbins will not fully complete their transitions in between changes.
#### hexbinLayer.colorScaleExtent(value?: [ number, number ])
Setter/getter for the colorScaleExtent configuration option.
This is used to override the derived extent of the color values and is specified as a tuple of the form [ min: number, max: number ].
A value of ```undefined`` for either min or max indicates that the derived value should be retained.
What this means is we derive the color value extent of the data (the min/max values in the data array) as an array of the form [ min, max ].
Once we have that tuple, we override those values with the values provided by this config option.
For example, if the derived min/max is [5, 102] and ```colorScaleExtent``` is [ 1, undefined ], the resulting extent used as the domain of the colorScale will be [ 1, 102 ].
This setting is useful when you want to be explicit about the domain of values for the hexbins.
For example, when you want consistent color scales between multiple maps or within the same map.
#### hexbinLayer.radiusScaleExtent(value?: [ number, number ])
Setter/getter for the radiusScaleExtent configuration option.
This is the same exact configuration option as ```colorScaleExtent```, only applied to the radius extent.
#### hexbinLayer.colorRange(value?: [ number, number ])
Setter/getter for the colorRange configuration option.
This value is used to specify the range of the color scale used to determine the fill colors of the hexbins.
There are a lot of different ways you can specify the color range.
One option is monotone: ```[ '#f7fbff', '#f7fbff' ]```.
The most common option is a linear transition between two colors: ```[ '#f7fbff', '#08306b' ]```
You can also create divering and discrete color scales by providing more than two values (see the examples for details).
#### hexbinLayer.radiusRange(value?: [ number, number ])
Setter/getter for the radiusRange configuration option.
This value is used to specify the range of the radius scale used to size the drawn hexbins.
This is relevant if you are providing a custom ```radiusValue``` function and want to specify the minimum and maximum drawn hexbin size.
*Note:* Overriding this value will have no effect unless you provide a custom ```radiusValue``` function.
#### hexbinLayer.colorScale(value?: d3.scale)
Default: d3.scaleLinear - Setter/getter for the d3 scale used to map the color of each hexbin from the color value.
If you override the scale, the color range will be ignored.
#### hexbinLayer.radiusScale(value?: d3.scale)
Default: d3.scaleLinear - Setter/getter for the d3 scale used to map the radius of each hexbin from the radius value.
If you override the scale, the radius range will be ignored.
#### hexbinLayer.lng(value?: function(d, i) {})
Default: function(d) { return d[0]; } - Setter/getter for the function used to derive the value of the longitude for each object in the data array.
#### hexbinLayer.lat(value?: function(d, i) {})
Default: function(d) { return d[1]; } - Setter/getter for the function used to derive the value of the latitude for each object in the data array.
#### hexbinLayer.colorValue(value?: function(d, i) {})
Default: function(d) { return d.length; } - Setter/getter for the function used to derive the value of the color for each object in the data array.
#### hexbinLayer.radiusValue(value?: function(d, i) {})
Default: function(d) { return 1; } - Setter/getter for the function used to derive the value of the radius for each object in the data array.
#### hexbinLayer.fill(value?: function(d, i) {})
Setter/getter for the function used to derive the fill for each hexbin given the object generated by the d3 hexbin layout.
The default fill function will simply map to the colorScale, but use 'none' when there is an undefined or null value.
#### hexbinLayer.dispatch()
Getter for the d3 dispatch object that exposes mouse events for the hexbins.
Example:
```js
hexLayer.dispatch()
.on('mouseover', function(d, i) {
console.log({ type: 'mouseover', event: d, index: i, context: this });
})
.on('mouseout', function(d, i) {
console.log({ type: 'mouseout', event: d, index: i, context: this });
})
.on('click', function(d, i) {
console.log({ type: 'click', event: d, index: i, context: this });
});
```
#### hexbinLayer.hoverHandler()
Default: None - Setter/getter for the hover behavior.
Hover handlers help you customize hexbin hover behavior.
Examples include growing the size of the hexbin in various ways or showing a tooltip.
If the hover handlers don't do what you want, you can always handle events yourself or implement your own hover handler.
For more details, see the section on hover handlers below.
### L.HexbinHoverHandler
All handlers are under the ```L.HexbinHoverHandler``` namespace.
Handlers are created as follows:
```js
L.HexbinHoverHandler.ResizeFill(options)
```
Here's a basic example:
```js
// Create a hexbin layer where hexbins that are hovered will grow from their
// current radius up to the maximum radius (in this case 11)
var hexLayer = L.hexbinLayer({ duration: 400, radiusRange: [ 5, 11 ] })
.radiusValue(function(d) { return d.length; })
.hoverHandler(L.HexbinHoverHandler.resizeFill());
```
You can combine hover handlers with CSS to achieve interesting effects.
The above hover handler combined with the below CSS will grow hexbins on hover using a smooth animation
and will change the stroke to orange.
```css
.hexbin-container:hover .hexbin-hexagon {
transition: 200ms;
stroke: orange;
stroke-width: 1px;
stroke-opacity: 1;
}
```
There are several provided hover handlers and they each may take options. They are described below.
#### HoverHandler.tooltip(options)
Shows a basic tooltip centered above the hexbin.
Options:
* **tooltipContent** - function(d) { return 'tooltip content here'; }
#### HoverHandler.resizeFill()
Resize the hovered hexagon to fill the current hexbin.
No options required.
#### HoverHandler.resizeScale(options)
Resize the hovered hexagon by scaling it to be a percentage larger than the maximum drawn hexagon radius.
Options:
* **radiusScale** - provides the scale factor by which to increase the radius of the hexbin. Example: ```radiusScale: 0.5``` will result in a hovered hexbin radius that is 50% larger than the maximum hexagon radius.
#### HoverHandler.compound(options)
Combine multiple hover handlers.
Options:
* **handlers** - Array of hover handlers to combine.
#### Customizing your own Hover Handler
If you want to implement (or contribute) your own hover handler, the interface is pretty simple:
```js
L.HexbinHoverHandler.myHoverHandler = function() {
// return the handler instance
return {
mouseover: function (hexLayer, data) {
// hexLayer - reference to the L.HexbinLayer instance
// data - reference to the data bound to the hovered hexbin
// this - D3 wrapped DOM element for hovered hexbin
},
mouseout: function (hexLayer, data) {}
};
};
```
## Pings API
### L.pingLayer(options?: {}): L.PingLayer
Create a Leaflet map layer for visualizing transient event data using animated expanding circles.
```js
var pingLayer = L.pingLayer().addTo(map);
```
### options
Set of options for customizing the appearance/behavior of the ping layer.
Example:
```js
var options = {
duration: 800,
fps : 32,
opacityRange: [ 1, 0 ],
radiusRange: [ 5, 12 ]
};
```
#### duration
Default: 800 - Sets the transition duration for the ping layer (see below for details).
#### fps
Default: 32 - Sets the target framerate for the ping animation (see below for details).
#### opacityRange
Default: [ 1, 0 ] - Sets the range of the opacity scale used to fade out the pings as they age (see below for details).
#### radiusRange
Default: [ 3, 15 ] - Sets the range of the radius scale used to size the pings as they age (see below for details).
### L.PingLayer
#### pingLayer.ping(value: {})
Submit a ping to the layer.
The default data schema for the ping layer is:
```[ [ lng1, lat1 ], [ lng2, lat2 ], [ lng3, lat3 ]... [ lngN, latN ] ]```
Where the ping radius scale factor is fixed at 1.
#### pingLayer.duration(value?: number)
Setter/getter for the durations configuration option.
The millisecond duration of each ping's lifecycle.
This value should be a non-negative number.
The pings will grow from their initial size/opacity to their final size/opacity over this period of time.
After this duration, the pings are removed from the map.
#### pingLayer.fps(value?: number)
Setter/getter for the fps configuration option.
The animation loop will limit DOM changes to this frequency in order to reduce the impact to the CPU.
#### pingLayer.radiusRange(value?: [ number, number ])
Setter/getter for the radiusRange configuration option.
The start/end radius applied during each ping's lifecycle.
This value should be a tuple of size two.
The pings will start at a pixel radius equal to the first number in the tuple and animate to the second number in the tuple.
#### pingLayer.opacityRange(value?: [ number, number ])
Setter/getter for the opacityRange configuration option.
The start/end opacity state applied during each ping's lifecycle.
This value should be a tuple of size two.
The pings will start at an opacity equal to the first number in the tuple and animate to the second number in the tuple.
#### pingLayer.radiusScale(value?: d3.scale)
Default: d3.scalePow().exponent(0.35) - Setter/getter for the scale used to determine the radius during the ping lifecycle.
If you override the scale, the radius range will be ignored.
#### pingLayer.opacityScale(value?: d3.scale)
Default: d3.scaleLinear() - Setter/getter for the scale used to determine the opacity during the ping lifecycle.
If you override the scale, the opacity range will be ignored.
#### pingLayer.radiusScaleFactor(function(d) {})
Default: function(d) { return 1; } - Setter/getter for the scale factor applied to the radius of each ping.
This can be used to differentiate different events by size.
#### pingLayer.lng(value?: function(d) {})
Default: function(d) { return d[0]; } - Setter/getter for the function used to derive the value of the longitude for each object in the data array.
#### pingLayer.lat(value?: function(d) {})
Default: function(d) { return d[1]; } - Setter/getter for the function used to derive the value of the latitude for each object in the data array.
#### pingLayer.data()
Getter for the set of currently alive pings.
#### pingLayer.getActualFps()
Getter for the actual fps (based on the actual time between the last two animation frames).
## Changelog
### Version 4.x
#### 4.4.0
- Minor version updates for d3 and leaflet.
#### 4.2.0
- Corrected the algorithm that filters out hexbins to avoid drawing those that fall outside of the visible bounds of the map.
#### 4.1.0
- Added Hexbin Layer options for colorDomain and radiusDomain. See README docs for details.
#### 4.0.0
- D3 v5: We now support D3 v5. Only minor changes were required.
- Fix for Leaflet > 1.2 Mixins Deprecation Warning: Updated the events include reference to remove the warning about using L.Mixins.Events
- Fixes for Hover Handlers Data and Tooltip positions: See Issue #45 and #50, thanks @ninio for finding these.
- Migrated to npm run based build: Not really an external facing thing, but matters if you're trying to build the library.
### Version 3.x
#### Dropping Support for Leaflet 0.7.x
We added some functionality that made it hard to backward support Leaflet 0.7.x.
You can continue to use our 2.x release for Leaflet 0.7.x support, but it's unlikely that branch will see any further development/releases.
This is the primary reason for increasing the major version as this is the only change that is not backwards compatible.
#### Hexbins/Pings now Zoom with Map Before Redrawing
We switched the HebinLayer to extend the built-in Leaflet SVG layer.
This provides a bunch of advantages, including that the SVG layer is zoom-transformed with the other layers on the map.
This allowed us to leave the hexbins on the map until the zoom animation is complete, at which point the hexbin grid is recalculated and redrawn.
#### Automatic Filtering of Off-Map Hexbins
We updated the Hexbin layer code to automatically filter out points that fall outside of the visible bounds of the map.
This _dramatically_ improves performance at high zoom levels where we used to draw A LOT of paths off the map for no reason.
#### Built-in Support for Tooltips and Other Hover Events
While you could always manually manage a tooltip or some kind of hexbin hover event, we've added some code to make it easier.
Now, you can pretty easily enable some built-in tooltip/highlight behavior or implement your own.
See the API docs on HoverHandlers and the advanced hexbin example for details.
### Version 2.x
#### Lots of API changes
Read through the API changes.
A lot of things were moved from config options to being configurable via chained function call.
#### You can now bind data to the radius of Hexbins!
You can now provide a radius value function to map a dimension of your data to the size of each hexbin.
#### We changed the Hexbin event dispatch
For Hexbins, we've changed the way that events are handled. Previously, you provided callback methods.
Now, we expose a d3 dispatch object:
```js
...
var hexLayer = L.hexbinLayer(options).addTo(map);
// Set up events
hexLayer.dispatch()
.on('mouseover', function(d, i) { })
.on('mouseout', function(d, i) { })
.on('click', function(d, i) { });
```
#### Pings now track the map when panning!
We've changed pings so that they track the map when as it pans.
The pan changes are applied immediately even when manually setting a low fps.
#### You can now size pings independently using a scale factor callback function
We've added a configurable option (pingLayer.radiusScaleFactor(...)) to provide a function that returns a data element-specific scale factor for the ping radius.
## Contribute
PRs accepted. If you are part of Asymmetrik, please make contributions on feature branches off of the ```develop``` branch. If you are outside of Asymmetrik, please fork our repo to make contributions.
## License
See LICENSE in repository for details.
## Credits
The hexbin portion of this plugin was based on [the work of Steven Hall](http://www.delimited.io/blog/2013/12/1/hexbins-with-d3-and-leaflet-maps). Check out his other awesome work at [Delimited](http://www.delimited.io/)
D3.js was created by the legendary [Mike Bostock](https://github.com/mbostock).
[Leaflet](http://leafletjs.com/) is maintained by [lots of cool people](https://github.com/Leaflet/Leaflet/graphs/contributors).
[travis-url]: https://travis-ci.org/Asymmetrik/leaflet-d3/
[travis-image]: https://travis-ci.org/Asymmetrik/leaflet-d3.svg
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2015-2016 Marin Atanasov Nikolov <dnaeon@gmail.com>
// Copyright (c) 2016 David Jack <davars@gmail.com>
// 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
// in this position and unchanged.
// 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 THE AUTHOR(S) ``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 AUTHOR(S) 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.
package recorder
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"os"
"strconv"
"time"
"github.com/dnaeon/go-vcr/cassette"
)
// Mode represents recording/playback mode
type Mode int
// Recorder states
const (
ModeRecording Mode = iota
ModeReplaying
ModeDisabled
)
// Recorder represents a type used to record and replay
// client and server interactions
type Recorder struct {
// Operating mode of the recorder
mode Mode
// Cassette used by the recorder
cassette *cassette.Cassette
// realTransport is the underlying http.RoundTripper to make real requests
realTransport http.RoundTripper
}
// SetTransport can be used to configure the behavior of the 'real' client used in record-mode
func (r *Recorder) SetTransport(t http.RoundTripper) {
r.realTransport = t
}
// Proxies client requests to their original destination
func requestHandler(r *http.Request, c *cassette.Cassette, mode Mode, realTransport http.RoundTripper) (*cassette.Interaction, error) {
// Return interaction from cassette if in replay mode
if mode == ModeReplaying {
if err := r.Context().Err(); err != nil {
return nil, err
}
return c.GetInteraction(r)
}
// Copy the original request, so we can read the form values
reqBytes, err := httputil.DumpRequestOut(r, true)
if err != nil {
return nil, err
}
reqBuffer := bytes.NewBuffer(reqBytes)
copiedReq, err := http.ReadRequest(bufio.NewReader(reqBuffer))
if err != nil {
return nil, err
}
err = copiedReq.ParseForm()
if err != nil {
return nil, err
}
reqBody := &bytes.Buffer{}
if r.Body != nil && !isNoBody(r.Body) {
// Record the request body so we can add it to the cassette
r.Body = ioutil.NopCloser(io.TeeReader(r.Body, reqBody))
}
// Perform client request to it's original
// destination and record interactions
resp, err := realTransport.RoundTrip(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// Add interaction to cassette
interaction := &cassette.Interaction{
Request: cassette.Request{
Body: reqBody.String(),
Form: copiedReq.PostForm,
Headers: r.Header,
URL: r.URL.String(),
Method: r.Method,
},
Response: cassette.Response{
Body: string(respBody),
Headers: resp.Header,
Status: resp.Status,
Code: resp.StatusCode,
},
}
for _, filter := range c.Filters {
err = filter(interaction)
if err != nil {
return nil, err
}
}
c.AddInteraction(interaction)
return interaction, nil
}
// New creates a new recorder
func New(cassetteName string) (*Recorder, error) {
// Default mode is "replay" if file exists
return NewAsMode(cassetteName, ModeReplaying, nil)
}
// NewAsMode creates a new recorder in the specified mode
func NewAsMode(cassetteName string, mode Mode, realTransport http.RoundTripper) (*Recorder, error) {
var c *cassette.Cassette
cassetteFile := fmt.Sprintf("%s.yaml", cassetteName)
if mode != ModeDisabled {
// Depending on whether the cassette file exists or not we
// either create a new empty cassette or load from file
if _, err := os.Stat(cassetteFile); os.IsNotExist(err) || mode == ModeRecording {
// Create new cassette and enter in recording mode
c = cassette.New(cassetteName)
mode = ModeRecording
} else {
// Load cassette from file and enter replay mode
c, err = cassette.Load(cassetteName)
if err != nil {
return nil, err
}
mode = ModeReplaying
}
}
if realTransport == nil {
realTransport = http.DefaultTransport
}
r := &Recorder{
mode: mode,
cassette: c,
realTransport: realTransport,
}
return r, nil
}
// Stop is used to stop the recorder and save any recorded interactions
func (r *Recorder) Stop() error {
if r.mode == ModeRecording {
if err := r.cassette.Save(); err != nil {
return err
}
}
return nil
}
// RoundTrip implements the http.RoundTripper interface
func (r *Recorder) RoundTrip(req *http.Request) (*http.Response, error) {
if r.mode == ModeDisabled {
return r.realTransport.RoundTrip(req)
}
// Pass cassette and mode to handler, so that interactions can be
// retrieved or recorded depending on the current recorder mode
interaction, err := requestHandler(req, r.cassette, r.mode, r.realTransport)
if err != nil {
return nil, err
}
select {
case <-req.Context().Done():
return nil, req.Context().Err()
default:
buf := bytes.NewBuffer([]byte(interaction.Response.Body))
// apply the duration defined in the interaction
if interaction.Response.Duration != "" {
d, err := time.ParseDuration(interaction.Duration)
if err != nil {
return nil, err
}
// block for the configured 'duration' to simulate the network latency and server processing time.
<-time.After(d)
}
contentLength := int64(buf.Len())
// For HTTP HEAD requests, the ContentLength should be set to the size
// of the body that would have been sent for a GET.
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13
if req.Method == "HEAD" {
if hdr := interaction.Response.Headers.Get("Content-Length"); hdr != "" {
cl, err := strconv.ParseInt(hdr, 10, 64)
if err == nil {
contentLength = cl
}
}
}
return &http.Response{
Status: interaction.Response.Status,
StatusCode: interaction.Response.Code,
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Request: req,
Header: interaction.Response.Headers,
Close: true,
ContentLength: contentLength,
Body: ioutil.NopCloser(buf),
}, nil
}
}
// CancelRequest implements the github.com/coreos/etcd/client.CancelableTransport interface
func (r *Recorder) CancelRequest(req *http.Request) {
type cancelableTransport interface {
CancelRequest(req *http.Request)
}
if ct, ok := r.realTransport.(cancelableTransport); ok {
ct.CancelRequest(req)
}
}
// SetMatcher sets a function to match requests against recorded HTTP interactions.
func (r *Recorder) SetMatcher(matcher cassette.Matcher) {
if r.cassette != nil {
r.cassette.Matcher = matcher
}
}
// AddFilter appends a hook to modify a request before it is recorded.
//
// Filters are useful for filtering out sensitive parameters from the recorded data.
func (r *Recorder) AddFilter(filter cassette.Filter) {
if r.cassette != nil {
r.cassette.Filters = append(r.cassette.Filters, filter)
}
}
| {
"pile_set_name": "Github"
} |
{
"OFPFlowMod": {
"buffer_id": 65535,
"command": 0,
"cookie": 0,
"cookie_mask": 0,
"flags": 0,
"hard_timeout": 0,
"idle_timeout": 0,
"instructions": [
{
"OFPInstructionGotoTable": {
"len": 8,
"table_id": 1,
"type": 1
}
}
],
"match": {
"OFPMatch": {
"length": 22,
"oxm_fields": [
{
"OXMTlv": {
"field": "in_port",
"mask": null,
"value": 6
}
},
{
"OXMTlv": {
"field": "eth_src",
"mask": null,
"value": "f2:0b:a4:7d:f8:ea"
}
}
],
"type": 1
}
},
"out_group": 4294967295,
"out_port": 4294967295,
"priority": 123,
"table_id": 0
}
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 342899bac8a417243b6738a7a9e8378f
timeCreated: 1511173561
licenseType: Free
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 100100000
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
/* boost random auto_link.hpp header file
*
* Copyright Steven Watanabe 2010
* 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)
*
* $Id: auto_link.hpp 60755 2010-03-22 00:45:06Z steven_watanabe $
*/
#ifndef BOOST_RANDOM_DETAIL_AUTO_LINK_HPP
#define BOOST_RANDOM_DETAIL_AUTO_LINK_HPP
#include <boost/config.hpp>
#ifdef BOOST_HAS_DECLSPEC
#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_RANDOM_DYN_LINK)
#if defined(BOOST_RANDOM_SOURCE)
#define BOOST_RANDOM_DECL __declspec(dllexport)
#else
#define BOOST_RANDOM_DECL __declspec(dllimport)
#endif
#endif
#endif
#ifndef BOOST_RANDOM_DECL
#define BOOST_RANDOM_DECL
#endif
#if !defined(BOOST_RANDOM_NO_LIB) && !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_RANDOM_SOURCE)
#define BOOST_LIB_NAME boost_random
#if defined(BOOST_RANDOM_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)
#define BOOST_DYN_LINK
#endif
#include <boost/config/auto_link.hpp>
#endif
#endif
| {
"pile_set_name": "Github"
} |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
return array(
'code' => '595',
'patterns' => array(
'national' => array(
'general' => '/^5[0-5]\\d{4,7}|[2-46-9]\\d{5,8}$/',
'fixed' => '/^(?:[26]1|3[289]|4[124678]|7[123]|8[1236])\\d{5,7}|(?:2(?:2[4568]|7[15]|9[1-5])|3(?:18|3[167]|4[2357]|51)|4(?:18|2[45]|3[12]|5[13]|64|71|9[1-47])|5(?:[1-4]\\d|5[0234])|6(?:3[1-3]|44|7[1-4678])|7(?:17|4[0-4]|6[1-578]|75|8[0-8])|858)\\d{5,6}$/',
'mobile' => '/^9(?:61|[78][1-6]|9[1-5])\\d{6}$/',
'voip' => '/^8700[0-4]\\d{4}$/',
'uan' => '/^[2-9]0\\d{4,7}$/',
'shortcode' => '/^1[1-4]\\d$/',
'emergency' => '/^128|911$/',
),
'possible' => array(
'general' => '/^\\d{5,9}$/',
'mobile' => '/^\\d{9}$/',
'voip' => '/^\\d{9}$/',
'uan' => '/^\\d{6,9}$/',
'shortcode' => '/^\\d{3}$/',
'emergency' => '/^\\d{3}$/',
),
),
);
| {
"pile_set_name": "Github"
} |
{
"url": "https://api.github.com/repos/kohsuke/sandbox-ant/comments/35673784",
"html_url": "https://github.com/kohsuke/sandbox-ant/commit/8ae38db0ea5837313ab5f39d43a6f73de3bd9000#commitcomment-35673784",
"id": 35673784,
"node_id": "MDEzOkNvbW1pdENvbW1lbnQzNTY3Mzc4NA==",
"user": {
"login": "bitwiseman",
"id": 1958953,
"node_id": "MDQ6VXNlcjE5NTg5NTM=",
"avatar_url": "https://avatars3.githubusercontent.com/u/1958953?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/bitwiseman",
"html_url": "https://github.com/bitwiseman",
"followers_url": "https://api.github.com/users/bitwiseman/followers",
"following_url": "https://api.github.com/users/bitwiseman/following{/other_user}",
"gists_url": "https://api.github.com/users/bitwiseman/gists{/gist_id}",
"starred_url": "https://api.github.com/users/bitwiseman/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/bitwiseman/subscriptions",
"organizations_url": "https://api.github.com/users/bitwiseman/orgs",
"repos_url": "https://api.github.com/users/bitwiseman/repos",
"events_url": "https://api.github.com/users/bitwiseman/events{/privacy}",
"received_events_url": "https://api.github.com/users/bitwiseman/received_events",
"type": "User",
"site_admin": false
},
"position": null,
"line": null,
"path": null,
"commit_id": "8ae38db0ea5837313ab5f39d43a6f73de3bd9000",
"created_at": "2019-10-26T01:28:59Z",
"updated_at": "2019-10-26T01:28:59Z",
"author_association": "NONE",
"body": "updated text"
} | {
"pile_set_name": "Github"
} |
function F = factorize (A,strategy,burble)
%FACTORIZE an object-oriented method for solving linear systems
% and least-squares problems, and for representing operations with the
% inverse of a square matrix or the pseudo-inverse of a rectangular matrix.
%
% F = factorize(A) returns an object F that holds the factorization of A.
% x=F\b then solves a linear system or a least-squares problem. S=inverse(F)
% or S=inverse(A) returns a factorized representation of the inverse of A so
% that inverse(A)*b is mathematically equivalent to pinv(A)*b, but the former
% does not actually compute the inverse or pseudo-inverse of A.
%
% Example
%
% F = factorize(A) ; % LU, QR, or Cholesky factorization of A
% x = F\b ; % solve A*x=b; same as x=A\b
% S = inverse (F) ; % S represents the factorization of inv(A)
% x = S*b ; % same as x = A\b.
% E = A-B*inverse(D)*C % efficiently computes the Schur complement
% E = A-B*inv(D)*C % bad method for computing the Schur complement
% S = inverse(A) ; S(:,1) % compute just the first column of inv(A),
% % without computing inv(A)
%
% F = factorize (A, strategy, burble) ; % optional 2nd and 3rd inputs
%
% A string can be specified as a second input parameter to select the strategy
% used to factorize the matrix. The first two are meta-strategies:
%
% 'default' if rectangular
% use QR for sparse A or A' (whichever is tall and thin);
% use COD for full A
% else
% if symmetric
% if positive real diagonal: try CHOL
% else (or if CHOL fails): try LDL
% end
% if not yet factorized: try LU (fails if rank-deficient)
% end
% if all else fails, or if QR or LU report that the matrix
% is singular (or nearly so): use COD
% This strategy mimics backslash, except that backslash never
% uses COD. Backslash also exploits other solvers, such as
% specialized tridiagonal and banded solvers.
%
% 'symmetric' as 'default' above, but assumes A is symmetric without
% checking, which is faster if you already know A is symmetric.
% Uses tril(A) and assumes triu(A) is its transpose. Results
% will be incorrect if A is not symmetric. If A is rectangular,
% the 'default' strategy is used instead.
%
% 'unsymmetric' as 'default', but assumes A is unsymmetric.
%
% The next "strategies" just select a single method, listed in decreasing order
% of generality and increasing order of speed and memory efficiency. All of
% them except the SVD can exploit sparsity.
%
% 'svd' use SVD. Never fails ... unless it runs out of time or memory.
% Coerces a sparse matrix A to full.
%
% 'cod' use COD. Almost as accurate as SVD, and much faster. Based
% on dense or sparse QR with rank estimation. Handles
% rank-deficient matrices, as long as it correctly estimates
% the rank. If the rank is ill-defined, use the SVD instead.
% Sparse COD requires the SPQR package to be installed
% (see http://www.suitesparse.com).
%
% 'qr' use QR. Reports a warning if A is singular.
%
% 'lu' use LU. Fails if A is rectangular; warning if A singular.
%
% 'ldl' use LDL. Fails if A is rank-deficient or not symmetric, or if
% A is sparse and complex. Uses tril(A) and assumes triu(A)
% is the transpose of tril(A).
%
% 'chol' use CHOL. Fails if A is rank-deficient or not symmetric
% positive definite. If A is sparse, it uses tril(A) and
% assumes triu(A) is the transpose of tril(A). If A is dense,
% triu(A) is used instead.
%
% A third input, burble, can be provided to tell this function to print what
% methods it tries (if burble is nonzero).
%
% For a demo type "fdemo" in the Demo directory or see the Doc/ directory.
%
% See also inverse, slash, linsolve, spqr.
% Copyright 2011-2012, Timothy A. Davis, http://www.suitesparse.com
assert (ndims (A) == 2, 'Matrix must be 2D.') ;
if (nargin < 2 || isempty (strategy))
strategy = 'default' ;
end
if (nargin < 3)
burble = 0 ;
end
if (burble)
fprintf ('\nfactorize: strategy %s, A has size %d-by-%d, ', ...
strategy, size (A)) ;
if (issparse (A))
fprintf ('sparse with %d nonzeros.\n', nnz (A)) ;
else
fprintf ('full.\n') ;
end
end
switch strategy
case 'default'
[F, me] = backslash_mimic (A, burble, 0) ;
case 'symmetric'
[F, me] = backslash_mimic (A, burble, 1) ;
case 'unsymmetric'
[F, me] = backslash_mimic (A, burble, 2) ;
case 'svd'
[F, me] = factorize_svd (A, burble) ;
case 'cod'
[F, me] = factorize_cod (A, burble) ;
case 'qr'
[F, me] = factorize_qr (A, burble, 0) ;
case 'lu'
% do not report a failure if the matrix is singular
[F, me] = factorize_lu (A, burble, 0) ;
case 'ldl'
[F, me] = factorize_ldl (A, burble) ;
case 'chol'
[F, me] = factorize_chol (A, burble) ;
otherwise
error ('FACTORIZE:invalidStrategy', 'unrecognized strategy.') ;
end
if (~isobject (F))
throw (me) ;
end
%-------------------------------------------------------------------------------
function [F, me] = backslash_mimic (A, burble, strategy)
%BACKSLASH_MIMIC automatically select a method to factorize A.
F = [ ] ;
me = [ ] ;
[m, n] = size (A) ;
% If the following condition is true, then the QR, QRT, or LU factorizations
% will report a failure if A is singular (or nearly so). This allows COD
% or COD_SPARSE to then be used instead. COD_SPARSE relies on the SPQR
% mexFunction in SuiteSparse, which might not be installed. In this case,
% QR, QRT, and LU do not report failures for sparse matrices that are singular
% (or nearly so), since there is no COD_SPARSE to fall back on.
fail_if_singular = ~issparse (A) || (exist ('spqr') == 3) ; %#ok
try_cod = true ;
if (m ~= n)
if (issparse (A))
% Use QR for the sparse rectangular case (ignore 'strategy' argument).
[F, me] = factorize_qr (A, burble, fail_if_singular) ;
else
% Use COD for the full rectangular case (ignore 'strategy' argument).
% If this fails, there's no reason to retry the COD below. If A has
% full rank, then COD is the same as QR with column pivoting (with the
% same cost in terms of run time and memory). Backslash in MATLAB uses
% QR with column pivoting alone, so this is just as fast as x=A\b in
% the full-rank case, but gives a more reliable result in the rank-
% deficient case.
try_cod = false ;
[F, me] = factorize_cod (A, burble) ;
end
else
% square case: Cholesky, LDL, or LU factorization of A
switch strategy
case 0
is_symmetric = (nnz (A-A') == 0) ;
case 1
is_symmetric = true ;
case 2
is_symmetric = false ;
end
if (is_symmetric)
% A is symmetric (or assumed to be so)
d = diag (A) ;
if (all (d > 0) && nnz (imag (d)) == 0)
% try a Cholesky factorization
[F, me] = factorize_chol (A, burble) ;
end
if (~isobject (F) && (~issparse (A) || isreal (A)))
% try an LDL factorization.
% complex sparse LDL does not yet exist in MATLAB
[F, me] = factorize_ldl (A, burble) ;
end
end
if (~isobject (F))
% use LU if Cholesky and/or LDL failed, or were skipped.
[F, me] = factorize_lu (A, burble, fail_if_singular) ;
end
end
if (~isobject (F) && try_cod)
% everything else failed, matrix is rank-deficient. Use COD
[F, me] = factorize_cod (A, burble) ;
end
%-------------------------------------------------------------------------------
function [F, me] = factorize_qr (A, burble, fail_if_singular)
% QR fails if the matrix is rank-deficient.
F = [ ] ;
me = [ ] ;
try
[m, n] = size (A) ;
if (m >= n)
if (burble)
fprintf ('factorize: try QR of A ... ') ;
end
if (issparse (A))
F = factorization_qr_sparse (A, fail_if_singular) ;
else
F = factorization_qr_dense (A, fail_if_singular) ;
end
else
if (burble)
fprintf ('factorize: try QR of A'' ... ') ;
end
if (issparse (A))
F = factorization_qrt_sparse (A, fail_if_singular) ;
else
F = factorization_qrt_dense (A, fail_if_singular) ;
end
end
if (burble)
fprintf ('OK.\n') ;
end
catch me
if (burble)
fprintf ('failed.\nfactorize: %s\n', me.message) ;
end
end
%-------------------------------------------------------------------------------
function [F, me] = factorize_chol (A, burble)
% LDL fails if the matrix is rectangular, rank-deficient, or not positive
% definite. Only the lower triangular part of A is used.
F = [ ] ;
me = [ ] ;
try
if (burble)
fprintf ('factorize: try CHOL ... ') ;
end
if (issparse (A))
F = factorization_chol_sparse (A) ;
else
F = factorization_chol_dense (A) ;
end
if (burble)
fprintf ('OK.\n') ;
end
catch me
if (burble)
fprintf ('failed.\nfactorize: %s\n', me.message) ;
end
end
%-------------------------------------------------------------------------------
function [F, me] = factorize_ldl (A, burble)
% LDL fails if the matrix is rectangular or rank-deficient.
% As of MATLAB R2012a, ldl does not work for complex sparse matrices.
% Only the lower triangular part of A is used.
F = [ ] ;
me = [ ] ;
try
if (burble)
fprintf ('factorize: try LDL ... ') ;
end
if (issparse (A))
F = factorization_ldl_sparse (A) ;
else
F = factorization_ldl_dense (A) ;
end
if (burble)
fprintf ('OK.\n') ;
end
catch me
if (burble)
fprintf ('failed.\nfactorize: %s\n', me.message) ;
end
end
%-------------------------------------------------------------------------------
function [F, me] = factorize_lu (A, burble, fail_if_singular)
% LU fails if the matrix is rectangular or rank-deficient.
F = [ ] ;
me = [ ] ;
try
if (burble)
fprintf ('factorize: try LU ... ') ;
end
if (issparse (A))
F = factorization_lu_sparse (A, fail_if_singular) ;
else
F = factorization_lu_dense (A, fail_if_singular) ;
end
if (burble)
fprintf ('OK.\n') ;
end
catch me
if (burble)
fprintf ('failed.\nfactorize: %s\n', me.message) ;
end
end
%-------------------------------------------------------------------------------
function [F, me] = factorize_cod (A, burble)
% COD only fails when it runs out of memory.
F = [ ] ;
me = [ ] ;
try
if (burble)
fprintf ('factorize: try COD ... ') ;
end
if (issparse (A))
F = factorization_cod_sparse (A) ;
else
F = factorization_cod_dense (A) ;
end
if (burble)
fprintf ('OK.\n') ;
end
catch me
if (burble)
fprintf ('failed.\nfactorize: %s\n', me.message) ;
end
end
%-------------------------------------------------------------------------------
function [F, me] = factorize_svd (A, burble)
% SVD only fails when it runs out of memory.
F = [ ] ;
me = [ ] ;
try
if (burble)
fprintf ('factorize: try SVD ... ') ;
end
F = factorization_svd (A) ;
if (burble)
fprintf ('OK.\n') ;
end
catch me
if (burble)
fprintf ('failed.\nfactorize: %s\n', me.message) ;
end
end
| {
"pile_set_name": "Github"
} |
namespace FluentSecurity.SampleApplication.Models
{
public enum UserRole
{
Administrator,
Publisher
}
} | {
"pile_set_name": "Github"
} |
;
; jdct.inc - private declarations for forward & reverse DCT subsystems
;
; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
;
; Based on
; x86 SIMD extension for IJG JPEG library
; Copyright (C) 1999-2006, MIYASAKA Masaru.
; For conditions of distribution and use, see copyright notice in jsimdext.inc
;
; [TAB8]
; Each IDCT routine is responsible for range-limiting its results and
; converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
; be quite far out of range if the input data is corrupt, so a bulletproof
; range-limiting step is required. We use a mask-and-table-lookup method
; to do the combined operations quickly.
;
%define RANGE_MASK (MAXJSAMPLE * 4 + 3) ; 2 bits wider than legal samples
%define ROW(n,b,s) ((b)+(n)*(s))
%define COL(n,b,s) ((b)+(n)*(s)*DCTSIZE)
%define DWBLOCK(m,n,b,s) ((b)+(m)*DCTSIZE*(s)+(n)*SIZEOF_DWORD)
%define MMBLOCK(m,n,b,s) ((b)+(m)*DCTSIZE*(s)+(n)*SIZEOF_MMWORD)
%define XMMBLOCK(m,n,b,s) ((b)+(m)*DCTSIZE*(s)+(n)*SIZEOF_XMMWORD)
; --------------------------------------------------------------------------
| {
"pile_set_name": "Github"
} |
# Dash to Dock Basque translation.
# This file is distributed under the same license as the Dash to Dock package.
# Ibai Oihanguren Sala <ibai@oihanguren.com>, 2020.
#
msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-03-22 23:54+0100\n"
"PO-Revision-Date: 2020-03-22 23:54+0100\n"
"Last-Translator: Ibai Oihanguren Sala <ibai@oihanguren.com>\n"
"Language-Team: \n"
"Language: eu\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: prefs.js:268
msgid "Primary monitor"
msgstr "Monitore nagusia"
#: prefs.js:277 prefs.js:284
msgid "Secondary monitor "
msgstr "Bigarren monitorea "
#: prefs.js:309 Settings.ui.h:29
msgid "Right"
msgstr "Eskuinean"
#: prefs.js:310 Settings.ui.h:26
msgid "Left"
msgstr "Ezkerrean"
#: prefs.js:360
msgid "Intelligent autohide customization"
msgstr "Ezkutatze adimentsuaren pertsonalizazioa"
#: prefs.js:367 prefs.js:560 prefs.js:616
msgid "Reset to defaults"
msgstr "Berrezarri balio lehenetsiak"
#: prefs.js:553
msgid "Show dock and application numbers"
msgstr "Erakutsi atrakea eta aplikazioen zenbakiak"
#: prefs.js:609
msgid "Customize middle-click behavior"
msgstr "Pertsonalizatu erdiko klikaren portaera"
#: prefs.js:692
msgid "Customize running indicators"
msgstr "Pertsonalizatu martxan egotearen adierazleak"
#: prefs.js:804 Settings.ui.h:75
msgid "Customize opacity"
msgstr "Pertsonalizatu opakutasuna"
#: appIcons.js:792
msgid "All Windows"
msgstr "Leiho guztiak"
#. Translators: %s is "Settings", which is automatically translated. You
#. can also translate the full message if this fits better your language.
#: appIcons.js:1119
#, javascript-format
msgid "Dash to Dock %s"
msgstr "Dash to Dock %s"
#: locations.js:65
msgid "Trash"
msgstr "Zakarrontzia"
#: locations.js:74
msgid "Empty Trash"
msgstr "Hustu zakarrontzia"
#: locations.js:189
msgid "Mount"
msgstr "Muntatu"
#: locations.js:232
msgid "Eject"
msgstr "Egotzi"
#: locations.js:237
msgid "Unmount"
msgstr "Desmuntatu"
#: Settings.ui.h:1
msgid ""
"When set to minimize, double clicking minimizes all the windows of the "
"application."
msgstr ""
"Minimizatzea hautatuz gero, klik bikoitzak aplikazioaren leiho guztiak "
"minimizatzen ditu."
#: Settings.ui.h:2
msgid "Shift+Click action"
msgstr "Maius+Klik ekintza"
#: Settings.ui.h:3
msgid "Raise window"
msgstr "Goratu leihoa"
#: Settings.ui.h:4
msgid "Minimize window"
msgstr "Minimizatu leihoa"
#: Settings.ui.h:5
msgid "Launch new instance"
msgstr "Abiarazi instantzia berria"
#: Settings.ui.h:6
msgid "Cycle through windows"
msgstr "Txandakatu leihoak"
#: Settings.ui.h:7
msgid "Minimize or overview"
msgstr "Minimizatu edo ikuspegi orokorra"
#: Settings.ui.h:8
msgid "Show window previews"
msgstr "Erakutsi leihoen aurrebistak"
#: Settings.ui.h:9
msgid "Minimize or show previews"
msgstr "Minimizatu edo erakutsi aurrebistak"
#: Settings.ui.h:10
msgid "Focus or show previews"
msgstr "Fokuratu edo erakutsi aurrebistak"
#: Settings.ui.h:11
msgid "Quit"
msgstr "Irten"
#: Settings.ui.h:12
msgid "Behavior for Middle-Click."
msgstr "Erdiko klikaren portaera"
#: Settings.ui.h:13
msgid "Middle-Click action"
msgstr "Erdiko klikaren ekintza"
#: Settings.ui.h:14
msgid "Behavior for Shift+Middle-Click."
msgstr "Maius+Erdiko klikaren portaera"
#: Settings.ui.h:15
msgid "Shift+Middle-Click action"
msgstr "Maius+Erdiko klikaren ekintza"
#: Settings.ui.h:16
msgid "Enable Unity7 like glossy backlit items"
msgstr "Gaitu Unity7 erako atzeko argidun elementu distiratsuak"
#: Settings.ui.h:17
msgid "Apply glossy effect."
msgstr "Aplikatu efektu distiratsua."
#: Settings.ui.h:18
msgid "Use dominant color"
msgstr "Erabili kolore nagusia"
#: Settings.ui.h:19
msgid "Customize indicator style"
msgstr "Pertsonalizatu adierazleen estiloa"
#: Settings.ui.h:20
msgid "Color"
msgstr "Kolorea"
#: Settings.ui.h:21
msgid "Border color"
msgstr "Ertzaren kolorea"
#: Settings.ui.h:22
msgid "Border width"
msgstr "Ertzaren zabalera"
#: Settings.ui.h:23
msgid "Show the dock on"
msgstr "Erakutsi atrakea hemen"
#: Settings.ui.h:24
msgid "Show on all monitors."
msgstr "Erakutsi monitore guztietan."
#: Settings.ui.h:25
msgid "Position on screen"
msgstr "Pantailako posizioa"
#: Settings.ui.h:27
msgid "Bottom"
msgstr "Behean"
#: Settings.ui.h:28
msgid "Top"
msgstr "Goian"
#: Settings.ui.h:30
msgid ""
"Hide the dock when it obstructs a window of the current application. More "
"refined settings are available."
msgstr ""
"Ezkutatu atrakea uneko aplikazioaren leiho bat eragozten duenean. Ezarpen "
"zehatzagoak erabilgarri daude."
#: Settings.ui.h:31
msgid "Intelligent autohide"
msgstr "Ezkutatze adimentsua"
#: Settings.ui.h:32
msgid "Dock size limit"
msgstr "Atrakearen tamaina-muga"
#: Settings.ui.h:33
msgid "Panel mode: extend to the screen edge"
msgstr "Panel modua: hedatu pantailaren ertzetara"
#: Settings.ui.h:34
msgid "Icon size limit"
msgstr "Ikonoen tamaina-muga"
#: Settings.ui.h:35
msgid "Fixed icon size: scroll to reveal other icons"
msgstr "Ikono-tamaina finkoa: korritu beste ikonoak erakusteko"
#: Settings.ui.h:36
msgid "Position and size"
msgstr "Posizioa eta tamaina"
#: Settings.ui.h:37
msgid "Show favorite applications"
msgstr "Erakutsi gogoko aplikazioak"
#: Settings.ui.h:38
msgid "Show running applications"
msgstr "Erakutsi martxan dauden aplikazioak"
#: Settings.ui.h:39
msgid "Isolate workspaces."
msgstr "Isolatu laneako areak."
#: Settings.ui.h:40
msgid "Isolate monitors."
msgstr "Isolatu monitoreak."
#: Settings.ui.h:41
msgid "Show open windows previews."
msgstr "Erakutsi irekitako leihoen aurrebistak."
#: Settings.ui.h:42
msgid ""
"If disabled, these settings are accessible from gnome-tweak-tool or the "
"extension website."
msgstr ""
"Desgaituz gero, ezarpen hauek gnome-tweak-tool aplikazioan edo hedapenen "
"webgunean daude erabilgarri."
#: Settings.ui.h:43
msgid "Show <i>Applications</i> icon"
msgstr "Erakutsi <i>Aplikazioak</i> ikonoa"
#: Settings.ui.h:44
msgid "Move the applications button at the beginning of the dock."
msgstr "Eraman aplikazioen botoia atrakearen hasierara."
#: Settings.ui.h:45
msgid "Animate <i>Show Applications</i>."
msgstr "Animatu <i>Erakutsi aplikazioak</i> ekintza."
#: Settings.ui.h:46
msgid "Show trash can"
msgstr "Erakutsi zakarrontzia"
#: Settings.ui.h:47
msgid "Show mounted volumes and devices"
msgstr "Erakutsi muntatutako bolumen eta gailuak"
#: Settings.ui.h:48
msgid "Launchers"
msgstr "Abiarazleak"
#: Settings.ui.h:49
msgid ""
"Enable Super+(0-9) as shortcuts to activate apps. It can also be used "
"together with Shift and Ctrl."
msgstr ""
"Gaitu Super+(0-9) aplikazioak aktibatzeko laster-tekla gisa. Maius eta Ktrl "
"teklekin batera ere erabil daiteke."
#: Settings.ui.h:50
msgid "Use keyboard shortcuts to activate apps"
msgstr "Erabili laster-teklak aplikazioak aktibatzeko"
#: Settings.ui.h:51
msgid "Behaviour when clicking on the icon of a running application."
msgstr "Martxan dagoen aplikazio baten ikonoak klik egitean duen portaera."
#: Settings.ui.h:52
msgid "Click action"
msgstr "Klik ekintza"
#: Settings.ui.h:53
msgid "Minimize"
msgstr "Minimizatu"
#: Settings.ui.h:54
msgid "Behaviour when scrolling on the icon of an application."
msgstr "Aplikazio baten ikonoaren gainean sagua korritzean duen portaera."
#: Settings.ui.h:55
msgid "Scroll action"
msgstr "Korritze-ekintza"
#: Settings.ui.h:56
msgid "Do nothing"
msgstr "Ez egin ezer"
#: Settings.ui.h:57
msgid "Switch workspace"
msgstr "Aldatu laneko areaz"
#: Settings.ui.h:58
msgid "Behavior"
msgstr "Portaera"
#: Settings.ui.h:59
msgid ""
"Few customizations meant to integrate the dock with the default GNOME theme. "
"Alternatively, specific options can be enabled below."
msgstr ""
"Atrakea GNOMEren gai lehenetsiarekin integratzeko ezarritako pertsonalizazio "
"txikiak. Honen ordez aukera zehatzak gaitu daitezke jarraian."
#: Settings.ui.h:60
msgid "Use built-in theme"
msgstr "Erabili integrazio gaia"
#: Settings.ui.h:61
msgid "Save space reducing padding and border radius."
msgstr "Hartu leku gutxiago betegarria eta ertzen erradioa txikituz."
#: Settings.ui.h:62
msgid "Shrink the dash"
msgstr "Txikiagotu abiarazle-panela"
#: Settings.ui.h:63
msgid "Customize windows counter indicators"
msgstr "Pertsonalizatu leiho kopuruen adierazleak"
#: Settings.ui.h:64
msgid "Default"
msgstr "Lehenetsia"
#: Settings.ui.h:65
msgid "Dots"
msgstr "Puntuak"
#: Settings.ui.h:66
msgid "Squares"
msgstr "Laukiak"
#: Settings.ui.h:67
msgid "Dashes"
msgstr "Marrak"
#: Settings.ui.h:68
msgid "Segmented"
msgstr "Zatikatua"
#: Settings.ui.h:69
msgid "Solid"
msgstr "Solidoa"
#: Settings.ui.h:70
msgid "Ciliora"
msgstr "Ciliora"
#: Settings.ui.h:71
msgid "Metro"
msgstr "Metro"
#: Settings.ui.h:72
msgid "Set the background color for the dash."
msgstr "Ezarri abiarazle-panelaren atzeko planoko kolorea"
#: Settings.ui.h:73
msgid "Customize the dash color"
msgstr "Personalizatu abiarazle-panelaren kolorea"
#: Settings.ui.h:74
msgid "Tune the dash background opacity."
msgstr "Doitu abiarazle-panelaren atzeko planoaren opakutasuna."
#: Settings.ui.h:76
msgid "Fixed"
msgstr "Finkoa"
#: Settings.ui.h:77
msgid "Dynamic"
msgstr "Dinamikoa"
#: Settings.ui.h:78
msgid "Opacity"
msgstr "Opakutasuna"
#: Settings.ui.h:79
msgid "Force straight corner\n"
msgstr "Behartu erpin zuzena\n"
#: Settings.ui.h:80
msgid "Appearance"
msgstr "Itxura"
#: Settings.ui.h:81
msgid "version: "
msgstr "bertsioa: "
#: Settings.ui.h:82
msgid "Moves the dash out of the overview transforming it in a dock"
msgstr "Abiarazle-panela ikuspegi orokorretik ateratzen du, atrake bihurtuz"
#: Settings.ui.h:83
msgid "Created by"
msgstr "Sortzaileak"
#: Settings.ui.h:84
msgid "Webpage"
msgstr "Webgunea"
#: Settings.ui.h:85
msgid ""
"<span size=\"small\">This program comes with ABSOLUTELY NO WARRANTY.\n"
"See the <a href=\"https://www.gnu.org/licenses/old-licenses/gpl-"
"2.0.html\">GNU General Public License, version 2 or later</a> for "
"details.</span>"
msgstr ""
"<span size=\"small\">Programa honek ez du inolako bermerik.\n"
"Xehetasun gehiagorako, ikusi <a href=\"https://www.gnu.org/licenses/old-"
"licenses/gpl-2.0.html\">GNUren Lizentzia Publiko Orokorra, 2. bertsioa edo "
"berriagoa</a></span>"
#: Settings.ui.h:87
msgid "About"
msgstr "Honi buruz"
#: Settings.ui.h:88
msgid "Customize minimum and maximum opacity values"
msgstr "Pertsonalizatu opakutasun minimo eta maximoa"
#: Settings.ui.h:89
msgid "Minimum opacity"
msgstr "Opakutasun minimoa"
#: Settings.ui.h:90
msgid "Maximum opacity"
msgstr "Opakutasun maximoa"
#: Settings.ui.h:91
msgid "Number overlay"
msgstr "Gainjarritako zenbakiak"
#: Settings.ui.h:92
msgid ""
"Temporarily show the application numbers over the icons, corresponding to "
"the shortcut."
msgstr ""
"Erakutsi une batez laster-teklei dagozkien aplikazio-zenbakiak ikonoen "
"gainean."
#: Settings.ui.h:93
msgid "Show the dock if it is hidden"
msgstr "Erakutsi atrakea ezkutatua badago"
#: Settings.ui.h:94
msgid ""
"If using autohide, the dock will appear for a short time when triggering the "
"shortcut."
msgstr ""
"Ezkutatze automatikoa erabiltzean, laster-tekla sakatuz atrakea une baterako "
"azalduko da."
#: Settings.ui.h:95
msgid "Shortcut for the options above"
msgstr "Goiko aukeretarako laster-teklak"
#: Settings.ui.h:96
msgid "Syntax: <Shift>, <Ctrl>, <Alt>, <Super>"
msgstr "Sintaxia: <Shift>, <Ctrl>, <Alt>, <Super>"
#: Settings.ui.h:97
msgid "Hide timeout (s)"
msgstr "Ezkutatzeko denbora-muga (s)"
#: Settings.ui.h:98
msgid "Show the dock by mouse hover on the screen edge."
msgstr "Erakutsi atrakea sagua pantailaren ertzera eramatean."
#: Settings.ui.h:99
msgid "Autohide"
msgstr "Ezkutatze automatikoa"
#: Settings.ui.h:100
msgid "Push to show: require pressure to show the dock"
msgstr "Bultzatu erakusteko: presio pixka bat egin behar da atrakea erakusteko"
#: Settings.ui.h:101
msgid "Enable in fullscreen mode"
msgstr "Gaitu pantaila osoko moduan"
#: Settings.ui.h:102
msgid "Show the dock when it doesn't obstruct application windows."
msgstr "Erakutsi atrakea aplikazioaren leihoak eragozten ez dituenean."
#: Settings.ui.h:103
msgid "Dodge windows"
msgstr "Saihestu leihoak"
#: Settings.ui.h:104
msgid "All windows"
msgstr "Leiho guztiak"
#: Settings.ui.h:105
msgid "Only focused application's windows"
msgstr "Fokuratutako aplikazioen leihoetan soilik"
#: Settings.ui.h:106
msgid "Only maximized windows"
msgstr "Maximizatutako leihoetan soilik"
#: Settings.ui.h:107
msgid "Animation duration (s)"
msgstr "Animazioaren iraupena (s)"
#: Settings.ui.h:108
msgid "Show timeout (s)"
msgstr "Erakusteko denbora-muga (s)"
#: Settings.ui.h:109
msgid "Pressure threshold"
msgstr "Presio-atalasea"
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Esprima: Coverage Analysis Report</title>
<link rel="stylesheet" type="text/css" href="../assets/style.css"/>
</head>
<style>
span.covered {
}
span.uncovered {
background: #FDD;
}
span.partial {
background: #FFA;
}
</style>
<body>
<div class="container">
<div class="topbar">
<ul class="nav">
<li><a href="../index.html">← Home</a></li>
<li><a href="http://github.com/ariya/esprima">Code</a></li>
<li><a href="../doc/index.html">Documentation</a></li>
<li><a href="http://issues.esprima.org">Issues</a></li>
</ul>
</div>
<h1>Coverage Analysis <small>ensures systematic exercise of the parser</small></h1>
<p><strong>Note</strong>: This is not a live (in-browser) code coverage report.
The analysis is <a href="http://code.google.com/p/esprima/wiki/Testing#Code_coverage_test">performed</a> offline
(using <a href="https://github.com/itay/node-cover">node-cover</a>).<br>
| {
"pile_set_name": "Github"
} |
"""
Copyright (C) 2018-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import io
import os
import struct
import numpy as np
from mo.utils.error import Error
from mo.utils.utils import refer_to_faq_msg
end_of_nnet_tag = '</Nnet>'
end_of_component_tag = '<!EndOfComponent>'
supported_components = [
'addshift',
'affinecomponent',
'affinecomponentpreconditionedonline',
'affinetransform',
'backproptruncationcomponent',
'batchnormcomponent',
'clipgradientcomponent',
'convolutional1dcomponent',
'convolutionalcomponent',
'copy',
'elementwiseproductcomponent',
'fixedaffinecomponent',
'fixedscalecomponent',
'fixedbiascomponent',
'linearcomponent',
'logsoftmaxcomponent',
'lstmnonlinearitycomponent',
'lstmprojected',
'lstmprojectedstreams',
'maxpoolingcomponent',
'naturalgradientaffinecomponent',
'naturalgradientperelementscalecomponent',
'noopcomponent',
'normalizecomponent',
'parallelcomponent',
'pnormcomponent',
'rectifiedlinearcomponent',
'rescale',
'sigmoid',
'sigmoidcomponent',
'softmax',
'softmaxcomponent',
'splicecomponent',
'sumgroupcomponent',
'tanhcomponent',
]
def get_bool(s: bytes) -> bool:
"""
Get bool value from bytes
:param s: bytes array contains bool value
:return: bool value from bytes array
"""
if str(s) == "b\'F\'":
return False
elif str(s) == "b\'T\'":
return True
else:
return struct.unpack('?', s)[0]
def get_uint16(s: bytes) -> int:
"""
Get unsigned int16 value from bytes
:param s: bytes array contains unsigned int16 value
:return: unsigned int16 value from bytes array
"""
return struct.unpack('H', s)[0]
def get_uint32(s: bytes) -> int:
"""
Get unsigned int32 value from bytes
:param s: bytes array contains unsigned int32 value
:return: unsigned int32 value from bytes array
"""
return struct.unpack('I', s)[0]
def get_uint64(s: bytes) -> int:
"""
Get unsigned int64 value from bytes
:param s: bytes array contains unsigned int64 value
:return: unsigned int64 value from bytes array
"""
return struct.unpack('q', s)[0]
def read_binary_bool_token(file_desc: io.BufferedReader) -> bool:
"""
Get next bool value from file
The carriage moves forward to 1 position.
:param file_desc: file descriptor
:return: next boolean value in file
"""
return get_bool(file_desc.read(1))
def read_binary_integer32_token(file_desc: io.BufferedReader) -> int:
"""
Get next int32 value from file
The carriage moves forward to 5 position.
:param file_desc: file descriptor
:return: next uint32 value in file
"""
buffer_size = file_desc.read(1)
return get_uint32(file_desc.read(buffer_size[0]))
def read_binary_integer64_token(file_desc: io.BufferedReader) -> int:
"""
Get next int64 value from file
The carriage moves forward to 9 position.
:param file_desc: file descriptor
:return: next uint64 value in file
"""
buffer_size = file_desc.read(1)
return get_uint64(file_desc.read(buffer_size[0]))
def read_binary_float_token(file_desc: io.BufferedReader) -> float:
"""
Get next float32 value from file
The carriage moves forward to 5 position.
:param file_desc: file descriptor
:return: next float32 value in file
"""
buffer_size = file_desc.read(1)
s = file_desc.read(buffer_size[0])
return np.frombuffer(s, dtype=np.float32)[0]
def read_string(file_desc: io.BufferedReader) -> int:
return collect_until_whitespace(file_desc)
def find_next_tag(file_desc: io.BufferedReader) -> str:
"""
Get next tag in the file
:param file_desc:file descriptor
:return: string like '<sometag>'
"""
tag = b''
while True:
symbol = file_desc.read(1)
if symbol == b'':
raise Error('Unexpected end of Kaldi model')
if tag == b'' and symbol != b'<':
continue
elif symbol == b'<':
tag = b''
tag += symbol
if symbol != b'>':
continue
try:
return tag.decode('ascii')
except UnicodeDecodeError:
# Tag in Kaldi model always in ascii encoding
tag = b''
def read_placeholder(file_desc: io.BufferedReader, size=3) -> bytes:
"""
Read size bytes from file
:param file_desc:file descriptor
:param size:number of reading bytes
:return: bytes
"""
return file_desc.read(size)
def find_next_component(file_desc: io.BufferedReader) -> str:
"""
Read next component in the file.
All components are contained in supported_components
:param file_desc:file descriptor
:return: string like '<component>'
"""
is_start = True
while True:
tag = find_next_tag(file_desc)
# Tag is <NameOfTheLayer>. But we want get without '<' and '>'
component_name = tag[1:-1].lower()
if component_name in supported_components or tag == end_of_nnet_tag:
# There is whitespace after component's name
read_placeholder(file_desc, 1)
return component_name
elif tag == '<ComponentName>':
raise Error('Component has unsupported or not specified type')
elif not (is_start and tag == end_of_component_tag) and tag.find('Component') != -1:
raise Error('Component has unsupported type {}'.format(tag))
is_start = False
def get_name_from_path(path: str) -> str:
"""
Get name from path to the file
:param path: path to the file
:return: name of the file
"""
return os.path.splitext(os.path.basename(path))[0]
def find_end_of_component(file_desc: io.BufferedReader, component: str, end_tags: tuple = ()):
"""
Find an index and a tag of the ent of the component
:param file_desc: file descriptor
:param component: component from supported_components
:param end_tags: specific end tags
:return: the index and the tag of the end of the component
"""
end_tags_of_component = ['</{}>'.format(component),
end_of_component_tag.lower(),
end_of_nnet_tag.lower(),
*end_tags,
*['<{}>'.format(component) for component in supported_components]]
next_tag = find_next_tag(file_desc)
while next_tag.lower() not in end_tags_of_component:
next_tag = find_next_tag(file_desc)
return next_tag, file_desc.tell()
def get_parameters(file_desc: io.BufferedReader, start_index: int, end_index: int):
"""
Get part of file
:param file_desc: file descriptor
:param start_index: Index of the start reading
:param end_index: Index of the end reading
:return: part of the file
"""
file_desc.seek(start_index)
buffer = file_desc.read(end_index - start_index)
return io.BytesIO(buffer)
def read_token_value(file_desc: io.BufferedReader, token: bytes = b'', value_type: type = np.uint32):
"""
Get value of the token.
Read next token (until whitespace) and check if next teg equals token
:param file_desc: file descriptor
:param token: token
:param value_type: type of the reading value
:return: value of the token
"""
getters = {
np.uint32: read_binary_integer32_token,
np.uint64: read_binary_integer64_token,
np.bool: read_binary_bool_token
}
current_token = collect_until_whitespace(file_desc)
if token != b'' and token != current_token:
raise Error('Can not load token {} from Kaldi model'.format(token) +
refer_to_faq_msg(94))
return getters[value_type](file_desc)
def collect_until_whitespace(file_desc: io.BufferedReader):
"""
Read from file until whitespace
:param file_desc: file descriptor
:return:
"""
res = b''
while True:
new_sym = file_desc.read(1)
if new_sym == b' ' or new_sym == b'':
break
res += new_sym
return res
def collect_until_token(file_desc: io.BufferedReader, token, size_search_zone=0):
"""
Read from file until the token
:param file_desc: file descriptor
:param token: token that we find
:return:
"""
while True:
# usually there is the following structure <CellDim> DIM<ClipGradient> VALUEFM
res = collect_until_whitespace(file_desc)
if res == token or res[-len(token):] == token:
return
size = size_search_zone
if size == 0 and isinstance(file_desc, io.BytesIO):
size = len(file_desc.getbuffer())
elif size == 0 and isinstance(file_desc, io.BufferedReader):
size = os.fstat(file_desc.fileno()).st_size
if file_desc.tell() >= size:
raise Error('End of the file. Token {} not found. {}'.format(token, file_desc.tell()))
def collect_until_token_and_read(file_desc: io.BufferedReader, token, value_type: type = np.uint32):
"""
Read from file until the token
:param file_desc: file descriptor
:param token: token to find and read
:param value_type: type of value to read
:return:
"""
getters = {
np.uint32: read_binary_integer32_token,
np.uint64: read_binary_integer64_token,
np.bool: read_binary_bool_token,
np.string_: read_string
}
collect_until_token(file_desc, token)
return getters[value_type](file_desc)
def create_edge_attrs(prev_layer_id: str, next_layer_id: str, in_port=0, out_port=0) -> dict:
"""
Create common edge's attributes
:param prev_layer_id: id of previous layer
:param next_layer_id: id of next layer
:param in_port: 'in' port
:param out_port: 'out' port
:return: dictionary contains common attributes for edge
"""
return {
'out': out_port,
'in': in_port,
'name': next_layer_id,
'fw_tensor_debug_info': [(prev_layer_id, next_layer_id)],
'in_attrs': ['in', 'permutation'],
'out_attrs': ['out', 'permutation'],
'data_attrs': ['fw_tensor_debug_info']
}
def read_blob(file_desc: io.BufferedReader, size: int, dtype=np.float32):
"""
Read blob from the file
:param file_desc: file descriptor
:param size: size of the blob
:param dtype: type of values of the blob
:return: np array contains blob
"""
dsizes = {
np.float32: 4,
np.int32: 4
}
data = file_desc.read(size * dsizes[dtype])
return np.frombuffer(data, dtype=dtype)
def get_args_for_specifier(string):
"""
Parse arguments in brackets and return list of arguments
:param string: string in format (<arg1>, <arg2>, .., <argn>)
:return: list with arguments
"""
open_bracket = 1
pos = 1
args = []
prev_arg_pos = 1
pos_close = string.rfind(b')')
string = string[:pos_close+1]
while pos < len(string):
pos_open = string.find(b'(', pos)
pos_close = string.find(b')', pos)
pos_sep = string.find(b',', pos)
if pos_open == -1:
if open_bracket == 1:
args = args + string[prev_arg_pos:pos_close].replace(b' ', b'').split(b',')
pos = len(string)
else:
open_bracket = open_bracket - 1
while open_bracket > 1:
pos_close = string.find(b')', pos_close+1)
if pos_close != -1:
open_bracket = open_bracket - 1
else:
raise Error("Syntax error in model: incorrect number of brackets")
args.append(string[prev_arg_pos:pos_close+1].strip())
prev_arg_pos = string.find(b',', pos_close+1) + 1
if prev_arg_pos != 0 and string[prev_arg_pos:-2].replace(b' ', b'').split(b',') != [b'']:
args = args + string[prev_arg_pos:-1].replace(b' ', b'').split(b',')
pos = len(string)
else:
if pos_sep < pos_open and open_bracket == 1:
pos_sep = string[pos_sep:pos_open].rfind(b',') + pos_sep
args = args + string[prev_arg_pos:pos_sep].replace(b' ', b'').split(b',')
prev_arg_pos = pos_sep + 1
if pos_open < pos_close:
open_bracket = open_bracket + 1
pos = pos_open + 1
else:
open_bracket = open_bracket - 1
if open_bracket == 1:
args.append(string[prev_arg_pos:pos_close + 1].strip())
prev_arg_pos = string.find(b',', pos_close+1) + 1
pos = prev_arg_pos
else:
pos = pos_close + 1
return args
| {
"pile_set_name": "Github"
} |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: CodeContext.py
"""CodeContext - Extension to display the block context above the edit window
Once code has scrolled off the top of a window, it can be difficult to
determine which block you are in. This extension implements a pane at the top
of each IDLE edit window which provides block structure hints. These hints are
the lines which contain the block opening keywords, e.g. 'if', for the
enclosing block. The number of hint lines is determined by the numlines
variable in the CodeContext section of config-extensions.def. Lines which do
not open blocks are not shown in the context hints pane.
"""
import Tkinter
from Tkconstants import TOP, LEFT, X, W, SUNKEN
import re
from sys import maxint as INFINITY
from idlelib.configHandler import idleConf
BLOCKOPENERS = set(['class', 'def', 'elif', 'else', 'except', 'finally', 'for',
'if', 'try', 'while', 'with'])
UPDATEINTERVAL = 100
FONTUPDATEINTERVAL = 1000
getspacesfirstword = lambda s, c=re.compile('^(\\s*)(\\w*)'): c.match(s).groups()
class CodeContext:
menudefs = [
(
'options', [('!Code Conte_xt', '<<toggle-code-context>>')])]
context_depth = idleConf.GetOption('extensions', 'CodeContext', 'numlines', type='int', default=3)
bgcolor = idleConf.GetOption('extensions', 'CodeContext', 'bgcolor', type='str', default='LightGray')
fgcolor = idleConf.GetOption('extensions', 'CodeContext', 'fgcolor', type='str', default='Black')
def __init__(self, editwin):
self.editwin = editwin
self.text = editwin.text
self.textfont = self.text['font']
self.label = None
self.info = [
(
0, -1, '', False)]
self.topvisible = 1
visible = idleConf.GetOption('extensions', 'CodeContext', 'visible', type='bool', default=False)
if visible:
self.toggle_code_context_event()
self.editwin.setvar('<<toggle-code-context>>', True)
self.text.after(UPDATEINTERVAL, self.timer_event)
self.text.after(FONTUPDATEINTERVAL, self.font_timer_event)
return
def toggle_code_context_event(self, event=None):
if not self.label:
widgets = (
self.editwin.text, self.editwin.text_frame)
padx = 0
for widget in widgets:
padx += int(str(widget.pack_info()['padx']))
padx += int(str(widget.cget('padx')))
border = 0
for widget in widgets:
border += int(str(widget.cget('border')))
self.label = Tkinter.Label(self.editwin.top, text='\n' * (self.context_depth - 1), anchor=W, justify=LEFT, font=self.textfont, bg=self.bgcolor, fg=self.fgcolor, width=1, padx=padx, border=border, relief=SUNKEN)
self.label.pack(side=TOP, fill=X, expand=False, before=self.editwin.text_frame)
else:
self.label.destroy()
self.label = None
idleConf.SetOption('extensions', 'CodeContext', 'visible', str(self.label is not None))
idleConf.SaveUserCfgFiles()
return
def get_line_info(self, linenum):
"""Get the line indent value, text, and any block start keyword
If the line does not start a block, the keyword value is False.
The indentation of empty lines (or comment lines) is INFINITY.
"""
text = self.text.get('%d.0' % linenum, '%d.end' % linenum)
spaces, firstword = getspacesfirstword(text)
opener = firstword in BLOCKOPENERS and firstword
if len(text) == len(spaces) or text[len(spaces)] == '#':
indent = INFINITY
else:
indent = len(spaces)
return (indent, text, opener)
def get_context(self, new_topvisible, stopline=1, stopindent=0):
"""Get context lines, starting at new_topvisible and working backwards.
Stop when stopline or stopindent is reached. Return a tuple of context
data and the indent level at the top of the region inspected.
"""
lines = []
lastindent = INFINITY
for linenum in xrange(new_topvisible, stopline - 1, -1):
indent, text, opener = self.get_line_info(linenum)
if indent < lastindent:
lastindent = indent
if opener in ('else', 'elif'):
lastindent += 1
if opener and linenum < new_topvisible and indent >= stopindent:
lines.append((linenum, indent, text, opener))
if lastindent <= stopindent:
break
lines.reverse()
return (
lines, lastindent)
def update_code_context(self):
"""Update context information and lines visible in the context pane.
"""
new_topvisible = int(self.text.index('@0,0').split('.')[0])
if self.topvisible == new_topvisible:
return
if self.topvisible < new_topvisible:
lines, lastindent = self.get_context(new_topvisible, self.topvisible)
while self.info[-1][1] >= lastindent:
del self.info[-1]
elif self.topvisible > new_topvisible:
stopindent = self.info[-1][1] + 1
while self.info[-1][0] >= new_topvisible:
stopindent = self.info[-1][1]
del self.info[-1]
lines, lastindent = self.get_context(new_topvisible, self.info[-1][0] + 1, stopindent)
self.info.extend(lines)
self.topvisible = new_topvisible
context_strings = [
''] * max(0, self.context_depth - len(self.info))
context_strings += [ x[2] for x in self.info[-self.context_depth:] ]
self.label['text'] = '\n'.join(context_strings)
def timer_event(self):
if self.label:
self.update_code_context()
self.text.after(UPDATEINTERVAL, self.timer_event)
def font_timer_event(self):
newtextfont = self.text['font']
if self.label and newtextfont != self.textfont:
self.textfont = newtextfont
self.label['font'] = self.textfont
self.text.after(FONTUPDATEINTERVAL, self.font_timer_event) | {
"pile_set_name": "Github"
} |
package mekanism.generators.client.model;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
public class ModelBioGenerator extends ModelBase
{
ModelRenderer Base;
ModelRenderer Pipe1;
ModelRenderer Pipe2;
ModelRenderer ContainerLid;
ModelRenderer ContainerRight;
ModelRenderer ContainerBottom;
ModelRenderer ContainerFront;
ModelRenderer ContainerBack;
ModelRenderer ContainerLeft;
ModelRenderer Decor1;
ModelRenderer Decor2;
ModelRenderer BackTop;
ModelRenderer FrontPanel1;
ModelRenderer FrontPanel2;
ModelRenderer LeftPanel;
ModelRenderer RightPanel;
ModelRenderer BackPanel;
public ModelBioGenerator()
{
textureWidth = 64;
textureHeight = 64;
Base = new ModelRenderer(this, 0, 0);
Base.addBox(0F, 0F, 0F, 14, 1, 14);
Base.setRotationPoint(-7F, 23F, -7F);
Base.setTextureSize(64, 64);
Base.mirror = true;
setRotation(Base, 0F, 0F, 0F);
Pipe1 = new ModelRenderer(this, 0, 16);
Pipe1.addBox(0F, 0F, 0F, 2, 2, 2);
Pipe1.setRotationPoint(-1F, 13F, -3F);
Pipe1.setTextureSize(64, 64);
Pipe1.mirror = true;
setRotation(Pipe1, 0F, 0F, 0F);
Pipe2 = new ModelRenderer(this, 0, 21);
Pipe2.addBox(0F, 0F, 0F, 2, 2, 8);
Pipe2.setRotationPoint(-1F, 11F, -3F);
Pipe2.setTextureSize(64, 64);
Pipe2.mirror = true;
setRotation(Pipe2, 0F, 0F, 0F);
ContainerLid = new ModelRenderer(this, 0, 32);
ContainerLid.addBox(0F, 0F, 0F, 4, 1, 4);
ContainerLid.setRotationPoint(-2F, 15F, -5F);
ContainerLid.setTextureSize(64, 64);
ContainerLid.mirror = true;
setRotation(ContainerLid, 0F, 0F, 0F);
ContainerRight = new ModelRenderer(this, 0, 38);
ContainerRight.addBox(0F, 0F, 0F, 1, 6, 4);
ContainerRight.setRotationPoint(2F, 16F, -5F);
ContainerRight.setTextureSize(64, 64);
ContainerRight.mirror = true;
setRotation(ContainerRight, 0F, 0F, 0F);
ContainerBottom = new ModelRenderer(this, 0, 49);
ContainerBottom.addBox(0F, 0F, 0F, 6, 1, 6);
ContainerBottom.setRotationPoint(-3F, 22F, -6F);
ContainerBottom.setTextureSize(64, 64);
ContainerBottom.mirror = true;
setRotation(ContainerBottom, 0F, 0F, 0F);
ContainerFront = new ModelRenderer(this, 11, 41);
ContainerFront.addBox(0F, 0F, 0F, 6, 6, 1);
ContainerFront.setRotationPoint(-3F, 16F, -6F);
ContainerFront.setTextureSize(64, 64);
ContainerFront.mirror = true;
setRotation(ContainerFront, 0F, 0F, 0F);
ContainerBack = new ModelRenderer(this, 11, 41);
ContainerBack.addBox(0F, 0F, 0F, 6, 6, 1);
ContainerBack.setRotationPoint(-3F, 16F, -1F);
ContainerBack.setTextureSize(64, 64);
ContainerBack.mirror = true;
setRotation(ContainerBack, 0F, 0F, 0F);
ContainerLeft = new ModelRenderer(this, 0, 38);
ContainerLeft.addBox(0F, 0F, 0F, 1, 6, 4);
ContainerLeft.setRotationPoint(-3F, 16F, -5F);
ContainerLeft.setTextureSize(64, 64);
setRotation(ContainerLeft, 0F, 0F, 0F);
ContainerLeft.mirror = false;
Decor1 = new ModelRenderer(this, 21, 20);
Decor1.addBox(0F, 0F, 0F, 2, 2, 3);
Decor1.setRotationPoint(4.1F, 15F, 2F);
Decor1.setTextureSize(64, 64);
Decor1.mirror = true;
setRotation(Decor1, 0F, 0F, 0F);
Decor2 = new ModelRenderer(this, 21, 20);
Decor2.addBox(0F, 0F, 0F, 2, 2, 3);
Decor2.setRotationPoint(-6.1F, 15F, 2F);
Decor2.setTextureSize(64, 64);
Decor2.mirror = true;
setRotation(Decor2, 0F, 0F, 0F);
BackTop = new ModelRenderer(this, 21, 26);
BackTop.addBox(0F, 0F, 0F, 8, 1, 3);
BackTop.setRotationPoint(-4F, 10F, 5F);
BackTop.setTextureSize(64, 64);
BackTop.mirror = true;
setRotation(BackTop, 0F, 0F, 0F);
FrontPanel1 = new ModelRenderer(this, 17, 32);
FrontPanel1.addBox(0F, 0F, 0F, 3, 6, 2);
FrontPanel1.setRotationPoint(-7F, 17F, -6F);
FrontPanel1.setTextureSize(64, 64);
FrontPanel1.mirror = true;
setRotation(FrontPanel1, 0F, 0F, 0F);
FrontPanel2 = new ModelRenderer(this, 17, 32);
FrontPanel2.addBox(0F, 0F, 0F, 3, 6, 2);
FrontPanel2.setRotationPoint(4F, 17F, -6F);
FrontPanel2.setTextureSize(64, 64);
FrontPanel2.mirror = true;
setRotation(FrontPanel2, 0F, 0F, 0F);
LeftPanel = new ModelRenderer(this, 28, 31);
LeftPanel.addBox(0F, 0F, 0F, 3, 7, 10);
LeftPanel.setRotationPoint(-7F, 16F, -4F);
LeftPanel.setTextureSize(64, 64);
LeftPanel.mirror = true;
setRotation(LeftPanel, 0F, 0F, 0F);
RightPanel = new ModelRenderer(this, 28, 31);
RightPanel.addBox(0F, 0F, 0F, 3, 7, 10);
RightPanel.setRotationPoint(4F, 16F, -4F);
RightPanel.setTextureSize(64, 64);
RightPanel.mirror = true;
setRotation(RightPanel, 0F, 0F, 0F);
BackPanel = new ModelRenderer(this, 28, 49);
BackPanel.addBox(0F, 0F, 0F, 10, 12, 3);
BackPanel.setRotationPoint(-5F, 11F, 5F);
BackPanel.setTextureSize(64, 64);
BackPanel.mirror = true;
setRotation(BackPanel, 0F, 0F, 0F);
}
public void render(float size)
{
Base.render(size);
Pipe1.render(size);
Pipe2.render(size);
ContainerLid.render(size);
ContainerRight.render(size);
ContainerBottom.render(size);
ContainerFront.render(size);
ContainerBack.render(size);
ContainerLeft.render(size);
Decor1.render(size);
Decor2.render(size);
BackTop.render(size);
FrontPanel1.render(size);
FrontPanel2.render(size);
LeftPanel.render(size);
RightPanel.render(size);
BackPanel.render(size);
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
}
| {
"pile_set_name": "Github"
} |
#!/bin/bash
#
# docker-entrypoint for docker-solr
set -e
if [[ "$VERBOSE" == "yes" ]]; then
set -x
fi
if [[ -v SOLR_PORT ]] && ! grep -E -q '^[0-9]+$' <<<"${SOLR_PORT:-}"; then
SOLR_PORT=8983
export SOLR_PORT
fi
# when invoked with e.g.: docker run solr -help
if [ "${1:0:1}" == '-' ]; then
set -- solr-foreground "$@"
fi
# execute command passed in as arguments.
# The Dockerfile has specified the PATH to include
# /opt/solr/bin (for Solr) and /opt/docker-solr/scripts (for our scripts
# like solr-foreground, solr-create, solr-precreate, solr-demo).
# Note: if you specify "solr", you'll typically want to add -f to run it in
# the foreground.
exec "$@"
| {
"pile_set_name": "Github"
} |
import {
METRICS_CLICK,
METRICS_DATA_ACCESS,
METRICS_MAP,
METRICS_SPATIAL_EDIT,
METRICS_TIMELINE,
METRICS_TIMING,
METRICS_COLLECTION_SORT_CHANGE
} from './constants'
export const metricsDataAccess = payload => ({
type: METRICS_DATA_ACCESS,
payload
})
export const metricsClick = payload => ({
type: METRICS_CLICK,
payload
})
export const metricsTimeline = type => ({
type: METRICS_TIMELINE,
payload: {
eventLabel: type
}
})
export const metricsMap = type => ({
type: METRICS_MAP,
payload: {
eventLabel: type
}
})
export const metricsSpatialEdit = payload => ({
type: METRICS_SPATIAL_EDIT,
payload
})
export const metricsTiming = payload => ({
type: METRICS_TIMING,
payload
})
export const metricsCollectionSortChange = payload => ({
type: METRICS_COLLECTION_SORT_CHANGE,
payload
})
| {
"pile_set_name": "Github"
} |
const __ = require('config').universalPath
const _ = __.require('builders', 'utils')
const error_ = __.require('lib', 'error/error')
const responses_ = __.require('lib', 'responses')
const notifs_ = __.require('lib', 'notifications')
const get = (req, res) => {
if (req.user == null) return error_.unauthorizedApiAccess(req, res)
return notifs_.byUserId(req.user._id)
.then(responses_.Wrap(res, 'notifications'))
.catch(error_.Handler(req, res))
}
const updateStatus = (req, res) => {
if (req.user == null) return error_.unauthorizedApiAccess(req, res)
const reqUserId = req.user._id
const { times } = req.body
if (!_.isArray(times) || (times.length <= 0)) return _.ok(res)
// could probably be replaced by a batch operation
return Promise.all(times.map(notifs_.updateReadStatus.bind(null, reqUserId)))
.then(() => {
_.success([ reqUserId, times ], 'notifs marked as read')
responses_.ok(res)
})
.catch(error_.Handler(req, res))
}
module.exports = {
get,
post: updateStatus
}
| {
"pile_set_name": "Github"
} |
export { AdvancedPieChartWidgetComponent } from './advanced-pie-chart-widget/advanced-pie-chart-widget.component';
export { AudienceOverviewWidgetComponent } from './audience-overview-widget/audience-overview-widget.component';
export { BarChartWidgetComponent } from './bar-chart-widget/bar-chart-widget.component';
export { DonutChartWidgetComponent } from './donut-chart-widget/donut-chart-widget.component';
export { LineChartWidgetComponent } from './line-chart-widget/line-chart-widget.component';
export { MarketWidgetComponent } from './market-widget/market-widget.component';
export { QuickInfoWidgetComponent } from './quick-info-widget/quick-info-widget.component';
export { RealtimeUsersWidgetComponent } from './realtime-users-widget/realtime-users-widget.component';
export {
RecentSalesWidgetTableComponent,
} from './recent-sales-widget/recent-sales-widget-table/recent-sales-widget-table.component';
export { RecentSalesWidgetComponent } from './recent-sales-widget/recent-sales-widget.component';
export { SalesSummaryWidgetComponent } from './sales-summary-widget/sales-summary-widget.component';
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio 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.
*
* Pydio 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 Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
// Import Builder class
import Builder from './Builder'
import TemplateBuilder from './TemplateBuilder'
import AsyncComponent from './AsyncComponent'
import BackgroundImage from './BackgroundImage'
import AsyncModal from './modal/AsyncModal'
import ActionDialogMixin from './modal/ActionDialogMixin'
import CancelButtonProviderMixin from './modal/CancelButtonProviderMixin'
import SubmitButtonProviderMixin from './modal/SubmitButtonProviderMixin'
import Modal from './modal/Modal'
import ConfirmDialog from './modal/ConfirmDialog'
import PromptDialog from './modal/PromptDialog'
import ActivityWarningDialog from './modal/ActivityWarningDialog'
import ServerPromptDialog from './modal/ServerPromptDialog'
import MessageBar from './modal/MessageBar'
import AbstractDialogModifier from './modal/AbstractDialogModifier'
import Loader from './Loader'
import Router from './router/Router'
import NetworkLoader from './modal/NetworkLoader'
import HiddenDownloadForm from './HiddenDownloadForm'
import PydioContextProvider from './PydioContextProvider'
import PydioContextConsumer from './PydioContextConsumer'
import CompatMigrationDialog from './compat/CompatMigrationDialog'
import CompatModal from './compat/CompatModal'
export {
Builder,
TemplateBuilder,
AsyncComponent,
AsyncModal,
ActionDialogMixin,
CancelButtonProviderMixin,
SubmitButtonProviderMixin,
AbstractDialogModifier,
Modal,
ConfirmDialog,
PromptDialog,
ServerPromptDialog,
ActivityWarningDialog,
Loader,
Router,
MessageBar,
NetworkLoader,
HiddenDownloadForm,
BackgroundImage,
PydioContextProvider,
PydioContextConsumer,
CompatMigrationDialog,
CompatModal
} | {
"pile_set_name": "Github"
} |
//HEAD_DSPH
/*
<DUALSPHYSICS> Copyright (c) 2020 by Dr Jose M. Dominguez et al. (see http://dual.sphysics.org/index.php/developers/).
EPHYSLAB Environmental Physics Laboratory, Universidade de Vigo, Ourense, Spain.
School of Mechanical, Aerospace and Civil Engineering, University of Manchester, Manchester, U.K.
This file is part of DualSPHysics.
DualSPHysics is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
DualSPHysics is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with DualSPHysics. If not, see <http://www.gnu.org/licenses/>.
*/
/// \file JSphCpuSingle.h \brief Declares the class \ref JSphCpuSingle.
#ifndef _JSphCpuSingle_
#define _JSphCpuSingle_
#include "DualSphDef.h"
#include "JSphCpu.h"
#include <string>
class JCellDivCpuSingle;
//##############################################################################
//# JSphCpuSingle
//##############################################################################
/// \brief Defines the attributes and functions used only in Single-Core implementation.
class JSphCpuSingle : public JSphCpu
{
protected:
JCellDivCpuSingle* CellDivSingle;
llong GetAllocMemoryCpu()const;
void UpdateMaxValues();
void LoadConfig(JSphCfgRun *cfg);
void ConfigDomain();
void ResizeParticlesSize(unsigned newsize,float oversize,bool updatedivide);
unsigned PeriodicMakeList(unsigned np,unsigned pini,bool stable,unsigned nmax,tdouble3 perinc,const tdouble3 *pos,const typecode *code,unsigned *listp)const;
void PeriodicDuplicatePos(unsigned pnew,unsigned pcopy,bool inverse,double dx,double dy,double dz,tuint3 cellmax,tdouble3 *pos,unsigned *dcell)const;
void PeriodicDuplicateVerlet(unsigned np,unsigned pini,tuint3 cellmax,tdouble3 perinc,const unsigned *listp
,unsigned *idp,typecode *code,unsigned *dcell,tdouble3 *pos,tfloat4 *velrhop,tsymatrix3f *spstau,tfloat4 *velrhopm1)const;
void PeriodicDuplicateSymplectic(unsigned np,unsigned pini,tuint3 cellmax,tdouble3 perinc,const unsigned *listp
,unsigned *idp,typecode *code,unsigned *dcell,tdouble3 *pos,tfloat4 *velrhop,tsymatrix3f *spstau,tdouble3 *pospre,tfloat4 *velrhoppre)const;
void PeriodicDuplicateNormals(unsigned np,unsigned pini,tuint3 cellmax //<vs_mddbc>
,tdouble3 perinc,const unsigned *listp,tfloat3 *motionvel,tfloat3 *normals)const; //<vs_mddbc>
void RunPeriodic();
void RunCellDivide(bool updateperiodic);
void AbortBoundOut();
void Interaction_Forces(TpInterStep tinterstep);
void MdbcBoundCorrection(); //<vs_mddbc>
double ComputeAceMax(unsigned np,const tfloat3* ace,const typecode *code)const;
template<bool checkcode> double ComputeAceMaxSeq(unsigned np,const tfloat3* ace,const typecode *code)const;
template<bool checkcode> double ComputeAceMaxOmp(unsigned np,const tfloat3* ace,const typecode *code)const;
double ComputeStep(){ return(TStep==STEP_Verlet? ComputeStep_Ver(): ComputeStep_Sym()); }
double ComputeStep_Ver();
double ComputeStep_Sym();
inline tfloat3 FtPeriodicDist(const tdouble3 &pos,const tdouble3 ¢er,float radius)const;
void FtCalcForcesSum(unsigned cf,tfloat3 &face,tfloat3 &fomegaace)const;
void FtCalcForces(StFtoForces *ftoforces)const;
void FtCalcForcesRes(double dt,const StFtoForces *ftoforces,StFtoForcesRes *ftoforcesres)const;
void FtApplyImposedVel(StFtoForcesRes *ftoforcesres)const; //<vs_fttvel>
void FtSumExternalForces(unsigned cf,tfloat3 &face,tfloat3 &fomegaace)const;//<vs_fttvel>
void FtApplyConstraints(StFtoForces *ftoforces,StFtoForcesRes *ftoforcesres)const;
void RunFloating(double dt,bool predictor);
void RunGaugeSystem(double timestep);
void ComputePips(bool run);
void SaveData();
void FinishRun(bool stop);
public:
JSphCpuSingle();
~JSphCpuSingle();
void Run(std::string appname,JSphCfgRun *cfg,JLog2 *log);
//<vs_innlet_ini>
//-Code for InOut in JSphCpuSingle_InOut.cpp
//--------------------------------------------
protected:
void InOutInit(double timestepini);
void InOutIgnoreFluidDef(const std::vector<unsigned> &mkfluidlist);
void InOutCheckProximity(unsigned newnp);
void InOutComputeStep(double stepdt);
void InOutCalculeZsurf();
void InOutExtrapolateData(unsigned inoutcount,const int *inoutpart);
void BoundCorrectionData();
//<vs_innlet_end>
};
#endif
| {
"pile_set_name": "Github"
} |
package ghissues.gh928;
import javax.persistence.Entity;
@Entity
public class Department extends BaseModel {
public String name;
}
| {
"pile_set_name": "Github"
} |
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Set of functions related to applying transformations for VIEWs
*
* @package PhpMyAdmin
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* Get the column details of VIEW with its original references
*
* @param string $sql_query SQL for original resource
* @param array $view_columns Columns of VIEW if defined new column names
*
* @return array $column_map Details of VIEW columns
*/
function PMA_getColumnMap($sql_query, $view_columns)
{
$column_map = array();
// Select query which give results for VIEW
$real_source_result = PMA_DBI_try_query($sql_query);
if ($real_source_result !== false) {
$real_source_fields_meta = PMA_DBI_get_fields_meta($real_source_result);
if (count($real_source_fields_meta) > 0) {
for ($i=0; $i<count($real_source_fields_meta); $i++) {
$map = array();
$map['table_name'] = $real_source_fields_meta[$i]->table;
$map['refering_column'] = $real_source_fields_meta[$i]->name;
if (count($view_columns) > 1) {
$map['real_column'] = $view_columns[$i];
}
$column_map[] = $map;
}
}
}
unset($real_source_result);
return $column_map;
}
/**
* Get existing data on tranformations applyed for
* columns in a particular table
*
* @param string $db Database name looking for
*
* @return mysqli_result Result of executed SQL query
*/
function PMA_getExistingTranformationData($db)
{
$cfgRelation = PMA_getRelationsParam();
// Get the existing transformation details of the same database
// from pma__column_info table
$pma_transformation_sql = 'SELECT * FROM '
. PMA_Util::backquote($cfgRelation['db']) . '.'
. PMA_Util::backquote($cfgRelation['column_info'])
. ' WHERE `db_name` = \''
. PMA_Util::sqlAddSlashes($db) . '\'';
return PMA_DBI_try_query($pma_transformation_sql);
}
/**
* Get SQL query for store new transformation details of a VIEW
*
* @param mysqli_result $pma_tranformation_data Result set of SQL execution
* @param array $column_map Details of VIEW columns
* @param string $view_name Name of the VIEW
* @param string $db Database name of the VIEW
*
* @return string $new_transformations_sql SQL query for new tranformations
*/
function PMA_getNewTransformationDataSql(
$pma_tranformation_data, $column_map, $view_name, $db
) {
$cfgRelation = PMA_getRelationsParam();
// Need to store new transformation details for VIEW
$new_transformations_sql = 'INSERT INTO '
. PMA_Util::backquote($cfgRelation['db']) . '.'
. PMA_Util::backquote($cfgRelation['column_info'])
. ' (`db_name`, `table_name`, `column_name`, `comment`, '
. '`mimetype`, `transformation`, `transformation_options`)'
. ' VALUES ';
$column_count = 0;
$add_comma = false;
while ($data_row = PMA_DBI_fetch_assoc($pma_tranformation_data)) {
foreach ($column_map as $column) {
if ($data_row['table_name'] == $column['table_name']
&& $data_row['column_name'] == $column['refering_column']
) {
$new_transformations_sql .= $add_comma ? ', ' : '';
$new_transformations_sql .= '('
. '\'' . $db . '\', '
. '\'' . $view_name . '\', '
. '\'';
$new_transformations_sql .= (isset($column['real_column']))
? $column['real_column']
: $column['refering_column'];
$new_transformations_sql .= '\', '
. '\'' . $data_row['comment'] . '\', '
. '\'' . $data_row['mimetype'] . '\', '
. '\'' . $data_row['transformation'] . '\', '
. '\''
. PMA_Util::sqlAddSlashes(
$data_row['transformation_options']
)
. '\')';
$add_comma = true;
$column_count++;
break;
}
}
if ($column_count == count($column_map)) {
break;
}
}
return ($column_count > 0) ? $new_transformations_sql : '';
}
?>
| {
"pile_set_name": "Github"
} |
#
# Password Management Servlets (PWM)
# http://www.pwm-project.org
#
# Copyright (c) 2006-2009 Novell, Inc.
# Copyright (c) 2009-2020 The PWM Project
#
# 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.
#
Password_MissingConfirm=Salasana t\u00e4ytt\u00e4\u00e4 ehdot, sy\u00f6t\u00e4 salasana viel\u00e4 vahvistus kentt\u00e4\u00e4n
Password_DoesNotMatch=Salasanat eiv\u00e4t ole samat
Password_Missing=Salasana puuttuu
Password_PreviouslyUsed=Uutta salasanaa on k\u00e4ytetty aikaisemmin
Password_BadPassword=Uusi salasana ei t\u00e4yt\u00e4 vaatimuksia
# Password_BadOldPassword=
Password_TooLong=Uusi salasana on liian pitk\u00e4
Password_TooShort=Uusi salasana on liian lyhyt
Password_NotEnoughNum=Uudessa salasanassa on liian v\u00e4h\u00e4n numeroita
Password_NotEnoughAlpha=Uudessa salasanassa on liian v\u00e4h\u00e4n kirjaimia
Password_NotEnoughUpper=Uudessa salasanassa on liian v\u00e4h\u00e4n ISOJA kirjaimia
Password_NotEnoughLower=Uudessa salasanassa on liian v\u00e4h\u00e4n pieni\u00e4 kirjaimia
Password_NotEnoughSpecial=Uudessa salasanassa on liian v\u00e4h\u00e4n erikoismerkkej\u00e4
Password_NotEnoughUnique=Uudessa salasanassa on liian v\u00e4h\u00e4n uniikkeja merkkej\u00e4
Password_TooManyRepeat=Uudessa salasanassa on liian monta samaa merkki\u00e4 per\u00e4kk\u00e4in
Password_TooManySpecial=Uudessa salasanassa on liian monta erikoismerkki\u00e4
Password_TooManyAlpha=Uudessa salasanassa on liian monta kirjainta
Password_TooManyNumeric=Uudessa salasanassa on liian monta numeroa
Password_TooManyLower=Uudessa salasanassa on liian monta pient\u00e4 kirjainta
Password_TooManyUpper=Uudessa salasanassa on liian monta ISOA kirjainta
Password_TooManyOldChars=Uudessa salasanassa on liian monta samaa merkki\u00e4 kuin vanhassa salasanassa
Password_TooManyNonAlphaSpecial=Uudessa salasanassa on liian monta erikoismerkki\u00e4
Password_InvalidChar=Uudessa salasanassa on kielletty merkki
Password_RequiredMissing=Uudesta salasanasta puuttuu vaadittu merkki
Password_InWordlist=Uusi salasana on liian yleinen
Password_SameAsOld=Uusi salasana on sama kuin nykyinen
Password_SameAsAttr=Uusi salasana on liian heikko
Password_FirstIsNumeric=Ensimm\u00e4inen merkki ei saa olla numeerinen
Password_LastIsNumeric=Viimeinen merkki ei saa olla numeerinen
Password_FirstIsSpecial=Ensimm\u00e4inen merkki ei saa olla erikoismerkki
Password_LastIsSpecial=Viimeinen merkki ei saa olla erikoismerkki
Password_HistoryFull=Salasana historia on t\u00e4ynn\u00e4
Password_MeetsRules=Uusi salasana on hyv\u00e4ksytty, klikkaa Vaihda salasana - nappulaa jatkaaksesi
Password_TooSoon=Edellisest\u00e4 salasanan vaihdosta ei ole kulunut tarpeeksi aikaa.
Password_UsingDisallowedValue=Uusi salasana ei ole sallittu
Password_TooWeak=Uusi salasana on liian heikko, lis\u00e4\u00e4 erikokoisia kirjaimia, numeroita tai erikoismerkkej\u00e4.
Password_TooManyNonAlpha=Uudessa salasanassa on liian monta merkki\u00e4, jotka eiv\u00e4t ole kirjaimia
Password_NotEnoughNonAlpha=Uudessa salasanassa on liian v\u00e4h\u00e4n muita merkkej\u00e4 kuin kirjaimia
Password_UnknownValidation=Uusi salasana ei t\u00e4yt\u00e4 vaatimuksia, sy\u00f6t\u00e4 toinen salasana.
Error_WrongResponse=Yksi tai useampi vastauksista on v\u00e4\u00e4rin. Yrit\u00e4 uudelleen.
Error_WrongPassword=K\u00e4ytt\u00e4j\u00e4tunnus tai salasana ei kelpaa, yrit\u00e4 uudelleen.
Error_Response_NoResponse=K\u00e4ytt\u00e4j\u00e4tunnusta ei l\u00f6ydy tai tarvittavat tiedot unohtuneen salasanan vaihtoon puuttuvat
Error_Response_TooShort=Vastauksesi kysymykseen "%1%" on liian lyhyt
Error_Response_Wordlist=Vastauksesi kysymykseen "%1%" on liian yleinen
Error_Response_TooLong=Vastauksesi kysymykseen "%1%" on liian pitk\u00e4
Error_Response_Duplicate=Vastauksesi kysymykseen "%1%" ei saa olla sama kuin toisen kysymyksen vastaus
Error_Challenge_Duplicate=Kysymyksien tulee olla uniikkeja.
Error_Missing_Challenge_Text=K\u00e4ytt\u00e4j\u00e4n sy\u00f6tt\u00e4m\u00e4st\u00e4 kysymyksest\u00e4 puuttuu teksti
Error_UserAuthenticated=Olet jo kirjautunut palveluun.
Error_MissingParameter=Vaadittu parametri puuttuu.
Error_DirectoryUnavailable=Hakemistoon ei saada yhteytt\u00e4. Jos virhe toistuu ota yhteytt\u00e4 helpdeskiin.
Error_Internal=Tuntematon virhe. Jos virhe toistuu ota yhteytt\u00e4 helpdeskiin.
Error_ActivationValidationFailed=Yksi tai useampi arvoista on v\u00e4\u00e4rin.
Error_CantMatchUser=K\u00e4ytt\u00e4j\u00e4\u00e4 ei l\u00f6ydy, yrit\u00e4 uudelleen.
Error_ServiceNotAvailable=Palvelu ei ole aktivoitu.
Error_UserMisMatch=Tapahtui virhe tunnistautumisessa, sulje selain.
Error_ActivateUserNoQueryMatch=Tunnustasi ei voida aktivoida.
Error_AuthenticationRequired=Tunnistautuminen vaaditaan.
Error_NoChallenges=Haasteita ei ole konfiguroitu.
Error_UserIntruder=K\u00e4ytt\u00e4j\u00e4tunnuksellasi on yritetty kirjautua liian monta kertaa. Yrit\u00e4 my\u00f6hemmin uudelleen.
Error_AddressIntruder=T\u00e4st\u00e4 IP osoitteesta on yritetty kirjautua liian monta kertaa. Yrit\u00e4 my\u00f6hemmin uudelleen.
Error_SessionIntruder=T\u00e4ss\u00e4 istunnossa on yritetty kirjautua liian monta kertaa.
Error_BadSessionPassword=Session salasanan luonti ei onnistu.
Error_Unauthorized=Tunnuksellasi ei ole oikeuksia suorittaa pyydetty\u00e4 toimintoa.
Error_BadSession=Yhteys selaimeen ei onnistu. Sulje selain ja yrit\u00e4 uudelleen.
Error_MissingRequiredResponse=Sy\u00f6t\u00e4 kaikki pakollisen vastaukset.
Error_MissingRandomResponse=Sy\u00f6t\u00e4 viel\u00e4 yksi satunnainen vastaus.
Error_BadCaptchaResponse=Koodi ei kelpaa, yrit\u00e4 uudelleen.
Error_CaptchaAPIError=Tapahtui virhe captcha vastausta vahvistettaessa, sulje selain ja yrit\u00e4 uudelleen. Mik\u00e4li virhe toistuu ota yhteytt\u00e4 yll\u00e4pitoon.
Error_InvalidConfig=Sovelluksen konfiguraatio on ep\u00e4kelpo tai vioittunut. Korjaa virhe tai poista konfiguraatio tiedosto.
Error_InvalidFormID=Selainsessiosi on vanhentunut. Sulje selain ja yrit\u00e4 uudelleen.
Error_TokenMissingContact=Tunnuksestasi puuttuu tarvittavat yhteystiedot. Ota yhteytt\u00e4 yll\u00e4pitoon.
Error_TokenIncorrect=Koodi ei kelpaa, yrit\u00e4 uudelleen.
Error_BadCurrentPassword=Salasana on v\u00e4\u00e4r\u00e4, yrit\u00e4 uudelleen.
Error_Closing=Operaatiota ei voida suorittaa loppuun, koska palvelua ollaan sammuttamassa.
Error_Missing_GUID=Tunnuksen GUID tietoa ei l\u00f6ydy. Ota yhteytt\u00e4 yll\u00e4pitoon.
Error_TokenExpired=Sy\u00f6tt\u00e4m\u00e4si token on vanhentunut, yrit\u00e4 uudelleen.
Error_SecureRequestRequired=Salaamaton yhteys (HTTP) ei ole sallittu. Yrit\u00e4 uudelleen salatulla (HTTPS) yhteydell\u00e4.
Error_Writing_Responses=Tapahtui virhe tallennettaessa kysymyksien vastauksia. Ota yhteytt\u00e4 yll\u00e4pitoon.
Error_Unlock_Failure=Tapahtui virhe avatessa tunnustasi. Ota yhteytt\u00e4 yll\u00e4pitoon.
Error_Update_Attrs_Failure=Tapahtui virhe tallennettaessa profiilisi tietoja. Ota yhteytt\u00e4 yll\u00e4pitoon.
Error_Activation_Failure=Tapahtui virhe tunnuksen aktivoinnissa. Ota yhteytt\u00e4 yll\u00e4pitoon.
Error_NewUser_Failure=Tapahtui virhe luotaessa uutta k\u00e4ytt\u00e4j\u00e4tunnusta. Ota yhteytt\u00e4 yll\u00e4pitoon.
Error_Activation=Tunnuksen aktivointi ei onnistu sy\u00f6tt\u00e4mill\u00e4si tiedoilla, yrit\u00e4 uudelleen.
Error_DB_Unavailable=Tietokantaan ei saada yhteytt\u00e4. Jos virhe toistuu ota yhteytt\u00e4 helpdeskiin.
Error_LocalDB_Unavailable=Tietokantaan ei saada yhteytt\u00e4. Jos virhe toistuu ota yhteytt\u00e4 helpdeskiin.
Error_App_Unavailable=Sovellukseen ei saada yhteytt\u00e4 tai se on juuri k\u00e4ynnistym\u00e4ss\u00e4. Jos virhe toistuu ota yhteytt\u00e4 helpdeskiin.
Error_FieldRequired=%1% vaaditaan
Error_FieldNotANumber=%1% pit\u00e4\u00e4 olla numero
Error_FieldInvalidEmail=%1% ei ole s\u00e4hk\u00f6postiosoite
Error_FieldTooShort="%1%" on liian lyhyt
Error_FieldTooLong=%1% on liian pitk\u00e4
Error_FieldDuplicate=%1% on jo k\u00e4yt\u00f6ss\u00e4, kokeile toista arvoa
Error_FieldBadConfirm=%1% tiedot eiv\u00e4t ole samat
Error_ConfigUploadSuccess=Tiedosto siirretty
Error_ConfigUploadFailure=Tiedoston siirto ep\u00e4onnistui: %1%
Error_ConfigSaveSuccess=Konfiguraatio on tallennettu. PWM uudelleen k\u00e4ynnistys aloitettu. PWM saattaa olla pois k\u00e4yt\u00f6st\u00e4 k\u00e4ynnistyksen aikana. Jos uudelleen k\u00e4ynnistys ep\u00e4onnistuu k\u00e4ynnist\u00e4 PWM manuaalisesti.
Error_ConfigFormatError=Konfuguraation muodossa vikaa: %1%
Error_ConfigLdapFailure=Yhteys LDAP palvelimeen ei onnistu: %1%
Error_ConfigLdapSuccess=Yhteys LDAP hakemistoon onnistui
Error_HTTP_404=Hakemaasi sivua ei l\u00f6ydy.
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.