text
stringlengths 2
99.9k
| meta
dict |
---|---|
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<body style="font-family:sans-serif">
<table border width="1"><tr><td>
a bcd<span>efg</span>hij k
</td></tr></table>
</body>
| {
"pile_set_name": "Github"
} |
use super::{Map, InitialMapBuilder, BuilderMap, TileType};
use rltk::RandomNumberGenerator;
pub struct MazeBuilder {}
impl InitialMapBuilder for MazeBuilder {
#[allow(dead_code)]
fn build_map(&mut self, rng: &mut rltk::RandomNumberGenerator, build_data : &mut BuilderMap) {
self.build(rng, build_data);
}
}
impl MazeBuilder {
#[allow(dead_code)]
pub fn new() -> Box<MazeBuilder> {
Box::new(MazeBuilder{})
}
#[allow(clippy::map_entry)]
fn build(&mut self, rng : &mut RandomNumberGenerator, build_data : &mut BuilderMap) {
// Maze gen
let mut maze = Grid::new((build_data.map.width / 2)-2, (build_data.map.height / 2)-2, rng);
maze.generate_maze(build_data);
}
}
/* Maze code taken under MIT from https://github.com/cyucelen/mazeGenerator/ */
const TOP : usize = 0;
const RIGHT : usize = 1;
const BOTTOM : usize = 2;
const LEFT : usize = 3;
#[derive(Copy, Clone)]
struct Cell {
row: i32,
column: i32,
walls: [bool; 4],
visited: bool,
}
impl Cell {
fn new(row: i32, column: i32) -> Cell {
Cell{
row,
column,
walls: [true, true, true, true],
visited: false
}
}
fn remove_walls(&mut self, next : &mut Cell) {
let x = self.column - next.column;
let y = self.row - next.row;
if x == 1 {
self.walls[LEFT] = false;
next.walls[RIGHT] = false;
}
else if x == -1 {
self.walls[RIGHT] = false;
next.walls[LEFT] = false;
}
else if y == 1 {
self.walls[TOP] = false;
next.walls[BOTTOM] = false;
}
else if y == -1 {
self.walls[BOTTOM] = false;
next.walls[TOP] = false;
}
}
}
struct Grid<'a> {
width: i32,
height: i32,
cells: Vec<Cell>,
backtrace: Vec<usize>,
current: usize,
rng : &'a mut RandomNumberGenerator
}
impl<'a> Grid<'a> {
fn new(width: i32, height:i32, rng: &mut RandomNumberGenerator) -> Grid {
let mut grid = Grid{
width,
height,
cells: Vec::new(),
backtrace: Vec::new(),
current: 0,
rng
};
for row in 0..height {
for column in 0..width {
grid.cells.push(Cell::new(row, column));
}
}
grid
}
fn calculate_index(&self, row: i32, column: i32) -> i32 {
if row < 0 || column < 0 || column > self.width-1 || row > self.height-1 {
-1
} else {
column + (row * self.width)
}
}
fn get_available_neighbors(&self) -> Vec<usize> {
let mut neighbors : Vec<usize> = Vec::new();
let current_row = self.cells[self.current].row;
let current_column = self.cells[self.current].column;
let neighbor_indices : [i32; 4] = [
self.calculate_index(current_row -1, current_column),
self.calculate_index(current_row, current_column + 1),
self.calculate_index(current_row + 1, current_column),
self.calculate_index(current_row, current_column - 1)
];
for i in neighbor_indices.iter() {
if *i != -1 && !self.cells[*i as usize].visited {
neighbors.push(*i as usize);
}
}
neighbors
}
fn find_next_cell(&mut self) -> Option<usize> {
let neighbors = self.get_available_neighbors();
if !neighbors.is_empty() {
if neighbors.len() == 1 {
return Some(neighbors[0]);
} else {
return Some(neighbors[(self.rng.roll_dice(1, neighbors.len() as i32)-1) as usize]);
}
}
None
}
fn generate_maze(&mut self, build_data : &mut BuilderMap) {
let mut i = 0;
loop {
self.cells[self.current].visited = true;
let next = self.find_next_cell();
match next {
Some(next) => {
self.cells[next].visited = true;
self.backtrace.push(self.current);
// __lower_part__ __higher_part_
// / \ / \
// --------cell1------ | cell2-----------
let (lower_part, higher_part) =
self.cells.split_at_mut(std::cmp::max(self.current, next));
let cell1 = &mut lower_part[std::cmp::min(self.current, next)];
let cell2 = &mut higher_part[0];
cell1.remove_walls(cell2);
self.current = next;
}
None => {
if !self.backtrace.is_empty() {
self.current = self.backtrace[0];
self.backtrace.remove(0);
} else {
break;
}
}
}
if i % 50 == 0 {
self.copy_to_map(&mut build_data.map);
build_data.take_snapshot();
}
i += 1;
}
}
fn copy_to_map(&self, map : &mut Map) {
// Clear the map
for i in map.tiles.iter_mut() { *i = TileType::Wall; }
for cell in self.cells.iter() {
let x = cell.column + 1;
let y = cell.row + 1;
let idx = map.xy_idx(x * 2, y * 2);
map.tiles[idx] = TileType::Floor;
if !cell.walls[TOP] { map.tiles[idx - map.width as usize] = TileType::Floor }
if !cell.walls[RIGHT] { map.tiles[idx + 1] = TileType::Floor }
if !cell.walls[BOTTOM] { map.tiles[idx + map.width as usize] = TileType::Floor }
if !cell.walls[LEFT] { map.tiles[idx - 1] = TileType::Floor }
}
}
}
| {
"pile_set_name": "Github"
} |
Description :
Crée un modèle dans l'application LoopBack.
Exemple :
{{slc loopback:model Product}}
Cette opération ajoute une entrée à {{`Product.json`}} définissant le modèle "Product".
| {
"pile_set_name": "Github"
} |
/*
* COPYRIGHT: GPL - See COPYING in the top level directory
* PROJECT: ReactOS Virtual DOS Machine
* FILE: command.S
* PURPOSE: DOS32 command.com for NTVDM
* PROGRAMMERS: Hermes Belusca-Maito ([email protected])
*/
//
// See http://www.ganino.com/games/scripts/dos-6.0%20source%20code%3F/dev/smartdrv/umbload.asm
// and https://books.google.fr/books?id=rtmJgtfaxz8C&pg=PA256&lpg=PA256&dq=int+21+4b+program+exec+block&source=bl&ots=OfAF7qFwfl&sig=PrW73CE1dzFm3rwrTsYZkC77U4Y&hl=en&sa=X&redir_esc=y#v=onepage&q=int%2021%204b%20program%20exec%20block&f=false
//
/* INCLUDES *******************************************************************/
#include <asm.inc>
#include "asmxtras.inc"
#include <isvbop.inc>
#define NDEBUG
/* DEFINES ********************************************************************/
#define MAX_PATH 260
#define DOS_CMDLINE_LENGTH 127
#define DOS_VERSION HEX(0005) // MAKEWORD(5, 00)
#define NTDOS_VERSION HEX(3205) // MAKEWORD(5, 50)
#define SYSTEM_PSP HEX(08)
#define BOP .byte HEX(C4), HEX(C4),
// #define BOP_START_DOS HEX(2C)
#define BOP_CMD HEX(54)
/**** PSP MEMBERS ****/
#define PSP_VAR(x) es:[x]
#define PSP HEX(0000)
#define ParentPsp HEX(0016) // word
#define EnvBlock HEX(002C) // word
#define CmdLineLen HEX(0080) // byte
#define CmdLineStr HEX(0081) // byte[DOS_CMDLINE_LENGTH]
/**** DATA stored inside the stack ****/
#define CmdLine BaseStack // Command line for the program to be started
#define PgmName [CmdLine + (1 + DOS_CMDLINE_LENGTH)]
// WARNING! Using the VAL(x) macro doesn't work with GCC/GAS (because it inserts
// a spurious space in front of the parameter when the macro is expanded).
// So that: 'VAL(foo)' is expanded to: '\ foo', instead of '\foo' as one would expect.
/* NEXT_CMD structure */
STRUCT(NEXT_CMD, 2)
FIELD_DECL(EnvBlockSeg, word, 0)
FIELD_DECL(EnvBlockLen, word, 0)
FIELD_DECL(CurDrive , word, 0)
FIELD_DECL(NumDrives , word, 1)
FIELD_DECL(CmdLineSeg , word, 0)
FIELD_DECL(CmdLineOff , word, 0)
FIELD_DECL(Unknown0 , word, 2)
FIELD_DECL(ExitCode , word, 3)
FIELD_DECL(Unknown1 , word, 4)
FIELD_DECL(Unknown2 , long, 5)
FIELD_DECL(CodePage , word, 6)
FIELD_DECL(Unknown3 , word, 7)
FIELD_DECL(Unknown4 , word, 8)
FIELD_DECL(AppNameSeg , word, 0)
FIELD_DECL(AppNameOff , word, 0)
FIELD_DECL(AppNameLen , word, 0)
FIELD_DECL(Flags , word, 0)
ENDS(NEXT_CMD)
/* DOS_EXEC_PARAM_BLOCK structure */
STRUCT(DOS_EXEC_PARAM_BLOCK, 2)
FIELD_DECL(EnvSeg, word, 0) // Use parent's environment (ours)
FIELD_DECL(CmdLineOff, word, OFF(CmdLine))
FIELD_DECL(CmdLineSeg, word, 0)
FIELD_DECL(Fcb1Off, word, OFF(Fcb1))
FIELD_DECL(Fcb1Seg, word, 0)
FIELD_DECL(Fcb2Off, word, OFF(Fcb2))
FIELD_DECL(Fcb2Seg, word, 0)
ENDS(DOS_EXEC_PARAM_BLOCK)
/* RESIDENT CODE AND DATA *****************************************************/
.code16
// .org HEX(0100)
ASSUME CS:.text, DS:.text, ES:.text
/* CODE *******************************/
EntryPoint:
jmp Main
.align 2
ResidentMain:
/*
* Relocate our stack.
* Our local stack is big enough for holding the command line and the path
* to the executable to start, plus a full DOS_REGISTER_STATE and for one pusha 16-bit.
*
* FIXME: enlarge it for pushing the needed Load&Exec data.
*/
cli
mov ax, ds
mov ss, ax
mov bp, offset BaseStack
lea sp, [bp + (1 + DOS_CMDLINE_LENGTH) + MAX_PATH + 255]
sti
/* Resize ourselves */
mov bx, sp // Get size in bytes...
// sub bx, offset PSP_VAR(PSP)
add bx, HEX(0F) // (for rounding to the next paragraph)
shr bx, 4 // ... then the number of paragraphs
mov ah, HEX(4A)
int HEX(21)
/* Check whether we need to start the 32-bit command interpreter */
BOP BOP_CMD, HEX(10) // Check whether we were started from a new console (SessionId != 0)
test al, al // and we are not reentering (32-bit process starting a 16-bit process).
jz Run
cmp word ptr OldParentPsp, SYSTEM_PSP // Check whether our parent is SYSTEM
je Run
#ifndef NDEBUG
/********************************/
mov dx, offset Msg1
mov ah, HEX(09)
int HEX(21)
/********************************/
#endif
BOP BOP_CMD, HEX(0A) // Start 32-bit COMSPEC
jnc Quit
/* Loop for new commands to run */
Run:
/* Initialize the NextCmd structure */
mov word ptr FIELD(NextCmd, EnvBlockSeg), ds
mov word ptr FIELD(NextCmd, EnvBlockLen), 0 // FIXME
mov word ptr FIELD(NextCmd, CmdLineSeg), ds
mov word ptr FIELD(NextCmd, CmdLineOff), offset CmdLine
mov word ptr FIELD(NextCmd, AppNameSeg), ds
mov word ptr FIELD(NextCmd, AppNameOff), offset PgmName
/* Wait for the next command */
#ifndef NDEBUG
/********************************/
mov dx, offset Msg2
mov ah, HEX(09)
int HEX(21)
/********************************/
#endif
// FIXME: Initialize memory with structure for holding CmdLine etc...
// mov ds, seg NextCmd
mov dx, offset NextCmd
BOP BOP_CMD, HEX(01)
/* Quit if we shell-out */
jc Quit
/* Initialize the DosLoadExec structure */
// mov word ptr FIELD(DosLoadExec, EnvSeg), 0
mov word ptr FIELD(DosLoadExec, CmdLineSeg), ds
mov word ptr FIELD(DosLoadExec, Fcb1Seg), ds
mov word ptr FIELD(DosLoadExec, Fcb2Seg), ds
/* Run the command */
mov ds, word ptr FIELD(NextCmd, AppNameSeg)
mov dx, word ptr FIELD(NextCmd, AppNameOff)
// mov es, seg DosLoadExec
mov bx, offset DosLoadExec
pusha // Save the registers in case stuff go wrong
// FIXME: Save also SS !!
mov ax, HEX(4B00)
int HEX(21)
popa // Restore the registers
// FIXME: Restore also SS !!
/* Retrieve and set its exit code. Also detect whether
* we need to continue or whether we need to quit. */
// xor ax, ax
// mov ah, HEX(4D)
mov ax, HEX(4D00)
int HEX(21)
/* Send exit code back to NTVDM */
mov dx, ax
BOP BOP_CMD, HEX(0B)
/* If we don't shell-out, go and get a new app! */
jc Run
mov al, HEX(00) // ERROR_SUCCESS
Quit:
mov bl, al // Save AL in BL
#ifndef NDEBUG
/********************************/
cmp al, HEX(0A)
jne XXXX
mov dx, offset Msg3
mov ah, HEX(09)
int HEX(21)
XXXX:
/********************************/
#endif
#ifndef NDEBUG
/* Say bye-bye */
// mov ds, seg QuitMsg
mov dx, offset QuitMsg
mov ah, HEX(09)
int HEX(21)
#endif
/* Restore our old parent PSP */
mov ax, word ptr OldParentPsp
mov PSP_VAR(ParentPsp), ax
mov al, bl // Restore AL from BL
Exit:
/* Return to caller (with possible error code in AL) */
mov ah, HEX(4C)
int HEX(21)
int 3
/* Does not return */
/* DATA *******************************/
#ifndef NDEBUG
QuitMsg:
.ascii "Bye bye!", CR, LF, "$"
/********************************/
Msg1: .ascii "Starting COMSPEC...", CR, LF, "$"
Msg2: .ascii "Waiting for new command...", CR, LF, "$"
Msg3: .ascii "Bad environment!", CR, LF, "$"
/********************************/
#endif
OldParentPsp: .word 0
CurrentPsp: .word 0
// BOP_CMD, HEX(01) "Get a new app to start" structure
VAR_STRUCT(NextCmd, NEXT_CMD)
// DOS INT 21h, AH=4Bh "Load and Execute" structure
VAR_STRUCT(DosLoadExec, DOS_EXEC_PARAM_BLOCK)
// Blank FCB blocks needed for DOS INT 21h, AH=4Bh
Fcb1:
.byte 0
.space 11, ' '
.space 25, 0
Fcb2:
.byte 0
.space 11, ' '
.space 25, 0
// The stack resides at the end of the resident code+data
// and it overwrites the transient part.
BaseStack:
/* TRANSIENT CODE AND DATA ****************************************************/
/* DATA *******************************/
#ifndef NDEBUG
WelcomeMsg:
.ascii "ReactOS DOS32 Command", CR, LF, \
"Copyright (C) ReactOS Team 2015" , CR, LF, "$"
#endif
VerErrMsg:
.ascii "Incorrect DOS version", CR, LF, "$"
/* CODE *******************************/
.align 2
Main:
/* Setup segment registers */
mov ax, cs // cs contains the PSP segment on entry
mov ds, ax
mov es, ax
// mov fs, ax
// mov gs, ax
/* Stack is set to cs:FFFE down to cs:09xx by the DOS.
* We will need to relocate it before we resize ourselves. */
/*
* Verify DOS version:
* - Check whether we are on DOS 5+ (subject to SETVER);
* - If so, check our real DOS version and see
* whether we are running on NTVDM (version 5.50).
*/
mov ax, HEX(3000)
int HEX(21)
cmp ax, DOS_VERSION // AH:AL contains minor:major version number
jne VerErr
mov ax, HEX(3306)
int HEX(21)
cmp bx, NTDOS_VERSION // BH:BL contains minor:major version number
je Continue
VerErr:
/* Display wrong version error message and exit */
// mov ds, seg VerErrMsg
mov dx, offset VerErrMsg
mov ah, HEX(09)
int HEX(21)
jmp Exit
Continue:
/* Save our PSP */
mov word ptr CurrentPsp, cs
/*
* The DOS way:
*
* mov ah, HEX(51) // DOS 2+ internal, or HEX(62) since DOS 3+
* int HEX(21)
* mov word ptr CurrentPsp, bx
*/
/* Save our old parent PSP */
mov ax, PSP_VAR(ParentPsp)
mov word ptr OldParentPsp, ax
/* Give us shell privileges: set our PSP as our new parent */
mov ax, word ptr CurrentPsp
mov PSP_VAR(ParentPsp), ax
#ifndef NDEBUG
/* Say hello */
// mov ds, seg WelcomeMsg
mov dx, offset WelcomeMsg
mov ah, HEX(09)
int HEX(21)
#endif
/* Jump to resident code */
jmp ResidentMain
.endcode16
END
/* EOF */
| {
"pile_set_name": "Github"
} |
name: sqfentity_example
description: SqfEntity ORM for Flutter/Dart lets you build and execute SQL commands easily and quickly with the help of fluent methods similar to .Net Entity Framework.
author: Hüseyin TOKPINAR <[email protected]>
homepage: https://github.com/hhtokpinar/sqfEntity
version: 1.3.0
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
intl: ^0.15.7
http: ^0.12.0+1
flutter_datetime_picker:
git:
url: https://github.com/derohimat/flutter_datetime_picker.git
sqfentity:
sqfentity_gen:
dependency_overrides:
sqfentity:
path: ../sqfentity
sqfentity_gen:
path: ../sqfentity_gen
dev_dependencies:
build_runner: ^1.6.5
build_verify: ^1.1.0
sqflite_common_ffi:
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/chinook.sqlite
- line.png
- windows-wallpaper.jpg
- no-picture.png
fonts:
- family: LexendDeca
fonts:
- asset: fonts/LexendDeca-Regular.ttf
style: normal
- family: Raleway
fonts:
- asset: fonts/Raleway-Regular.ttf
- asset: fonts/Raleway-Thin.ttf
style: normal
| {
"pile_set_name": "Github"
} |
%% Creator: Matplotlib, PGF backend
%%
%% To include the figure in your LaTeX document, write
%% \input{<filename>.pgf}
%%
%% Make sure the required packages are loaded in your preamble
%% \usepackage{pgf}
%%
%% Figures using additional raster images can only be included by \input if
%% they are in the same directory as the main LaTeX file. For loading figures
%% from other directories you can use the `import` package
%% \usepackage{import}
%% and then include the figures with
%% \import{<path to file>}{<filename>.pgf}
%%
%% Matplotlib used the following preamble
%% \usepackage{fontspec}
%% \setmainfont{DejaVu Serif}
%% \setsansfont{DejaVu Sans}
%% \setmonofont{DejaVu Sans Mono}
%%
\begingroup%
\makeatletter%
\begin{pgfpicture}%
\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{4.296389in}{2.655314in}}%
\pgfusepath{use as bounding box, clip}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetmiterjoin%
\definecolor{currentfill}{rgb}{1.000000,1.000000,1.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.000000pt}%
\definecolor{currentstroke}{rgb}{1.000000,1.000000,1.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{4.296389in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{4.296389in}{2.655314in}}%
\pgfpathlineto{\pgfqpoint{0.000000in}{2.655314in}}%
\pgfpathclose%
\pgfusepath{fill}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetmiterjoin%
\definecolor{currentfill}{rgb}{1.000000,1.000000,1.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.000000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetstrokeopacity{0.000000}%
\pgfsetdash{}{0pt}%
\pgfpathmoveto{\pgfqpoint{0.629028in}{0.442778in}}%
\pgfpathlineto{\pgfqpoint{4.261389in}{0.442778in}}%
\pgfpathlineto{\pgfqpoint{4.261389in}{2.431981in}}%
\pgfpathlineto{\pgfqpoint{0.629028in}{2.431981in}}%
\pgfpathclose%
\pgfusepath{fill}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetroundjoin%
\definecolor{currentfill}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfsys@defobject{currentmarker}{\pgfqpoint{0.000000in}{-0.048611in}}{\pgfqpoint{0.000000in}{0.000000in}}{%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{0.000000in}{-0.048611in}}%
\pgfusepath{stroke,fill}%
}%
\begin{pgfscope}%
\pgfsys@transformshift{0.868550in}{0.442778in}%
\pgfsys@useobject{currentmarker}{}%
\end{pgfscope}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=0.868550in,y=0.345556in,,top]{\sffamily\fontsize{10.000000}{12.000000}\selectfont −3}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetroundjoin%
\definecolor{currentfill}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfsys@defobject{currentmarker}{\pgfqpoint{0.000000in}{-0.048611in}}{\pgfqpoint{0.000000in}{0.000000in}}{%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{0.000000in}{-0.048611in}}%
\pgfusepath{stroke,fill}%
}%
\begin{pgfscope}%
\pgfsys@transformshift{1.394102in}{0.442778in}%
\pgfsys@useobject{currentmarker}{}%
\end{pgfscope}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=1.394102in,y=0.345556in,,top]{\sffamily\fontsize{10.000000}{12.000000}\selectfont −2}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetroundjoin%
\definecolor{currentfill}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfsys@defobject{currentmarker}{\pgfqpoint{0.000000in}{-0.048611in}}{\pgfqpoint{0.000000in}{0.000000in}}{%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{0.000000in}{-0.048611in}}%
\pgfusepath{stroke,fill}%
}%
\begin{pgfscope}%
\pgfsys@transformshift{1.919655in}{0.442778in}%
\pgfsys@useobject{currentmarker}{}%
\end{pgfscope}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=1.919655in,y=0.345556in,,top]{\sffamily\fontsize{10.000000}{12.000000}\selectfont −1}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetroundjoin%
\definecolor{currentfill}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfsys@defobject{currentmarker}{\pgfqpoint{0.000000in}{-0.048611in}}{\pgfqpoint{0.000000in}{0.000000in}}{%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{0.000000in}{-0.048611in}}%
\pgfusepath{stroke,fill}%
}%
\begin{pgfscope}%
\pgfsys@transformshift{2.445208in}{0.442778in}%
\pgfsys@useobject{currentmarker}{}%
\end{pgfscope}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=2.445208in,y=0.345556in,,top]{\sffamily\fontsize{10.000000}{12.000000}\selectfont 0}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetroundjoin%
\definecolor{currentfill}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfsys@defobject{currentmarker}{\pgfqpoint{0.000000in}{-0.048611in}}{\pgfqpoint{0.000000in}{0.000000in}}{%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{0.000000in}{-0.048611in}}%
\pgfusepath{stroke,fill}%
}%
\begin{pgfscope}%
\pgfsys@transformshift{2.970761in}{0.442778in}%
\pgfsys@useobject{currentmarker}{}%
\end{pgfscope}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=2.970761in,y=0.345556in,,top]{\sffamily\fontsize{10.000000}{12.000000}\selectfont 1}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetroundjoin%
\definecolor{currentfill}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfsys@defobject{currentmarker}{\pgfqpoint{0.000000in}{-0.048611in}}{\pgfqpoint{0.000000in}{0.000000in}}{%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{0.000000in}{-0.048611in}}%
\pgfusepath{stroke,fill}%
}%
\begin{pgfscope}%
\pgfsys@transformshift{3.496314in}{0.442778in}%
\pgfsys@useobject{currentmarker}{}%
\end{pgfscope}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=3.496314in,y=0.345556in,,top]{\sffamily\fontsize{10.000000}{12.000000}\selectfont 2}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetroundjoin%
\definecolor{currentfill}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfsys@defobject{currentmarker}{\pgfqpoint{0.000000in}{-0.048611in}}{\pgfqpoint{0.000000in}{0.000000in}}{%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{0.000000in}{-0.048611in}}%
\pgfusepath{stroke,fill}%
}%
\begin{pgfscope}%
\pgfsys@transformshift{4.021867in}{0.442778in}%
\pgfsys@useobject{currentmarker}{}%
\end{pgfscope}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=4.021867in,y=0.345556in,,top]{\sffamily\fontsize{10.000000}{12.000000}\selectfont 3}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=2.445208in,y=0.155587in,,top]{\sffamily\fontsize{10.000000}{12.000000}\selectfont \(\displaystyle \theta\)}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetroundjoin%
\definecolor{currentfill}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfsys@defobject{currentmarker}{\pgfqpoint{-0.048611in}{0.000000in}}{\pgfqpoint{0.000000in}{0.000000in}}{%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{-0.048611in}{0.000000in}}%
\pgfusepath{stroke,fill}%
}%
\begin{pgfscope}%
\pgfsys@transformshift{0.629028in}{0.533196in}%
\pgfsys@useobject{currentmarker}{}%
\end{pgfscope}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=0.194552in,y=0.480435in,left,base]{\sffamily\fontsize{10.000000}{12.000000}\selectfont −1.0}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetroundjoin%
\definecolor{currentfill}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfsys@defobject{currentmarker}{\pgfqpoint{-0.048611in}{0.000000in}}{\pgfqpoint{0.000000in}{0.000000in}}{%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{-0.048611in}{0.000000in}}%
\pgfusepath{stroke,fill}%
}%
\begin{pgfscope}%
\pgfsys@transformshift{0.629028in}{0.985753in}%
\pgfsys@useobject{currentmarker}{}%
\end{pgfscope}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=0.194552in,y=0.932991in,left,base]{\sffamily\fontsize{10.000000}{12.000000}\selectfont −0.5}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetroundjoin%
\definecolor{currentfill}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfsys@defobject{currentmarker}{\pgfqpoint{-0.048611in}{0.000000in}}{\pgfqpoint{0.000000in}{0.000000in}}{%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{-0.048611in}{0.000000in}}%
\pgfusepath{stroke,fill}%
}%
\begin{pgfscope}%
\pgfsys@transformshift{0.629028in}{1.438309in}%
\pgfsys@useobject{currentmarker}{}%
\end{pgfscope}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=0.310926in,y=1.385548in,left,base]{\sffamily\fontsize{10.000000}{12.000000}\selectfont 0.0}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetroundjoin%
\definecolor{currentfill}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfsys@defobject{currentmarker}{\pgfqpoint{-0.048611in}{0.000000in}}{\pgfqpoint{0.000000in}{0.000000in}}{%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{-0.048611in}{0.000000in}}%
\pgfusepath{stroke,fill}%
}%
\begin{pgfscope}%
\pgfsys@transformshift{0.629028in}{1.890866in}%
\pgfsys@useobject{currentmarker}{}%
\end{pgfscope}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=0.310926in,y=1.838104in,left,base]{\sffamily\fontsize{10.000000}{12.000000}\selectfont 0.5}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetbuttcap%
\pgfsetroundjoin%
\definecolor{currentfill}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetfillcolor{currentfill}%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfsys@defobject{currentmarker}{\pgfqpoint{-0.048611in}{0.000000in}}{\pgfqpoint{0.000000in}{0.000000in}}{%
\pgfpathmoveto{\pgfqpoint{0.000000in}{0.000000in}}%
\pgfpathlineto{\pgfqpoint{-0.048611in}{0.000000in}}%
\pgfusepath{stroke,fill}%
}%
\begin{pgfscope}%
\pgfsys@transformshift{0.629028in}{2.343422in}%
\pgfsys@useobject{currentmarker}{}%
\end{pgfscope}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=0.310926in,y=2.290661in,left,base]{\sffamily\fontsize{10.000000}{12.000000}\selectfont 1.0}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=0.138997in,y=1.437379in,,bottom,rotate=90.000000]{\sffamily\fontsize{10.000000}{12.000000}\selectfont Value}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfpathrectangle{\pgfqpoint{0.629028in}{0.442778in}}{\pgfqpoint{3.632361in}{1.989203in}} %
\pgfusepath{clip}%
\pgfsetrectcap%
\pgfsetroundjoin%
\pgfsetlinewidth{1.505625pt}%
\definecolor{currentstroke}{rgb}{1.000000,0.498039,0.054902}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfpathmoveto{\pgfqpoint{0.794135in}{0.533196in}}%
\pgfpathlineto{\pgfqpoint{0.861526in}{0.540627in}}%
\pgfpathlineto{\pgfqpoint{0.928917in}{0.562798in}}%
\pgfpathlineto{\pgfqpoint{0.996307in}{0.599345in}}%
\pgfpathlineto{\pgfqpoint{1.063698in}{0.649667in}}%
\pgfpathlineto{\pgfqpoint{1.131089in}{0.712939in}}%
\pgfpathlineto{\pgfqpoint{1.198480in}{0.788122in}}%
\pgfpathlineto{\pgfqpoint{1.265870in}{0.873980in}}%
\pgfpathlineto{\pgfqpoint{1.333261in}{0.969105in}}%
\pgfpathlineto{\pgfqpoint{1.400652in}{1.071934in}}%
\pgfpathlineto{\pgfqpoint{1.468042in}{1.180779in}}%
\pgfpathlineto{\pgfqpoint{1.535433in}{1.293853in}}%
\pgfpathlineto{\pgfqpoint{1.602824in}{1.409299in}}%
\pgfpathlineto{\pgfqpoint{1.670215in}{1.525221in}}%
\pgfpathlineto{\pgfqpoint{1.737605in}{1.639716in}}%
\pgfpathlineto{\pgfqpoint{1.804996in}{1.750904in}}%
\pgfpathlineto{\pgfqpoint{1.872387in}{1.856959in}}%
\pgfpathlineto{\pgfqpoint{1.939778in}{1.956139in}}%
\pgfpathlineto{\pgfqpoint{2.007168in}{2.046817in}}%
\pgfpathlineto{\pgfqpoint{2.074559in}{2.127504in}}%
\pgfpathlineto{\pgfqpoint{2.141950in}{2.196874in}}%
\pgfpathlineto{\pgfqpoint{2.209341in}{2.253788in}}%
\pgfpathlineto{\pgfqpoint{2.276731in}{2.297312in}}%
\pgfpathlineto{\pgfqpoint{2.344122in}{2.326731in}}%
\pgfpathlineto{\pgfqpoint{2.411513in}{2.341562in}}%
\pgfpathlineto{\pgfqpoint{2.478904in}{2.341562in}}%
\pgfpathlineto{\pgfqpoint{2.546294in}{2.326731in}}%
\pgfpathlineto{\pgfqpoint{2.613685in}{2.297312in}}%
\pgfpathlineto{\pgfqpoint{2.681076in}{2.253788in}}%
\pgfpathlineto{\pgfqpoint{2.748466in}{2.196874in}}%
\pgfpathlineto{\pgfqpoint{2.815857in}{2.127504in}}%
\pgfpathlineto{\pgfqpoint{2.883248in}{2.046817in}}%
\pgfpathlineto{\pgfqpoint{2.950639in}{1.956139in}}%
\pgfpathlineto{\pgfqpoint{3.018029in}{1.856959in}}%
\pgfpathlineto{\pgfqpoint{3.085420in}{1.750904in}}%
\pgfpathlineto{\pgfqpoint{3.152811in}{1.639716in}}%
\pgfpathlineto{\pgfqpoint{3.220202in}{1.525221in}}%
\pgfpathlineto{\pgfqpoint{3.287592in}{1.409299in}}%
\pgfpathlineto{\pgfqpoint{3.354983in}{1.293853in}}%
\pgfpathlineto{\pgfqpoint{3.422374in}{1.180779in}}%
\pgfpathlineto{\pgfqpoint{3.489765in}{1.071934in}}%
\pgfpathlineto{\pgfqpoint{3.557155in}{0.969105in}}%
\pgfpathlineto{\pgfqpoint{3.624546in}{0.873980in}}%
\pgfpathlineto{\pgfqpoint{3.691937in}{0.788122in}}%
\pgfpathlineto{\pgfqpoint{3.759328in}{0.712939in}}%
\pgfpathlineto{\pgfqpoint{3.826718in}{0.649667in}}%
\pgfpathlineto{\pgfqpoint{3.894109in}{0.599345in}}%
\pgfpathlineto{\pgfqpoint{3.961500in}{0.562798in}}%
\pgfpathlineto{\pgfqpoint{4.028890in}{0.540627in}}%
\pgfpathlineto{\pgfqpoint{4.096281in}{0.533196in}}%
\pgfusepath{stroke}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetrectcap%
\pgfsetmiterjoin%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfpathmoveto{\pgfqpoint{0.629028in}{0.442778in}}%
\pgfpathlineto{\pgfqpoint{0.629028in}{2.431981in}}%
\pgfusepath{stroke}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetrectcap%
\pgfsetmiterjoin%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfpathmoveto{\pgfqpoint{4.261389in}{0.442778in}}%
\pgfpathlineto{\pgfqpoint{4.261389in}{2.431981in}}%
\pgfusepath{stroke}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetrectcap%
\pgfsetmiterjoin%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfpathmoveto{\pgfqpoint{0.629028in}{0.442778in}}%
\pgfpathlineto{\pgfqpoint{4.261389in}{0.442778in}}%
\pgfusepath{stroke}%
\end{pgfscope}%
\begin{pgfscope}%
\pgfsetrectcap%
\pgfsetmiterjoin%
\pgfsetlinewidth{0.803000pt}%
\definecolor{currentstroke}{rgb}{0.000000,0.000000,0.000000}%
\pgfsetstrokecolor{currentstroke}%
\pgfsetdash{}{0pt}%
\pgfpathmoveto{\pgfqpoint{0.629028in}{2.431981in}}%
\pgfpathlineto{\pgfqpoint{4.261389in}{2.431981in}}%
\pgfusepath{stroke}%
\end{pgfscope}%
\begin{pgfscope}%
\pgftext[x=2.445208in,y=2.515314in,,base]{\sffamily\fontsize{12.000000}{14.400000}\selectfont Cosine}%
\end{pgfscope}%
\end{pgfpicture}%
\makeatother%
\endgroup%
| {
"pile_set_name": "Github"
} |
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
factory(require('jquery'));
} else {
factory(jQuery);
}
}(function (jQuery) {
// Russian
function numpf(n, f, s, t) {
// f - 1, 21, 31, ...
// s - 2-4, 22-24, 32-34 ...
// t - 5-20, 25-30, ...
n = n % 100;
var n10 = n % 10;
if ( (n10 === 1) && ( (n === 1) || (n > 20) ) ) {
return f;
} else if ( (n10 > 1) && (n10 < 5) && ( (n > 20) || (n < 10) ) ) {
return s;
} else {
return t;
}
}
jQuery.timeago.settings.strings = {
prefixAgo: null,
prefixFromNow: "через",
suffixAgo: "назад",
suffixFromNow: null,
seconds: "меньше минуты",
minute: "минуту",
minutes: function(value) { return numpf(value, "%d минуту", "%d минуты", "%d минут"); },
hour: "час",
hours: function(value) { return numpf(value, "%d час", "%d часа", "%d часов"); },
day: "день",
days: function(value) { return numpf(value, "%d день", "%d дня", "%d дней"); },
month: "месяц",
months: function(value) { return numpf(value, "%d месяц", "%d месяца", "%d месяцев"); },
year: "год",
years: function(value) { return numpf(value, "%d год", "%d года", "%d лет"); }
};
}));
| {
"pile_set_name": "Github"
} |
/* rsa-encrypt.c
The RSA publickey algorithm. PKCS#1 encryption.
Copyright (C) 2001 Niels Möller
This file is part of GNU Nettle.
GNU Nettle is free software: you can redistribute it and/or
modify it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* 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.
or both in parallel, as here.
GNU Nettle 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 copies of the GNU General Public License and
the GNU Lesser General Public License along with this program. If
not, see http://www.gnu.org/licenses/.
*/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "rsa.h"
#include "rsa-internal.h"
#include "pkcs1.h"
int
rsa_encrypt(const struct rsa_public_key *key,
/* For padding */
void *random_ctx, nettle_random_func *random,
size_t length, const uint8_t *message,
mpz_t gibberish)
{
if (pkcs1_encrypt (key->size, random_ctx, random,
length, message, gibberish))
{
mpz_powm(gibberish, gibberish, key->e, key->n);
return 1;
}
else
return 0;
}
| {
"pile_set_name": "Github"
} |
/* Generated from:
* ap-northeast-1 (https://d33vqc0rt9ld30.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* ap-northeast-2 (https://d1ane3fvebulky.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* ap-northeast-3 (https://d2zq80gdmjim8k.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* ap-south-1 (https://d2senuesg1djtx.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* ap-southeast-1 (https://doigdx0kgq9el.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* ap-southeast-2 (https://d2stg8d246z9di.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* ca-central-1 (https://d2s8ygphhesbe7.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* eu-central-1 (https://d1mta8qj7i28i2.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* eu-west-1 (https://d3teyb21fexa9r.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* eu-west-2 (https://d1742qcu2c1ncx.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* eu-west-3 (https://d2d0mfegowb3wk.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* sa-east-1 (https://d3c9jyj3w509b0.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* us-east-1 (https://d1uauaxba7bl26.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* us-east-2 (https://dnwj8swjjbsbt.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* us-west-1 (https://d68hl49wbnanq.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* us-west-2 (https://d201a2mn26r7lk.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0
*/
import {Batch} from './index.namespace'
export default Batch
| {
"pile_set_name": "Github"
} |
Type.registerNamespace("Strings");
Strings.OfficeOM = function()
{
};
Strings.OfficeOM.registerClass("Strings.OfficeOM");
Strings.OfficeOM.L_ShowWindowDialogNotification = "{0} chce zobrazit nové okno.";
Strings.OfficeOM.L_CannotRegisterEvent = "Nedá se zaregistrovat obslužná rutina události.";
Strings.OfficeOM.L_NotImplemented = "Funkce {0} není implementovaná.";
Strings.OfficeOM.L_CustomXmlOutOfDateName = "Neaktuální data";
Strings.OfficeOM.L_ActivityLimitReached = "Byl dosažený limit aktivity.";
Strings.OfficeOM.L_InvalidBinding = "Neplatná vazba";
Strings.OfficeOM.L_BindingCreationError = "Chyba vytváření vazby";
Strings.OfficeOM.L_InvalidSetRows = "Zadané řádky jsou neplatné.";
Strings.OfficeOM.L_CannotWriteToSelection = "Do aktuálního výběru se nedá zapisovat.";
Strings.OfficeOM.L_IndexOutOfRange = "Index je mimo rozsah.";
Strings.OfficeOM.L_ReadSettingsError = "Chyba čtení nastavení";
Strings.OfficeOM.L_InvalidGetColumns = "Zadané sloupce jsou neplatné.";
Strings.OfficeOM.L_OverwriteWorksheetData = "Operace nastavení se nepovedla, protože zadaný datový objekt přepíše nebo posune data.";
Strings.OfficeOM.L_RowIndexOutOfRange = "Hodnota indexu řádku je mimo povolený rozsah. Použijte hodnotu (0 nebo vyšší), která je menší než počet řádků.";
Strings.OfficeOM.L_ColIndexOutOfRange = "Hodnota indexu sloupce je mimo povolený rozsah. Použijte hodnotu (0 nebo vyšší), která je menší než počet sloupců.";
Strings.OfficeOM.L_InvalidParameters = "Funkce {0} má neplatné parametry.";
Strings.OfficeOM.L_DialogAlreadyOpened = "Operace se nepovedla, protože tento doplněk už má aktivní okno.";
Strings.OfficeOM.L_SetDataParametersConflict = "Zadané parametry způsobují konflikt.";
Strings.OfficeOM.L_DataNotMatchCoercionType = "Typ zadaného datového objektu není kompatibilní s aktuálním výběrem.";
Strings.OfficeOM.L_RunMustReturnPromise = "Dávková funkce předaná metodě .run nevrátila příslib. Funkce musí vracet příslib, aby se po dokončení dávkové operace mohly uvolnit automaticky sledované objekty. Obvykle se příslib vrací vrácením odpovědi z context.sync().";
Strings.OfficeOM.L_UnsupportedEnumerationMessage = "Výčet není v aktuální hostitelské aplikaci podporovaný.";
Strings.OfficeOM.L_NewWindowCrossZoneConfigureBrowserLink = "prohlížeč nakonfigurujte";
Strings.OfficeOM.L_InvalidCoercion = "Neplatný typ převodu";
Strings.OfficeOM.L_UnsupportedDataObject = "Zadaný typ datového objektu není podporovaný.";
Strings.OfficeOM.L_AppNameNotExist = "Název doplňku pro: {0} neexistuje.";
Strings.OfficeOM.L_AddBindingFromPromptDefaultText = "Vyberte něco, prosím.";
Strings.OfficeOM.L_DataNotMatchBindingType = "Zadaný datový objekt není kompatibilní s typem vazby.";
Strings.OfficeOM.L_InvalidFormatValue = "Minimálně jeden parametr formátu má hodnoty, které nejsou povolené. Překontrolujte hodnoty a zkuste to znovu.";
Strings.OfficeOM.L_OperationNotSupported = "Operace není podporovaná.";
Strings.OfficeOM.L_InvalidRequestContext = "Objekt nejde použít v různých kontextech požadavků.";
Strings.OfficeOM.L_NamedItemNotFound = "Pojmenovaná položka neexistuje.";
Strings.OfficeOM.L_InvalidGetRows = "Zadané řádky jsou neplatné.";
Strings.OfficeOM.L_CellFormatAmountBeyondLimits = "Poznámka: Přes volání formátovacího API by se nemělo nastavovat víc než 100 formátování.";
Strings.OfficeOM.L_CustomXmlExceedQuotaName = "Dosáhli jste maximální velikosti výběru";
Strings.OfficeOM.L_TooManyIncompleteRequests = "Počkejte, než se dokončí předchozí volání.";
Strings.OfficeOM.L_SetDataIsTooLarge = "Zadaný datový objekt je moc velký.";
Strings.OfficeOM.L_DialogAddressNotTrusted = "Zadaná adresa nebyla pro doplněk důvěryhodná.";
Strings.OfficeOM.L_InvalidBindingOperation = "Neplatná operace vazby";
Strings.OfficeOM.L_APICallFailed = "Volání API selhalo";
Strings.OfficeOM.L_SpecifiedIdNotExist = "Zadané ID neexistuje.";
Strings.OfficeOM.L_SaveSettingsError = "Chyba ukládání nastavení";
Strings.OfficeOM.L_InvalidSetStartRowColumn = "Zadané hodnoty startRow nebo startColumn jsou neplatné.";
Strings.OfficeOM.L_InvalidFormat = "Chyba neplatného formátu";
Strings.OfficeOM.L_InvalidArgument = "Argument {0} nefunguje pro tuto situaci, chybí nebo není ve správném formátu.";
Strings.OfficeOM.L_EventHandlerAdditionFailed = "Nepovedlo se přidat obslužnou rutinu události.";
Strings.OfficeOM.L_InvalidAPICall = "Neplatné volání rozhraní API";
Strings.OfficeOM.L_EventRegistrationError = "Chyba registrace události";
Strings.OfficeOM.L_CustomXmlError = "Chyba vlastního kódu XML";
Strings.OfficeOM.L_TooManyOptionalFunction = "více volitelných funkcí v seznamu parametrů";
Strings.OfficeOM.L_CustomXmlExceedQuotaMessage = "XPath omezuje výběr na 1024 položek.";
Strings.OfficeOM.L_InvalidSelectionForBindingType = "Nejde vytvořit vazbu s aktuálním výběrem a zadaným typem vazby.";
Strings.OfficeOM.L_OperationNotSupportedOnMatrixData = "Vybraný obsah musí být ve formátu tabulky. Zformátujte data jako tabulku a zkuste to znovu.";
Strings.OfficeOM.L_ShowWindowDialogNotificationIgnore = "Ignorovat";
Strings.OfficeOM.L_SliceSizeNotSupported = "Zadaná velikost řezu není podporovaná.";
Strings.OfficeOM.L_EventHandlerRemovalFailed = "Nepovedlo se odebrat obslužnou rutinu události.";
Strings.OfficeOM.L_DataReadError = "Chyba čtení dat";
Strings.OfficeOM.L_InvalidDataFormat = "Formát zadaného datového objektu je neplatný.";
Strings.OfficeOM.L_RequestTimeout = "Zpracování volání trvalo moc dlouho.";
Strings.OfficeOM.L_GetSelectionNotSupported = "Aktuální výběr není podporovaný.";
Strings.OfficeOM.L_InvalidTableOptionValue = "Minimálně jeden parametr tableOptions má hodnoty, které nejsou povolené. Překontrolujte hodnoty a zkuste to znovu.";
Strings.OfficeOM.L_PermissionDenied = "Oprávnění odepřena";
Strings.OfficeOM.L_InvalidDataObject = "Neplatný datový objekt";
Strings.OfficeOM.L_InvalidColumnsForBinding = "Zadané sloupce jsou neplatné.";
Strings.OfficeOM.L_InvalidGetRowColumnCounts = "Zadané hodnoty rowCount nebo columnCount jsou neplatné.";
Strings.OfficeOM.L_OsfControlTypeNotSupported = "Typ OsfControl není podporovaný.";
Strings.OfficeOM.L_DialogNavigateError = "Chyba navigace v dialogovém okně";
Strings.OfficeOM.L_InvalidObjectPath = "Cesta k objektu {0} není pro požadovanou akci funkční. Pokud používáte objekt ve více voláních context.sync a mimo sekvenční provádění dávky .run, použijte prosím metody context.trackedObjects.add() a context.trackedObjects.remove() pro správu životnosti objektu.";
Strings.OfficeOM.L_InternalError = "Vnitřní chyba";
Strings.OfficeOM.L_CoercionTypeNotMatchBinding = "Zadaný typ převodu není kompatibilní s tímto typem vazby.";
Strings.OfficeOM.L_InValidOptionalArgument = "neplatný volitelný argument";
Strings.OfficeOM.L_InvalidNamedItemForBindingType = "Zadaný typ vazby není kompatibilní se zadanou pojmenovanou položkou.";
Strings.OfficeOM.L_InvalidNode = "Neplatný uzel";
Strings.OfficeOM.L_UnknownBindingType = "Tento typ vazby není podporovaný.";
Strings.OfficeOM.L_EventHandlerNotExist = "Zadaná obslužná rutina událostí se pro tuto vazbu nenašla.";
Strings.OfficeOM.L_NoCapability = "K provedení této akce nemáte dostatečná oprávnění.";
Strings.OfficeOM.L_SettingsCannotSave = "Nastavení nejde uložit.";
Strings.OfficeOM.L_DataWriteReminder = "Připomenutí zápisu dat";
Strings.OfficeOM.L_InvalidSetColumns = "Zadané sloupce jsou neplatné.";
Strings.OfficeOM.L_InvalidBindingError = "Chyba neplatné vazby";
Strings.OfficeOM.L_SelectionNotSupportCoercionType = "Aktuální výběr není kompatibilní se zadaným typem převodu.";
Strings.OfficeOM.L_FormatValueOutOfRange = "Hodnota je mimo povolený rozsah.";
Strings.OfficeOM.L_InvalidGetStartRowColumn = "Zadané hodnoty startRow nebo startColumn jsou neplatné.";
Strings.OfficeOM.L_NetworkProblem = "Problém se sítí";
Strings.OfficeOM.ConnectionFailureWithDetails = "Žádost selhala se stavovým kódem {0}, kódem chyby {1} a následující chybovou zprávou: {2}";
Strings.OfficeOM.L_MissingParameter = "Chybějící parametr";
Strings.OfficeOM.L_NewWindowCrossZone = "Nastavení zabezpečení ve vašem prohlížeči nám brání ve vytvoření dialogového okna. Zkuste jiný prohlížeč nebo si {0}, aby {1} a doména zobrazená ve vašem panelu Adresa byly ve stejné zóně zabezpečení.";
Strings.OfficeOM.L_SettingsStaleError = "Chyba zastaralých nastavení";
Strings.OfficeOM.L_CannotNavigateTo = "Objekt je v umístění, kde se nepodporuje navigace.";
Strings.OfficeOM.L_AppNotExistInitializeNotCalled = "Aplikace {0} neexistuje. Nevolá se rutina Microsoft.Office.WebExtension.initialize(reason).";
Strings.OfficeOM.L_CoercionTypeNotSupported = "Zadaný typ převodu není podporovaný.";
Strings.OfficeOM.L_InvalidReadForBlankRow = "Zadaný řádek je prázdný.";
Strings.OfficeOM.L_UnsupportedEnumeration = "Nepodporovaný výčet";
Strings.OfficeOM.L_CloseFileBeforeRetrieve = "Před načtením dalšího souboru volejte closeAsync pro aktuální soubor.";
Strings.OfficeOM.L_CustomXmlOutOfDateMessage = "Data jsou zastaralá. Načtěte objekt znovu.";
Strings.OfficeOM.L_NotSupportedEventType = "Zadaný typ události {0} není podporovaný.";
Strings.OfficeOM.L_GetDataIsTooLarge = "Požadovaná sada dat je moc velká.";
Strings.OfficeOM.L_MultipleNamedItemFound = "Našlo se více objektů se stejným názvem.";
Strings.OfficeOM.L_InvalidCellsValue = "Minimálně jeden parametr buňky má hodnoty, které nejsou povolené. Překontrolujte hodnoty a zkuste to znovu.";
Strings.OfficeOM.L_InitializeNotReady = "Soubor Office.js ještě není úplně načtený. Zkuste to znovu později nebo přidejte inicializační kód do funkce Office.initialize.";
Strings.OfficeOM.L_NotSupportedBindingType = "Zadaný typ vazby {0} není podporovaný.";
Strings.OfficeOM.L_ShuttingDown = "Operace se nepovedla, protože data na serveru nejsou aktuální.";
Strings.OfficeOM.L_FormattingReminder = "Připomenutí formátování";
Strings.OfficeOM.L_ConnectionFailureWithStatus = "Žádost selhala se stavovým kódem {0}.";
Strings.OfficeOM.L_DocumentReadOnly = "Požadovaná operace není v aktuálním režimu dokumentu povolená.";
Strings.OfficeOM.L_InvalidApiCallInContext = "Neplatné volání rozhraní API v aktuálním kontextu";
Strings.OfficeOM.L_ShowWindowDialogNotificationAllow = "Povolit";
Strings.OfficeOM.L_DataWriteError = "Chyba zápisu dat";
Strings.OfficeOM.L_FunctionCallFailed = "Volání funkce {0} se nepovedlo, kód chyby: {1}.";
Strings.OfficeOM.L_DataNotMatchBindingSize = "Zadaný datový objekt se neshoduje s velikostí aktuálního výběru.";
Strings.OfficeOM.L_RequestTokenUnavailable = "Toto rozhraní API se omezilo, aby se zpomalila četnost volání.";
Strings.OfficeOM.L_NewWindowCrossZoneErrorString = "Nemohli jsme dialogové okno vytvořit kvůli omezení prohlížeče. Doména dialogového okna a doména hostitele doplňku nejsou ve stejné zóně zabezpečení.";
Strings.OfficeOM.L_BindingNotExist = "Zadaná vazba neexistuje.";
Strings.OfficeOM.L_DisplayDialogError = "Chyba zobrazení dialogového okna";
Strings.OfficeOM.L_SettingNameNotExist = "Zadaný název nastavení neexistuje.";
Strings.OfficeOM.L_BrowserAPINotSupported = "Tento prohlížeč nepodporuje požadované rozhraní API.";
Strings.OfficeOM.L_NonUniformPartialSetNotSupported = "Parametry souřadnic nejde použít s převodem typu Tabulka, pokud tabulka obsahuje sloučené buňky.";
Strings.OfficeOM.L_ElementMissing = "Nemohli jsme naformátovat buňku tabulky, protože chybí některé hodnoty parametrů. Ještě jednou zkontrolujte parametry a zkuste to znovu.";
Strings.OfficeOM.L_ValueNotLoaded = "Ještě se nenačetla hodnota výsledného objektu. Před přečtením hodnoty vlastnosti volejte metodu context.sync() pro kontext přidružené žádosti.";
Strings.OfficeOM.L_NavOutOfBound = "Operace se nepovedla, protože index je mimo rozsah.";
Strings.OfficeOM.L_RedundantCallbackSpecification = "Zpětné volání nemůže být zadané v seznamu argumentů i ve volitelném objektu.";
Strings.OfficeOM.L_PropertyNotLoaded = "Vlastnost {0} není k dispozici. Před přečtením hodnoty vlastnosti volejte metodu pro načtení nadřazeného objektu a potom volejte context.sync() pro přidružený kontext požadavku.";
Strings.OfficeOM.L_SettingsAreStale = "Nastavení se nepodařilo uložit, protože nejsou aktuální.";
Strings.OfficeOM.L_MissingRequiredArguments = "chybí některé požadované argumenty";
Strings.OfficeOM.L_NonUniformPartialGetNotSupported = "Parametry souřadnic nejde použít s převodem typu Tabulka, pokud tabulka obsahuje sloučené buňky.";
Strings.OfficeOM.L_OutOfRange = "Mimo rozsah";
Strings.OfficeOM.L_HostError = "Chyba hostitele";
Strings.OfficeOM.L_TooManyOptionalObjects = "více volitelných objektů v seznamu parametrů";
Strings.OfficeOM.L_APINotSupported = "API není podporované";
Strings.OfficeOM.L_UserClickIgnore = "Uživatel se rozhodl ignorovat dialogové okno.";
Strings.OfficeOM.L_BindingToMultipleSelection = "Nesouvislé výběry nejsou podporované.";
Strings.OfficeOM.L_InternalErrorDescription = "Došlo k vnitřní chybě.";
Strings.OfficeOM.L_DataStale = "Neaktuální data";
Strings.OfficeOM.L_MemoryLimit = "Překročený limit paměti";
Strings.OfficeOM.L_CellDataAmountBeyondLimits = "Poznámka: Tabulka by neměla obsahovat víc než 20 000 buněk.";
Strings.OfficeOM.L_SelectionCannotBound = "Nejde vytvořit vazbu na aktuální výběr.";
Strings.OfficeOM.L_UserNotSignedIn = "Žádný uživatel není přihlášený v Office.";
Strings.OfficeOM.L_BadSelectorString = "Řetězec předaný selektoru je nesprávně naformátovaný nebo není podporovaný.";
Strings.OfficeOM.L_InvalidValue = "Neplatná hodnota";
Strings.OfficeOM.L_DataNotMatchSelection = "Zadaný datový objekt není kompatibilní s tvarem nebo rozměry aktuálního výběru.";
Strings.OfficeOM.L_NotSupported = "Funkce {0} není podporovaná.";
Strings.OfficeOM.L_CustomXmlNodeNotFound = "Zadaný uzel nejde najít.";
Strings.OfficeOM.L_NetworkProblemRetrieveFile = "Problémy se sítí zabránily načtení souboru.";
Strings.OfficeOM.L_TooManyArguments = "příliš mnoho argumentů";
Strings.OfficeOM.L_OperationNotSupportedOnThisBindingType = "Operace není u tohoto typu vazby podporovaná.";
Strings.OfficeOM.L_GetDataParametersConflict = "Zadané parametry způsobují konflikt.";
Strings.OfficeOM.L_FileTypeNotSupported = "Zadaný typ souboru není podporovaný.";
Strings.OfficeOM.L_CallbackNotAFunction = "Zpětné volání musí být typu funkce. Bylo typu {0}."
| {
"pile_set_name": "Github"
} |
{
"throws": "Unterminated regular expression (1:1)"
} | {
"pile_set_name": "Github"
} |
<?php
/**
* @package Campsite
*/
/**
* @package Campsite
*/
final class MetaPlaylist {
/**
* Constructor
*
* @param string $p_number
* @param string $p_count
* @param string $p_name
* @param string $p_content
* @param string $p_formattingStart
* @param string $p_formattingEnd
*/
public function __construct($p_playlistId = null)
{
}
public function __get($p_property)
{
switch (strtolower($p_property))
{
default:
$this->trigger_invalid_property_error($p_property);
return null;
}
}
/**
* Process the body field content (except subtitles):
* - internal links
* - image links
*
* @param string $p_content
* @return string
*/
private static function ProcessContent($p_content)
{
$content = trim($p_content);
if (empty($content)) {
return $p_content;
}
}
protected function trigger_invalid_property_error($p_property, $p_smarty = null)
{
$errorMessage = INVALID_PROPERTY_STRING . " $p_property "
. OF_OBJECT_STRING . ' subtitle';
CampTemplate::singleton()->trigger_error($errorMessage, $p_smarty);
}
}
?> | {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use \Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::THEME, 'frontend/Magento_FrameworkThemeTest/default', __DIR__);
| {
"pile_set_name": "Github"
} |
<template>
<div class="preview-box">
<div class="preview-body">
<img :src="preview" alt="" />
<p class="message" v-if="this.message"> {{ this.message }} </p>
</div>
<div class="preview-footer">
<button @click="back" class="red">重新选择</button>
<button @click="speech" class="blue">语音播报</button>
</div>
<audio :src="this.mp3" autoPlay></audio>
</div>
</template>
<script>
import { imgOCR, getRadio } from '../util';
export default {
name: 'preview',
data() {
return {
message: '',
mp3: '',
file: '',
preview: '',
};
},
methods: {
back() {
this.$router.push('/')
},
speech() {
(async () => {
if (this.message) {
const mp3 = await getRadio(this.message)
this.mp3 = mp3
}
})()
},
},
mounted() {
if (this.$route.query.file) {
this.preview = this.$route.query.preview
imgOCR(this.$route.query.file).then((message) => {
this.message = message
this.$electron.clipboard.writeText(message)
const notifition = new Notification('成功', {
body: '文本已经复制,赶紧去粘贴吧',
})
notifition.onclick = () => {}
})
}
},
};
</script>
<style>
.preview-box{
width: 800px;
height: 500px;
margin: auto;
border-radius: 10px;
background: #fff;
}
.preview-body{
height: 440px;
border-radius: 10px;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
position: relative;
display: flex;
background: url('../images/pre-bg.png') 0 0 repeat;
}
.preview-body img {
max-width: 500px;
margin: auto;
max-height: 86%;
}
.message{
background: rgba(0,0,0,.4);
padding: 5px;
position: absolute;
width: 100%;
bottom: 0;
box-sizing: border-box;
color: lightyellow;
}
.preview-footer{
display: flex;
height: 60px;
justify-content: center;
align-items: center;
}
.preview-footer > button {
margin-left: 10px;
}
</style>
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <TVKit/TVCollectionView.h>
@interface _TVInertiaContainingCollectionView : TVCollectionView
{
}
- (_Bool)_containsInertiaSelectionChanges;
@end
| {
"pile_set_name": "Github"
} |
module WebSocket
class WsConnection
attr_accessor :custom_headers
def http_handshake
key = WebSocket.create_key
headers = [
"Host: #{@host}:#{@port}",
"Connection: Upgrade",
"Upgrade: websocket",
"Sec-WebSocket-Version: 13",
"Sec-WebSocket-Key: #{key}"
]
headers += custom_headers if custom_headers
headers_str = headers.join("\r\n")
@socket.write("GET #{@path} HTTP/1.1\r\n#{headers_str}\r\n\r\n")
buf = @socket.recv(16384)
phr = Phr.new
while true
case phr.parse_response(buf)
when Fixnum
break
when :incomplete
buf << @socket.recv(16384)
when :parser_error
raise Error, "HTTP Parser error"
end
end
response_headers = phr.headers.to_h
unless response_headers.key?('sec-websocket-accept')
raise Error, "WebSocket upgrade failed"
end
unless WebSocket.create_accept(key).securecmp(response_headers.fetch('sec-websocket-accept'))
raise Error, "Handshake failure"
end
end
end
end
| {
"pile_set_name": "Github"
} |
<?php
namespace Emtudo\Units\Search\Courses\Providers;
use Emtudo\Units\Search\Courses\Routes\Api;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'Emtudo\Units\Search\Courses\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*/
public function boot()
{
parent::boot();
}
/**
* Define the routes for the application.
*/
public function map()
{
$this->mapApiRoutes();
}
/**
* API Routes.
*/
protected function mapApiRoutes()
{
(new Api([
'middleware' => ['api', 'auth'],
'namespace' => $this->namespace,
'prefix' => 'v1/search/courses',
'as' => 'search_courses::',
]))->register();
}
}
| {
"pile_set_name": "Github"
} |
# string_decoder
***Node-core v8.9.4 string_decoder for userland***
[](https://nodei.co/npm/string_decoder/)
[](https://nodei.co/npm/string_decoder/)
```bash
npm install --save string_decoder
```
***Node-core string_decoder for userland***
This package is a mirror of the string_decoder implementation in Node-core.
Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/).
As of version 1.0.0 **string_decoder** uses semantic versioning.
## Previous versions
Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10.
## Update
The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version.
## Streams Working Group
`string_decoder` is maintained by the Streams Working Group, which
oversees the development and maintenance of the Streams API within
Node.js. The responsibilities of the Streams Working Group include:
* Addressing stream issues on the Node.js issue tracker.
* Authoring and editing stream documentation within the Node.js project.
* Reviewing changes to stream subclasses within the Node.js project.
* Redirecting changes to streams from the Node.js project to this
project.
* Assisting in the implementation of stream providers within Node.js.
* Recommending versions of `readable-stream` to be included in Node.js.
* Messaging about the future of streams to give the community advance
notice of changes.
See [readable-stream](https://github.com/nodejs/readable-stream) for
more details.
| {
"pile_set_name": "Github"
} |
/*
FUSE: Filesystem in Userspace
Copyright (C) 2001-2007 Miklos Szeredi <[email protected]>
This program can be distributed under the terms of the GNU LGPLv2.
See the file COPYING.LIB
*/
#include "fuse_opt.h"
#include "fuse_misc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
struct fuse_opt_context {
void *data;
const struct fuse_opt *opt;
fuse_opt_proc_t proc;
int argctr;
int argc;
char **argv;
struct fuse_args outargs;
char *opts;
int nonopt;
};
void fuse_opt_free_args(struct fuse_args *args)
{
if (args) {
if (args->argv && args->allocated) {
int i;
for (i = 0; i < args->argc; i++)
free(args->argv[i]);
free(args->argv);
}
args->argc = 0;
args->argv = NULL;
args->allocated = 0;
}
}
static int alloc_failed(void)
{
fprintf(stderr, "fuse: memory allocation failed\n");
return -1;
}
int fuse_opt_add_arg(struct fuse_args *args, const char *arg)
{
char **newargv;
char *newarg;
assert(!args->argv || args->allocated);
newargv = realloc(args->argv, (args->argc + 2) * sizeof(char *));
newarg = newargv ? strdup(arg) : NULL;
if (!newargv || !newarg)
return alloc_failed();
args->argv = newargv;
args->allocated = 1;
args->argv[args->argc++] = newarg;
args->argv[args->argc] = NULL;
return 0;
}
static int fuse_opt_insert_arg_common(struct fuse_args *args, int pos,
const char *arg)
{
assert(pos <= args->argc);
if (fuse_opt_add_arg(args, arg) == -1)
return -1;
if (pos != args->argc - 1) {
char *newarg = args->argv[args->argc - 1];
memmove(&args->argv[pos + 1], &args->argv[pos],
sizeof(char *) * (args->argc - pos - 1));
args->argv[pos] = newarg;
}
return 0;
}
int fuse_opt_insert_arg(struct fuse_args *args, int pos, const char *arg)
{
return fuse_opt_insert_arg_common(args, pos, arg);
}
int fuse_opt_insert_arg_compat(struct fuse_args *args, int pos,
const char *arg);
int fuse_opt_insert_arg_compat(struct fuse_args *args, int pos, const char *arg)
{
return fuse_opt_insert_arg_common(args, pos, arg);
}
static int next_arg(struct fuse_opt_context *ctx, const char *opt)
{
if (ctx->argctr + 1 >= ctx->argc) {
fprintf(stderr, "fuse: missing argument after `%s'\n", opt);
return -1;
}
ctx->argctr++;
return 0;
}
static int add_arg(struct fuse_opt_context *ctx, const char *arg)
{
return fuse_opt_add_arg(&ctx->outargs, arg);
}
static int add_opt_common(char **opts, const char *opt, int esc)
{
unsigned oldlen = *opts ? strlen(*opts) : 0;
char *d = realloc(*opts, oldlen + 1 + strlen(opt) * 2 + 1);
if (!d)
return alloc_failed();
*opts = d;
if (oldlen) {
d += oldlen;
*d++ = ',';
}
for (; *opt; opt++) {
if (esc && (*opt == ',' || *opt == '\\'))
*d++ = '\\';
*d++ = *opt;
}
*d = '\0';
return 0;
}
int fuse_opt_add_opt(char **opts, const char *opt)
{
return add_opt_common(opts, opt, 0);
}
int fuse_opt_add_opt_escaped(char **opts, const char *opt)
{
return add_opt_common(opts, opt, 1);
}
static int add_opt(struct fuse_opt_context *ctx, const char *opt)
{
return add_opt_common(&ctx->opts, opt, 1);
}
static int call_proc(struct fuse_opt_context *ctx, const char *arg, int key,
int iso)
{
if (key == FUSE_OPT_KEY_DISCARD)
return 0;
if (key != FUSE_OPT_KEY_KEEP && ctx->proc) {
int res = ctx->proc(ctx->data, arg, key, &ctx->outargs);
if (res == -1 || !res)
return res;
}
if (iso)
return add_opt(ctx, arg);
else
return add_arg(ctx, arg);
}
static int match_template(const char *t, const char *arg, unsigned *sepp)
{
int arglen = strlen(arg);
const char *sep = strchr(t, '=');
sep = sep ? sep : strchr(t, ' ');
if (sep && (!sep[1] || sep[1] == '%')) {
int tlen = sep - t;
if (sep[0] == '=')
tlen ++;
if (arglen >= tlen && strncmp(arg, t, tlen) == 0) {
*sepp = sep - t;
return 1;
}
}
if (strcmp(t, arg) == 0) {
*sepp = 0;
return 1;
}
return 0;
}
static const struct fuse_opt *find_opt(const struct fuse_opt *opt,
const char *arg, unsigned *sepp)
{
for (; opt && opt->templ; opt++)
if (match_template(opt->templ, arg, sepp))
return opt;
return NULL;
}
int fuse_opt_match(const struct fuse_opt *opts, const char *opt)
{
unsigned dummy;
return find_opt(opts, opt, &dummy) ? 1 : 0;
}
static int process_opt_param(void *var, const char *format, const char *param,
const char *arg)
{
assert(format[0] == '%');
if (format[1] == 's') {
char *copy = strdup(param);
if (!copy)
return alloc_failed();
*(char **) var = copy;
} else {
if (sscanf(param, format, var) != 1) {
fprintf(stderr, "fuse: invalid parameter in option `%s'\n", arg);
return -1;
}
}
return 0;
}
static int process_opt(struct fuse_opt_context *ctx,
const struct fuse_opt *opt, unsigned sep,
const char *arg, int iso)
{
if (opt->offset == -1U) {
if (call_proc(ctx, arg, opt->value, iso) == -1)
return -1;
} else {
void *var = ctx->data + opt->offset;
if (sep && opt->templ[sep + 1]) {
const char *param = arg + sep;
if (opt->templ[sep] == '=')
param ++;
if (process_opt_param(var, opt->templ + sep + 1,
param, arg) == -1)
return -1;
} else
*(int *)var = opt->value;
}
return 0;
}
static int process_opt_sep_arg(struct fuse_opt_context *ctx,
const struct fuse_opt *opt, unsigned sep,
const char *arg, int iso)
{
int res;
char *newarg;
char *param;
if (next_arg(ctx, arg) == -1)
return -1;
param = ctx->argv[ctx->argctr];
newarg = malloc(sep + strlen(param) + 1);
if (!newarg)
return alloc_failed();
memcpy(newarg, arg, sep);
strcpy(newarg + sep, param);
res = process_opt(ctx, opt, sep, newarg, iso);
free(newarg);
return res;
}
static int process_gopt(struct fuse_opt_context *ctx, const char *arg, int iso)
{
unsigned sep;
const struct fuse_opt *opt = find_opt(ctx->opt, arg, &sep);
if (opt) {
for (; opt; opt = find_opt(opt + 1, arg, &sep)) {
int res;
if (sep && opt->templ[sep] == ' ' && !arg[sep])
res = process_opt_sep_arg(ctx, opt, sep, arg,
iso);
else
res = process_opt(ctx, opt, sep, arg, iso);
if (res == -1)
return -1;
}
return 0;
} else
return call_proc(ctx, arg, FUSE_OPT_KEY_OPT, iso);
}
static int process_real_option_group(struct fuse_opt_context *ctx, char *opts)
{
char *s = opts;
char *d = s;
int end = 0;
while (!end) {
if (*s == '\0')
end = 1;
if (*s == ',' || end) {
int res;
*d = '\0';
res = process_gopt(ctx, opts, 1);
if (res == -1)
return -1;
d = opts;
} else {
if (s[0] == '\\' && s[1] != '\0')
s++;
*d++ = *s;
}
s++;
}
return 0;
}
static int process_option_group(struct fuse_opt_context *ctx, const char *opts)
{
int res;
char *copy = strdup(opts);
if (!copy) {
fprintf(stderr, "fuse: memory allocation failed\n");
return -1;
}
res = process_real_option_group(ctx, copy);
free(copy);
return res;
}
static int process_one(struct fuse_opt_context *ctx, const char *arg)
{
if (ctx->nonopt || arg[0] != '-')
return call_proc(ctx, arg, FUSE_OPT_KEY_NONOPT, 0);
else if (arg[1] == 'o') {
if (arg[2])
return process_option_group(ctx, arg + 2);
else {
if (next_arg(ctx, arg) == -1)
return -1;
return process_option_group(ctx,
ctx->argv[ctx->argctr]);
}
} else if (arg[1] == '-' && !arg[2]) {
if (add_arg(ctx, arg) == -1)
return -1;
ctx->nonopt = ctx->outargs.argc;
return 0;
} else
return process_gopt(ctx, arg, 0);
}
static int opt_parse(struct fuse_opt_context *ctx)
{
if (ctx->argc) {
if (add_arg(ctx, ctx->argv[0]) == -1)
return -1;
}
for (ctx->argctr = 1; ctx->argctr < ctx->argc; ctx->argctr++)
if (process_one(ctx, ctx->argv[ctx->argctr]) == -1)
return -1;
if (ctx->opts) {
if (fuse_opt_insert_arg(&ctx->outargs, 1, "-o") == -1 ||
fuse_opt_insert_arg(&ctx->outargs, 2, ctx->opts) == -1)
return -1;
}
/* If option separator ("--") is the last argument, remove it */
if (ctx->nonopt && ctx->nonopt == ctx->outargs.argc &&
strcmp(ctx->outargs.argv[ctx->outargs.argc - 1], "--") == 0) {
free(ctx->outargs.argv[ctx->outargs.argc - 1]);
ctx->outargs.argv[--ctx->outargs.argc] = NULL;
}
return 0;
}
int fuse_opt_parse(struct fuse_args *args, void *data,
const struct fuse_opt opts[], fuse_opt_proc_t proc)
{
int res;
struct fuse_opt_context ctx = {
.data = data,
.opt = opts,
.proc = proc,
};
if (!args || !args->argv || !args->argc)
return 0;
ctx.argc = args->argc;
ctx.argv = args->argv;
res = opt_parse(&ctx);
if (res != -1) {
struct fuse_args tmp = *args;
*args = ctx.outargs;
ctx.outargs = tmp;
}
free(ctx.opts);
fuse_opt_free_args(&ctx.outargs);
return res;
}
/* This symbol version was mistakenly added to the version script */
FUSE_SYMVER(".symver fuse_opt_insert_arg_compat,fuse_opt_insert_arg@FUSE_2.5");
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2018 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.tools.idea.uibuilder.api.actions
import com.android.tools.idea.common.model.NlComponent
import com.android.tools.idea.uibuilder.analytics.NlAnalyticsManager
import com.android.tools.idea.uibuilder.api.ViewEditor
import com.android.tools.idea.uibuilder.api.ViewHandler
import com.intellij.ide.util.PropertiesComponent
import icons.StudioIcons
private const val PREFERENCE_KEY_PREFIX = "LayoutEditorPreference"
private const val AUTO_CONNECT_PREF_KEY = PREFERENCE_KEY_PREFIX + "AutoConnect"
private const val DEFAULT_AUTO_CONNECT_VALUE = false
private const val AUTO_CONNECTION_ON_TOOLTIP = "Enable Autoconnection to Parent"
private const val AUTO_CONNECTION_OFF_TOOLTIP = "Disable Autoconnection to Parent"
class ToggleAutoConnectAction : ToggleViewAction(StudioIcons.LayoutEditor.Toolbar.AUTO_CORRECT_OFF,
StudioIcons.LayoutEditor.Toolbar.AUTO_CONNECT,
AUTO_CONNECTION_ON_TOOLTIP,
AUTO_CONNECTION_OFF_TOOLTIP) {
override fun isSelected(editor: ViewEditor, handler: ViewHandler, parent: NlComponent, selectedChildren: List<NlComponent>) =
PropertiesComponent.getInstance().getBoolean(AUTO_CONNECT_PREF_KEY, DEFAULT_AUTO_CONNECT_VALUE)
override fun setSelected(editor: ViewEditor,
handler: ViewHandler,
parent: NlComponent,
selectedChildren: List<NlComponent>,
selected: Boolean) {
val analyticsManager = editor.scene.designSurface?.analyticsManager as? NlAnalyticsManager
if (analyticsManager != null) {
analyticsManager.trackToggleAutoConnect(selected)
}
PropertiesComponent.getInstance().setValue(AUTO_CONNECT_PREF_KEY, selected, DEFAULT_AUTO_CONNECT_VALUE)
}
companion object {
@JvmStatic
fun isAutoconnectOn(): Boolean {
return PropertiesComponent.getInstance().getBoolean(AUTO_CONNECT_PREF_KEY, DEFAULT_AUTO_CONNECT_VALUE)
}
}
}
| {
"pile_set_name": "Github"
} |
// Copyright (C) 2016 by rr-
//
// This file is part of arc_unpacker.
//
// arc_unpacker is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at
// your option) any later version.
//
// arc_unpacker 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 arc_unpacker. If not, see <http://www.gnu.org/licenses/>.
#pragma once
#include "dec/base_archive_decoder.h"
namespace au {
namespace dec {
namespace microsoft {
class ExeArchiveDecoder final : public BaseArchiveDecoder
{
protected:
bool is_recognized_impl(io::File &input_file) const override;
std::unique_ptr<ArchiveMeta> read_meta_impl(
const Logger &logger,
io::File &input_file) const override;
std::unique_ptr<io::File> read_file_impl(
const Logger &logger,
io::File &input_file,
const ArchiveMeta &m,
const ArchiveEntry &e) const override;
};
} } }
| {
"pile_set_name": "Github"
} |
# 在原始高清文件夹下运行,压制 webp 图片
for file in *.jpg; do echo $file ${file%%.*}.webp; convert -resize 1920x1920 $file ../${file%%.*}.webp; done | {
"pile_set_name": "Github"
} |
/*
* HaOptModule.cpp
*
* Created on: Oct 29, 2012
* Modified Code: Kamal Sharma
* Original Code: Jeff Keasler
*/
#include "HaOptModule.hpp"
#include "TALCAttribute.cpp"
/**
* Hardware Optimizer constructor
* @param args Command Line arguments
* @param meta Meta file handler
*/
HaOptModule::HaOptModule(Rose_STL_Container<string> &args, Meta *meta)
: isVisit(false), compiler(CompilerTypes::UNKNOWN)
{
handleModuleOptions(args);
setMeta(meta);
}
/**
* Internal Method to invoke pragma processing
*/
void HaOptModule::processPragma(SgProject *project) {
HAOPTUtil::DoPragma(project, compiler);
}
/**
* Internal Method to process variable declarations
* This parses the TALC attribute to see if the struct
* was created by AOSModule or tries to check if Meta
* exist for a given variable
* @param functionDeclaration
*/
void HaOptModule::processVariableDecls(
SgFunctionDeclaration *functionDeclaration) {
PrintUtil::printFunctionStart("HaOptModule::processVariableDecls");
SgBasicBlock *functionBody =
functionDeclaration->get_definition()->get_body();
ROSE_ASSERT(functionBody);
Rose_STL_Container<SgVariableDeclaration*> varDeclList =
querySubTree<SgVariableDeclaration>(functionBody, V_SgVariableDeclaration);
foreach(SgVariableDeclaration * varDecl, varDeclList)
{
bool isTALCStructDecl = false;
// Check if TALC Attribute exist
AstAttribute *astattribute = varDecl->getAttribute("TALCAttribute");
TALCAttribute *talcAttribute =
dynamic_cast<TALCAttribute*>(astattribute);
if (talcAttribute != NULL) {
trace << " TALC Attribute is not NULL " << endl;
isTALCStructDecl = talcAttribute->isStructDecl();
}
SgInitializedNamePtrList ¶meterList = varDecl->get_variables();
foreach(SgInitializedName * initializedName, parameterList)
{
trace << " Init Name : " << initializedName->get_name().str()
<< endl;
if (isTALCStructDecl) {
HAOPTUtil::DoStructDecl(initializedName, applyRestrict);
continue;
}
// Check if Meta Field exists
Field *metaField = meta->getField(
initializedName->get_name().str());
if (metaField == NULL)
continue;
trace << " Meta Field found " << endl;
HAOPTUtil::DoPointer(initializedName, varDecl, compiler,
applyRestrict)
|| HAOPTUtil::DoArray(initializedName, varDecl, compiler);
}
}
PrintUtil::printFunctionEnd("HaOptModule::processVariableDecls");
}
/**
* Internal Method to handle function parameters
* @param functionDeclaration
*/
void HaOptModule::processParameters(
SgFunctionDeclaration *functionDeclaration) {
PrintUtil::printFunctionStart("HaOptModule::processParameters");
SgBasicBlock *functionBody =
functionDeclaration->get_definition()->get_body();
ROSE_ASSERT(functionBody);
SgFunctionParameterList *parameters =
functionDeclaration->get_parameterList();
ROSE_ASSERT (parameters);
SgInitializedNamePtrList & parameterList = parameters->get_args();
foreach(SgInitializedName * initializedName, parameterList)
{
SgType *paramType = initializedName->get_type();
string type = TransformationSupport::getTypeName(paramType);
trace << " Function Parameter :" << initializedName->get_name()
<< " Type: " << type << endl;
// Check if Meta Field exists
Field *metaField = meta->getField(initializedName->get_name().str());
if (metaField == NULL)
continue;
trace << " Meta Field found " << endl;
HAOPTUtil::DoPointer(initializedName, functionBody, compiler,
applyRestrict);
}
PrintUtil::printFunctionEnd("HaOptModule::processParameters");
}
/**
* Internal method to process functions
* @param project
*/
void HaOptModule::process(SgProject *project) {
// For each source file in the project
SgFilePtrList & fileList = project->get_fileList();
foreach(SgFile * file, fileList)
{
SgSourceFile * sourceFile = isSgSourceFile(file);
ROSE_ASSERT(sourceFile);
Rose_STL_Container<SgFunctionDeclaration*> functionList =
querySubTree<SgFunctionDeclaration>(sourceFile, V_SgFunctionDeclaration);
foreach(SgFunctionDeclaration * functionDeclaration, functionList)
{
// Check for function definition
SgFunctionDefinition *functionDefintion =
functionDeclaration->get_definition();
if (functionDefintion == NULL)
continue;
// Ignore functions in system headers, Can keep them to test robustness
if (functionDefintion->get_file_info()->get_filename()
!= sourceFile->get_file_info()->get_filename())
continue;
// Now, process this function
PrintUtil::printHeader(functionDeclaration->get_name());
processParameters (functionDeclaration);
processVariableDecls(functionDeclaration);
}
}
processPragma(project);
}
/**
* Hardware Optimization visitor
* @param project
*/
void HaOptModule::visit(SgProject *project) {
PrintUtil::printStart("HaOptModule");
if (isVisit) {
if (compiler == CompilerTypes::UNKNOWN) {
traceerror<< " Unknown Compiler Type " << endl;
exit(1);
}
process(project);
}
PrintUtil::printEnd("HaOptModule");
}
/**
* Private method to handle different options
* @param args
*/
void HaOptModule::handleModuleOptions(Rose_STL_Container<string> &args)
{
if (CommandlineProcessing::isOption(args, "-module:", "ha",
true)) {
isVisit = true;
}
if ( CommandlineProcessing::isOption(
args, "-ha:", "(r|restrict)", true) )
{
applyRestrict = true;
}
if ( CommandlineProcessing::isOption(
args, "-ha:", "(g|gcc)", true) )
{
compiler = CompilerTypes::GCC;
}
if ( CommandlineProcessing::isOption(
args, "-ha:", "(i|icc)", true) )
{
compiler = CompilerTypes::ICC;
}
if ( CommandlineProcessing::isOption(
args, "-ha:", "(x|xlc)", true) )
{
compiler = CompilerTypes::XLC;
}
if ( CommandlineProcessing::isOption(
args, "-ha:", "(p|pgi)", true) )
{
compiler = CompilerTypes::PGI;
}
}
| {
"pile_set_name": "Github"
} |
linuxlibertine.sf.net
If you want to report bugs please decide if you want to:
- use the bug tracking system on sourceforge (see linuxlibertine.sf.net -> bugtracker)
- send a mail to philthelion (at) sf.net
-Hinting is still not perfect (you will find hinting faults that deform glyphs in an ugly way but this effetcs just the screen not printing)
(Hinting isn't always the best way for rendering on screen (especially on Linux-systems). Since this release Windows users will see the latest improvements in the TTF-Regular. You can also use the OTF-files insteadt of ttf to achieve different displaytion. Pleae do not forget, that Hinting changes the letterforms to fit the screen pixels. Therefore it does look different on screen from the printed form. If you want to see how it might look printed, choose at least 600% zoom.
-A few accented charakters or non-latin-charakters are probably not the style native users would prefer (even Unicode-Standards sometimes aren't). Get into contact with me, if you have something to correct. In this way I got, for example, many corrections for the russion charakters lately, what resulted in an enormous improvement of the cyrillic alphabet in LinuxLibertine (thanks alot for your help, once again!).
-... | {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 96e7a4955fb484059b8ba72c253c3091
folderAsset: yes
timeCreated: 1546562654
licenseType: Pro
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
use Test::Nginx::Socket::Lua;
use Cwd qw(cwd);
my $pwd = cwd();
our $HttpConfig = qq{
lua_package_path "$pwd/lib/?.lua;;";
lua_package_cpath "$pwd/lib/?.lua;;";
};
repeat_each(3);
plan tests => repeat_each() * 3 * blocks();
no_shuffle();
run_tests();
__DATA__
=== TEST 1: Merge done in init
--- http_config eval
$::HttpConfig . q#
init_by_lua_block {
local lua_resty_waf = require "resty.waf"
lua_resty_waf.init()
}
#
--- config
location /t {
access_by_lua_block {
local lua_resty_waf = require "resty.waf"
local waf = lua_resty_waf:new()
ngx.say(waf.need_merge)
}
}
--- request
GET /t
--- error_code: 200
--- response_body
false
--- no_error_log
[error]
=== TEST 2: One-time global merge
--- http_config eval
$::HttpConfig . q#
init_by_lua_block {
local lua_resty_waf = require "resty.waf"
lua_resty_waf.init()
}
#
--- config
location /t {
access_by_lua_block {
local lua_resty_waf = require "resty.waf"
local waf = lua_resty_waf:new()
ngx.say(waf.need_merge)
}
}
--- request
GET /t
--- error_code: 200
--- response_body
false
--- no_error_log
[error]
=== TEST 3: No global merge done (init never called)
--- http_config eval: $::HttpConfig
--- config
location /t {
access_by_lua_block {
local lua_resty_waf = require "resty.waf"
local waf = lua_resty_waf:new()
ngx.say(waf.need_merge)
}
}
--- request
GET /t
--- error_code: 200
--- response_body
true
--- no_error_log
[error]
=== TEST 4: Individual merge needed (scope-local ruleset change)
--- http_config eval
$::HttpConfig . q#
init_by_lua_block {
local lua_resty_waf = require "resty.waf"
lua_resty_waf.init()
}
#
--- config
location /t {
access_by_lua_block {
local lua_resty_waf = require "resty.waf"
local waf = lua_resty_waf:new()
ngx.say(waf.need_merge)
waf:set_option("ignore_ruleset", "42000_xss")
ngx.say(waf.need_merge)
}
}
--- request
GET /t
--- error_code: 200
--- response_body
false
true
--- no_error_log
[error]
=== TEST 5: Ignoring ruleset triggers merge
--- http_config eval
$::HttpConfig . q#
init_by_lua_block {
local lua_resty_waf = require "resty.waf"
lua_resty_waf.init()
}
#
--- config
location /t {
access_by_lua_block {
local lua_resty_waf = require "resty.waf"
local waf = lua_resty_waf:new()
ngx.say(waf.need_merge)
waf:set_option("ignore_ruleset", "42000_xss")
ngx.say(waf.need_merge)
}
}
--- request
GET /t
--- error_code: 200
--- response_body
false
true
--- no_error_log
[error]
=== TEST 6: Adding ruleset triggers merge
--- http_config eval
$::HttpConfig . q#
init_by_lua_block {
local lua_resty_waf = require "resty.waf"
lua_resty_waf.init()
}
#
--- config
location /t {
access_by_lua_block {
local lua_resty_waf = require "resty.waf"
local waf = lua_resty_waf:new()
ngx.say(waf.need_merge)
waf:set_option("add_ruleset", "extra")
ngx.say(waf.need_merge)
}
}
--- request
GET /t
--- error_code: 200
--- response_body
false
true
--- no_error_log
[error]
=== TEST 7: Adding ruleset string triggers merge
--- http_config eval
$::HttpConfig . q#
init_by_lua_block {
local lua_resty_waf = require "resty.waf"
lua_resty_waf.init()
}
#
--- config
location /t {
access_by_lua_block {
local lua_resty_waf = require "resty.waf"
local waf = lua_resty_waf:new()
ngx.say(waf.need_merge)
waf:set_option("add_ruleset_string", "foo")
ngx.say(waf.need_merge)
}
}
--- request
GET /t
--- error_code: 200
--- response_body
false
true
--- no_error_log
[error]
=== TEST 8: Ignoring single rule does not trigger merge
--- http_config eval
$::HttpConfig . q#
init_by_lua_block {
local lua_resty_waf = require "resty.waf"
lua_resty_waf.init()
}
#
--- config
location /t {
access_by_lua_block {
local lua_resty_waf = require "resty.waf"
local waf = lua_resty_waf:new()
ngx.say(waf.need_merge)
waf:set_option("ignore_rule", 42001)
ngx.say(waf.need_merge)
}
}
--- request
GET /t
--- error_code: 200
--- response_body
false
false
--- no_error_log
[error]
| {
"pile_set_name": "Github"
} |
/* Include file for the R3 cone class */
/* Initialization functions */
int R3InitCone();
void R3StopCone();
/* Class definition */
class R3Cone : public R3Solid {
public:
// Constructor functions
R3Cone(void);
R3Cone(const R3Cone& cone);
R3Cone(const R3Span& axis, RNLength radius);
R3Cone(const R3Point& p1, const R3Point& p2, RNLength radius);
// Cone propetry functions/operators
const R3Point& Apex(void) const;
const R3Span& Axis(void) const;
const R3Circle& Base(void) const;
const RNLength Radius(void) const;
const RNLength Height(void) const;
const RNBoolean IsEmpty(void) const;
const RNBoolean IsFinite(void) const;
// Shape propetry functions/operators
virtual const RNBoolean IsPoint(void) const;
virtual const RNBoolean IsLinear(void) const ;
virtual const RNBoolean IsPlanar(void) const ;
virtual const RNBoolean IsConvex(void) const ;
virtual const RNInterval NFacets(void) const;
virtual const RNArea Area(void) const;
virtual const RNVolume Volume(void) const;
virtual const R3Point Centroid(void) const;
virtual const R3Shape& BShape(void) const;
virtual const R3Box BBox(void) const;
virtual const R3Sphere BSphere(void) const;
// Manipulation functions/operators
virtual void Empty(void);
virtual void Translate(const R3Vector& vector);
virtual void Reposition(const R3Span& span);
virtual void Resize(RNLength radius);
virtual void Transform(const R3Transformation& transformation);
// Draw functions/operators
virtual void Draw(const R3DrawFlags draw_flags = R3_DEFAULT_DRAW_FLAGS) const;
// Relationship functions/operators
RNBoolean operator==(const R3Cone& cone) const;
RNBoolean operator!=(const R3Cone& cone) const;
// Standard shape definitions
RN_CLASS_TYPE_DECLARATIONS(R3Cone);
R3_SHAPE_RELATIONSHIP_DECLARATIONS(R3Cone);
private:
R3Span axis;
R3Circle base;
};
/* Public variables */
extern const R3Cone R3null_cone;
extern const R3Cone R3zero_cone;
extern const R3Cone R3unit_cone;
extern const R3Cone R3infinite_cone;
/* Inline functions */
inline const R3Point& R3Cone::
Apex(void) const
{
// Return cone apex
return axis.End();
}
inline const R3Span& R3Cone::
Axis(void) const
{
// Return cone axis
return axis;
}
inline const R3Circle& R3Cone::
Base(void) const
{
// Return cone base circle
return base;
}
inline const RNLength R3Cone::
Radius(void) const
{
// Return cone radius
return base.Radius();
}
inline const RNLength R3Cone::
Height(void) const
{
// Return cone height
return axis.Length();
}
inline const RNBoolean R3Cone::
IsEmpty(void) const
{
// Return whether cone is empty
return (base.IsEmpty());
}
inline const RNBoolean R3Cone::
IsFinite(void) const
{
// Return whether cone is empty
return (base.IsFinite() && Apex().IsFinite());
}
inline RNBoolean R3Cone::
operator==(const R3Cone& cone) const
{
// Return whether cone is equal
return ((base == cone.base) && (axis == cone.axis));
}
inline RNBoolean R3Cone::
operator!=(const R3Cone& cone) const
{
// Return whether cone is not equal
return (!(*this == cone));
}
| {
"pile_set_name": "Github"
} |
# frozen_string_literal: true
# Cloud Foundry Java Buildpack
# Copyright 2013-2020 the original author or 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.
require 'java_buildpack'
module JavaBuildpack
# A module encapsulating all of the container components for the Java buildpack
module Container
end
end
| {
"pile_set_name": "Github"
} |
//
// AppDelegate.h
// Getting Started
//
// Created by Swartz on 11/19/14.
// Copyright (c) 2014 TokBox, Inc. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| {
"pile_set_name": "Github"
} |
{
"author": {
"name": "Mikeal Rogers",
"email": "[email protected]",
"url": "http://www.futurealoof.com"
},
"name": "cookie-jar",
"description": "Cookie Jar. Originally pulled form tobi, maintained as vendor in request, now a standalone module.",
"version": "0.3.0",
"repository": {
"url": "https://github.com/mikeal/cookie-jar"
},
"main": "index.js",
"scripts": {
"test": "node tests/run.js"
},
"dependencies": {},
"devDependencies": {},
"optionalDependencies": {},
"engines": {
"node": "*"
},
"readme": "cookie-jar\n==========\n\nCookie Jar. Originally pulled from LearnBoost/tobi, maintained as vendor in request, now a standalone module.\n",
"readmeFilename": "README.md",
"_id": "[email protected]",
"_from": "cookie-jar@~0.3.0"
}
| {
"pile_set_name": "Github"
} |
<?php
class Filter
{
private $mDom;
private $mXss;
private $mOk;
private $mAllowAttr = array('title', 'src', 'href', 'id', 'class', 'style', 'width', 'height', 'alt', 'target', 'align');
private $mAllowTag = array('a', 'img', 'br', 'strong', 'b', 'code', 'pre', 'p', 'div', 'em', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'table', 'ul', 'ol', 'tr', 'th', 'td', 'hr', 'li', 'u');
/**
* 字符串过滤
* @param string|array $date
* @param boolean $force
* @return string|array
*/
public function in($data, $force = false)
{
if (is_string($data))
{
if ($force == true || !get_magic_quotes_gpc())
{
$data = addslashes(trim($data));
}
return trim($data);
}
else
{
if (is_array($data))
{
foreach ($data as $key => $value)
{
$data[$key] = $this->in($value, $force);
}
return $data;
}
else
{
return $data;
}
}
}
/**
* 字符串还原
* @param string|array $date
* @return string|array
*/
public function out($data)
{
if (is_string($data))
{
return $data = stripslashes($data);
}
else
{
if (is_array($data))
{
foreach ($data as $key => $value)
{
$data[$key] = $this->out($value);
}
return $data;
}
else
{
return $data;
}
}
}
/**
* 帖子过滤处理
* @param string $date
* @return string
*/
public function topicIn($data)
{
$data = str_replace(["\n", " "], ["##br/##", "##nbsp;"], $data);
$data = htmlspecialchars($data);
$data = str_replace(["##br/##", "##nbsp;"], ["<br/>", " "], $data);
return $this->in($data);
}
/**
* 帖子过滤处理(WEB)
* @param string $date
* @return string
*/
public function topicInWeb($data)
{
$this->doFilter($data);
$data = $this->getHtml();
return $this->in($data);
}
/**
* 帖子输出处理
* @param string $date
* @return string
*/
public function topicOut($data, $changeEmoji = false)
{
$data = $this->out($data);
if ($changeEmoji)
{
$data = preg_replace("/<img src=\"\/app\/views\/emoji\/(\d+\.gif)\".+?>/i", '<img class="emoji" src="images/emoji/${1}"/>', $data);
}
return trim($data);
}
private function doFilter($html, $charset = 'utf-8', $AllowTag = [])
{
$this->mAllowTag = empty($AllowTag) ? $this->mAllowTag : $AllowTag;
if (is_array($html) && !empty($html)) {
static::doFilter(implode(' ', $html), $charset, $AllowTag);
} else {
$this->mXss = strip_tags($html, '<' . implode('><', $this->mAllowTag) . '>');
if (empty($this->mXss)) {
$this->mOk = FALSE;
return ;
}
$this->mXss = "<meta http-equiv=\"Content-Type\" content=\"text/html;charset={$charset}\"><nouse>" . $this->mXss . "</nouse>";
$this->mDom = new DOMDocument();
$this->mDom->strictErrorChecking = FALSE;
$this->mOk = @$this->mDom->loadHTML($this->mXss);
}
}
/**
* 获得过滤后的内容
*/
public function getHtml()
{
if (!$this->mOk)
{
return '';
}
$nodeList = $this->mDom->getElementsByTagName('*');
for ($i = 0; $i < $nodeList->length; $i++)
{
$node = $nodeList->item($i);
if (in_array($node->nodeName, $this->mAllowTag))
{
if (method_exists($this, "__node_{$node->nodeName}"))
{
call_user_func(array($this, "__node_{$node->nodeName}"), $node);
}
else
{
call_user_func(array($this, '__node_default'), $node);
}
}
}
$html = strip_tags($this->mDom->saveHTML(), '<' . implode('><', $this->mAllowTag) . '>');
$html = preg_replace('/^\n(.*)\n$/s', '$1', $html);
return $html;
}
private function __true_url($url)
{
if (preg_match('#^https?://.+#is', $url))
{
return $url;
}
else
{
return 'http://' . $url;
}
}
private function __get_style($node)
{
if ($node->attributes->getNamedItem('style'))
{
$style = $node->attributes->getNamedItem('style')->nodeValue;
$style = str_replace('\\', ' ', $style);
$style = str_replace(array('&#', '/*', '*/'), ' ', $style);
$style = preg_replace('#e.*x.*p.*r.*e.*s.*s.*i.*o.*n#Uis', ' ', $style);
return $style;
}
else
{
return '';
}
}
private function __get_link($node, $att)
{
$link = $node->attributes->getNamedItem($att);
if ($link)
{
return $this->__true_url($link->nodeValue);
}
else
{
return '';
}
}
private function __setAttr($dom, $attr, $val)
{
if (!empty($val))
{
$dom->setAttribute($attr, $val);
}
}
private function __set_default_attr($node, $attr, $default = '')
{
$o = $node->attributes->getNamedItem($attr);
if ($o)
{
$this->__setAttr($node, $attr, $o->nodeValue);
}
else
{
$this->__setAttr($node, $attr, $default);
}
}
private function __common_attr($node)
{
$list = array();
foreach ($node->attributes as $attr)
{
if (!in_array($attr->nodeName, $this->mAllowAttr))
{
$list[] = $attr->nodeName;
}
}
foreach ($list as $attr)
{
$node->removeAttribute($attr);
}
$style = $this->__get_style($node);
$this->__setAttr($node, 'style', $style);
$this->__set_default_attr($node, 'title');
$this->__set_default_attr($node, 'id');
$this->__set_default_attr($node, 'class');
}
private function __node_img($node)
{
$this->__common_attr($node);
$this->__set_default_attr($node, 'src');
$this->__set_default_attr($node, 'width');
$this->__set_default_attr($node, 'height');
$this->__set_default_attr($node, 'alt');
$this->__set_default_attr($node, 'align');
}
private function __node_a($node)
{
$this->__common_attr($node);
$href = $this->__get_link($node, 'href');
$this->__setAttr($node, 'href', $href);
$this->__set_default_attr($node, 'target', '_blank');
}
private function __node_embed($node)
{
$this->__common_attr($node);
$link = $this->__get_link($node, 'src');
$this->__setAttr($node, 'src', $link);
$this->__setAttr($node, 'allowscriptaccess', 'never');
$this->__set_default_attr($node, 'width');
$this->__set_default_attr($node, 'height');
}
private function __node_default($node)
{
$this->__common_attr($node);
}
}
?>
| {
"pile_set_name": "Github"
} |
import io
import os
import hashlib
import getpass
from base64 import standard_b64encode
from distutils import log
from distutils.command import upload as orig
from distutils.spawn import spawn
from distutils.errors import DistutilsError
from setuptools.extern.six.moves.urllib.request import urlopen, Request
from setuptools.extern.six.moves.urllib.error import HTTPError
from setuptools.extern.six.moves.urllib.parse import urlparse
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def run(self):
try:
orig.upload.run(self)
finally:
self.announce(
"WARNING: Uploading via this command is deprecated, use twine "
"to upload instead (https://pypi.org/p/twine/)",
log.WARN
)
def finalize_options(self):
orig.upload.finalize_options(self)
self.username = (
self.username or
getpass.getuser()
)
# Attempt to obtain password. Short circuit evaluation at the first
# sign of success.
self.password = (
self.password or
self._load_password_from_keyring() or
self._prompt_for_password()
)
def upload_file(self, command, pyversion, filename):
# Makes sure the repository URL is compliant
schema, netloc, url, params, query, fragments = \
urlparse(self.repository)
if params or query or fragments:
raise AssertionError("Incompatible url %s" % self.repository)
if schema not in ('http', 'https'):
raise AssertionError("unsupported schema " + schema)
# Sign if requested
if self.sign:
gpg_args = ["gpg", "--detach-sign", "-a", filename]
if self.identity:
gpg_args[2:2] = ["--local-user", self.identity]
spawn(gpg_args,
dry_run=self.dry_run)
# Fill in the data - send all the meta-data in case we need to
# register a new release
with open(filename, 'rb') as f:
content = f.read()
meta = self.distribution.metadata
data = {
# action
':action': 'file_upload',
'protocol_version': '1',
# identify release
'name': meta.get_name(),
'version': meta.get_version(),
# file content
'content': (os.path.basename(filename), content),
'filetype': command,
'pyversion': pyversion,
'md5_digest': hashlib.md5(content).hexdigest(),
# additional meta-data
'metadata_version': str(meta.get_metadata_version()),
'summary': meta.get_description(),
'home_page': meta.get_url(),
'author': meta.get_contact(),
'author_email': meta.get_contact_email(),
'license': meta.get_licence(),
'description': meta.get_long_description(),
'keywords': meta.get_keywords(),
'platform': meta.get_platforms(),
'classifiers': meta.get_classifiers(),
'download_url': meta.get_download_url(),
# PEP 314
'provides': meta.get_provides(),
'requires': meta.get_requires(),
'obsoletes': meta.get_obsoletes(),
}
data['comment'] = ''
if self.sign:
data['gpg_signature'] = (os.path.basename(filename) + ".asc",
open(filename+".asc", "rb").read())
# set up the authentication
user_pass = (self.username + ":" + self.password).encode('ascii')
# The exact encoding of the authentication string is debated.
# Anyway PyPI only accepts ascii for both username or password.
auth = "Basic " + standard_b64encode(user_pass).decode('ascii')
# Build up the MIME payload for the POST data
boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
sep_boundary = b'\r\n--' + boundary.encode('ascii')
end_boundary = sep_boundary + b'--\r\n'
body = io.BytesIO()
for key, value in data.items():
title = '\r\nContent-Disposition: form-data; name="%s"' % key
# handle multiple entries for the same name
if not isinstance(value, list):
value = [value]
for value in value:
if type(value) is tuple:
title += '; filename="%s"' % value[0]
value = value[1]
else:
value = str(value).encode('utf-8')
body.write(sep_boundary)
body.write(title.encode('utf-8'))
body.write(b"\r\n\r\n")
body.write(value)
body.write(end_boundary)
body = body.getvalue()
msg = "Submitting %s to %s" % (filename, self.repository)
self.announce(msg, log.INFO)
# build the Request
headers = {
'Content-type': 'multipart/form-data; boundary=%s' % boundary,
'Content-length': str(len(body)),
'Authorization': auth,
}
request = Request(self.repository, data=body,
headers=headers)
# send the data
try:
result = urlopen(request)
status = result.getcode()
reason = result.msg
except HTTPError as e:
status = e.code
reason = e.msg
except OSError as e:
self.announce(str(e), log.ERROR)
raise
if status == 200:
self.announce('Server response (%s): %s' % (status, reason),
log.INFO)
if self.show_response:
text = getattr(self, '_read_pypi_response',
lambda x: None)(result)
if text is not None:
msg = '\n'.join(('-' * 75, text, '-' * 75))
self.announce(msg, log.INFO)
else:
msg = 'Upload failed (%s): %s' % (status, reason)
self.announce(msg, log.ERROR)
raise DistutilsError(msg)
def _load_password_from_keyring(self):
"""
Attempt to load password from keyring. Suppress Exceptions.
"""
try:
keyring = __import__('keyring')
return keyring.get_password(self.repository, self.username)
except Exception:
pass
def _prompt_for_password(self):
"""
Prompt for a password on the tty. Suppress Exceptions.
"""
try:
return getpass.getpass()
except (Exception, KeyboardInterrupt):
pass
| {
"pile_set_name": "Github"
} |
using System.Globalization;
using System.Runtime.CompilerServices;
using Lucene.Net.Util;
namespace Raven.Server.Documents.Indexes.Persistence.Lucene.Analyzers
{
public struct LowerCaseKeywordTokenizerHelper : ILowerCaseTokenizerHelper
{
private static readonly TextInfo _invariantTextInfo = CultureInfo.InvariantCulture.TextInfo;
/// <summary>Returns true iff a character should be included in a token. This
/// tokenizer generates as tokens adjacent sequences of characters which
/// satisfy this predicate. Characters for which this is false are used to
/// define token boundaries and are not included in tokens.
/// </summary>
public bool IsTokenChar(char c)
{
return true;
}
/// <summary>Called on each token character to normalize it before it is added to the
/// token. The default implementation does nothing. Subclasses may use this
/// to, e.g., lowercase tokens.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public char Normalize(char c)
{
int cInt = c;
if (cInt < 128)
{
if (65 <= cInt && cInt <= 90)
c |= ' ';
return c;
}
return _invariantTextInfo.ToLower(c);
}
}
public class LowerCaseKeywordTokenizer : LowerCaseTokenizerBase<LowerCaseKeywordTokenizerHelper>
{
public LowerCaseKeywordTokenizer(System.IO.TextReader input)
: base(input)
{ }
protected LowerCaseKeywordTokenizer(AttributeSource source, System.IO.TextReader input)
: base(source, input)
{ }
protected LowerCaseKeywordTokenizer(AttributeFactory factory, System.IO.TextReader input)
: base(factory, input)
{ }
}
}
| {
"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.
*/
// GENERAL
// CONSONANTS
"sz" "" "" "s"
"zs" "" "" "Z"
"cs" "" "" "tS"
"ay" "" "" "(oj|aj)"
"ai" "" "" "(oj|aj)"
"aj" "" "" "(oj|aj)"
"ei" "" "" "(aj|ej)" // German element
"ey" "" "" "(aj|ej)" // German element
"y" "[áo]" "" "j"
"i" "[áo]" "" "j"
"ee" "" "" "(ej|e)"
"ely" "" "" "(ej|eli)"
"ly" "" "" "(j|li)"
"gy" "" "[aeouáéóúüöőű]" "dj"
"gy" "" "" "(d|gi)"
"ny" "" "[aeouáéóúüöőű]" "nj"
"ny" "" "" "(n|ni)"
"ty" "" "[aeouáéóúüöőű]" "tj"
"ty" "" "" "(t|ti)"
"qu" "" "" "(ku|kv)"
"h" "" "$" ""
// SPECIAL VOWELS
"á" "" "" "a"
"é" "" "" "e"
"í" "" "" "i"
"ó" "" "" "o"
"ú" "" "" "u"
"ö" "" "" "Y"
"ő" "" "" "Y"
"ü" "" "" "Q"
"ű" "" "" "Q"
// LATIN ALPHABET
"a" "" "" "a"
"b" "" "" "b"
"c" "" "" "ts"
"d" "" "" "d"
"e" "" "" "E"
"f" "" "" "f"
"g" "" "" "g"
"h" "" "" "h"
"i" "" "" "I"
"j" "" "" "j"
"k" "" "" "k"
"l" "" "" "l"
"m" "" "" "m"
"n" "" "" "n"
"o" "" "" "o"
"p" "" "" "p"
"q" "" "" "k"
"r" "" "" "r"
"s" "" "" "(S|s)"
"t" "" "" "t"
"u" "" "" "u"
"v" "" "" "v"
"w" "" "" "v"
"x" "" "" "ks"
"y" "" "" "i"
"z" "" "" "z"
| {
"pile_set_name": "Github"
} |
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Southwest Research Institute
* 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 the Southwest Research Institute, 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.
*/
#ifndef SIMPLE_MESSAGE_CONNECTION_H
#define SIMPLE_MESSAGE_CONNECTION_H
#ifndef FLATHEADERS
#include "simple_message/byte_array.h"
#include "simple_message/simple_message.h"
#include "simple_message/shared_types.h"
#else
#include "byte_array.h"
#include "simple_message.h"
#include "shared_types.h"
#endif
namespace industrial
{
namespace smpl_msg_connection
{
/**
* \brief Defines an interface and common methods for sending simple messages
* (see simple_message). This interface makes a bare minimum of assumptions:
*
* 1. The connection is capable of sending raw bytes (encapsulated within a simple message)
*
* 2. The data connection has an explicit connect that establishes the connection (and an
* associated disconnect method). NOTE: For data connections that are connectionless,
* such as UDP, the connection method can be a NULL operation.
*/
class SmplMsgConnection
{
public:
// Message
/**
* \brief Sends a message using the data connection
*
* \param message to send
*
* \return true if successful
*/
virtual bool sendMsg(industrial::simple_message::SimpleMessage & message);
/**
* \brief Receives a message using the data connection
*
* \param populated with received message
*
* \return true if successful
*/
virtual bool receiveMsg(industrial::simple_message::SimpleMessage & message);
/**
* \brief Performs a complete send and receive. This is helpful when sending
* a message that requires and explicit reply
*
* \param message to send
* \param populated with received message
* \param verbosity level of low level logging
*
* \return true if successful
*/
bool sendAndReceiveMsg(industrial::simple_message::SimpleMessage & send,
industrial::simple_message::SimpleMessage & recv,
bool verbose = false);
/**
* \brief return connection status
*
* \return true if connected
*/
virtual bool isConnected()=0;
/**
* \brief connects to the remote host
*
* \return true on success, false otherwise
*/
virtual bool makeConnect()=0;
private:
// Overrides
/**
* \brief Method used by send message interface method. This should be overridden
* for the specific connection type
*
* \param data to send.
*
* \return true if successful
*/
virtual bool sendBytes(industrial::byte_array::ByteArray & buffer) =0;
/**
* \brief Method used by receive message interface method. This should be overridden
* for the specific connection type
*
* \param data to receive.
* \param size (in bytes) of data to receive
*
* \return true if successful
*/
virtual bool receiveBytes(industrial::byte_array::ByteArray & buffer,
industrial::shared_types::shared_int num_bytes) =0;
};
} //namespace message_connection
} //namespace industrial
#endif //SIMPLE_MESSAGE_CONNECTION_H
| {
"pile_set_name": "Github"
} |
package me.zjns.lovecloudmusic.hooker;
import android.graphics.Canvas;
import android.os.BaseBundle;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import de.robv.android.xposed.XC_MethodHook;
import me.zjns.lovecloudmusic.hooker.base.BaseHook;
import static me.zjns.lovecloudmusic.Utils.findAndHookMethod;
public class CommonAdHook extends BaseHook {
private boolean removeSplashAd;
private boolean removeSearchAd;
@Override
protected void hookMain() {
removeSplashAd();
removeSearchBannerAd();
}
@Override
protected void initPrefs() {
removeSplashAd = prefs.getBoolean("convert_to_play", false);
removeSearchAd = prefs.getBoolean("remove_search_banner_ad", false);
}
private void removeSplashAd() {
Class<?> BundleClass = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? BaseBundle.class : Bundle.class;
findAndHookMethod(BundleClass,
"getSerializable", String.class,
new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if ("adInfo".equals(param.args[0])) {
loadPrefs();
if (!removeSplashAd) return;
param.setResult(null);
}
}
});
}
private void removeSearchBannerAd() {
findAndHookMethod("com.netease.cloudmusic.ui.AdBannerView", loader,
"onDraw", Canvas.class,
new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
loadPrefs();
if (!removeSearchAd) return;
View view = (View) param.thisObject;
View parent = (View) view.getParent().getParent();
boolean isTarget = parent instanceof LinearLayout;
if (isTarget) {
LinearLayout real = (LinearLayout) parent;
if (real.getChildCount() != 0) {
real.setVisibility(View.GONE);
real.removeAllViews();
param.setResult(null);
}
}
}
});
}
}
| {
"pile_set_name": "Github"
} |
package yamux
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"net"
"strings"
"sync"
"sync/atomic"
"time"
)
// Session is used to wrap a reliable ordered connection and to
// multiplex it into multiple streams.
type Session struct {
// remoteGoAway indicates the remote side does
// not want futher connections. Must be first for alignment.
remoteGoAway int32
// localGoAway indicates that we should stop
// accepting futher connections. Must be first for alignment.
localGoAway int32
// nextStreamID is the next stream we should
// send. This depends if we are a client/server.
nextStreamID uint32
// config holds our configuration
config *Config
// logger is used for our logs
logger *log.Logger
// conn is the underlying connection
conn io.ReadWriteCloser
// bufRead is a buffered reader
bufRead *bufio.Reader
// pings is used to track inflight pings
pings map[uint32]chan struct{}
pingID uint32
pingLock sync.Mutex
// streams maps a stream id to a stream, and inflight has an entry
// for any outgoing stream that has not yet been established. Both are
// protected by streamLock.
streams map[uint32]*Stream
inflight map[uint32]struct{}
streamLock sync.Mutex
// synCh acts like a semaphore. It is sized to the AcceptBacklog which
// is assumed to be symmetric between the client and server. This allows
// the client to avoid exceeding the backlog and instead blocks the open.
synCh chan struct{}
// acceptCh is used to pass ready streams to the client
acceptCh chan *Stream
// sendCh is used to mark a stream as ready to send,
// or to send a header out directly.
sendCh chan sendReady
// recvDoneCh is closed when recv() exits to avoid a race
// between stream registration and stream shutdown
recvDoneCh chan struct{}
// shutdown is used to safely close a session
shutdown bool
shutdownErr error
shutdownCh chan struct{}
shutdownLock sync.Mutex
}
// sendReady is used to either mark a stream as ready
// or to directly send a header
type sendReady struct {
Hdr []byte
Body io.Reader
Err chan error
}
// newSession is used to construct a new session
func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session {
logger := config.Logger
if logger == nil {
logger = log.New(config.LogOutput, "", log.LstdFlags)
}
s := &Session{
config: config,
logger: logger,
conn: conn,
bufRead: bufio.NewReader(conn),
pings: make(map[uint32]chan struct{}),
streams: make(map[uint32]*Stream),
inflight: make(map[uint32]struct{}),
synCh: make(chan struct{}, config.AcceptBacklog),
acceptCh: make(chan *Stream, config.AcceptBacklog),
sendCh: make(chan sendReady, 64),
recvDoneCh: make(chan struct{}),
shutdownCh: make(chan struct{}),
}
if client {
s.nextStreamID = 1
} else {
s.nextStreamID = 2
}
go s.recv()
go s.send()
if config.EnableKeepAlive {
go s.keepalive()
}
return s
}
// IsClosed does a safe check to see if we have shutdown
func (s *Session) IsClosed() bool {
select {
case <-s.shutdownCh:
return true
default:
return false
}
}
// CloseChan returns a read-only channel which is closed as
// soon as the session is closed.
func (s *Session) CloseChan() <-chan struct{} {
return s.shutdownCh
}
// NumStreams returns the number of currently open streams
func (s *Session) NumStreams() int {
s.streamLock.Lock()
num := len(s.streams)
s.streamLock.Unlock()
return num
}
// Open is used to create a new stream as a net.Conn
func (s *Session) Open() (net.Conn, error) {
conn, err := s.OpenStream()
if err != nil {
return nil, err
}
return conn, nil
}
// OpenStream is used to create a new stream
func (s *Session) OpenStream() (*Stream, error) {
if s.IsClosed() {
return nil, ErrSessionShutdown
}
if atomic.LoadInt32(&s.remoteGoAway) == 1 {
return nil, ErrRemoteGoAway
}
// Block if we have too many inflight SYNs
select {
case s.synCh <- struct{}{}:
case <-s.shutdownCh:
return nil, ErrSessionShutdown
}
GET_ID:
// Get an ID, and check for stream exhaustion
id := atomic.LoadUint32(&s.nextStreamID)
if id >= math.MaxUint32-1 {
return nil, ErrStreamsExhausted
}
if !atomic.CompareAndSwapUint32(&s.nextStreamID, id, id+2) {
goto GET_ID
}
// Register the stream
stream := newStream(s, id, streamInit)
s.streamLock.Lock()
s.streams[id] = stream
s.inflight[id] = struct{}{}
s.streamLock.Unlock()
// Send the window update to create
if err := stream.sendWindowUpdate(); err != nil {
select {
case <-s.synCh:
default:
s.logger.Printf("[ERR] yamux: aborted stream open without inflight syn semaphore")
}
return nil, err
}
return stream, nil
}
// Accept is used to block until the next available stream
// is ready to be accepted.
func (s *Session) Accept() (net.Conn, error) {
conn, err := s.AcceptStream()
if err != nil {
return nil, err
}
return conn, err
}
// AcceptStream is used to block until the next available stream
// is ready to be accepted.
func (s *Session) AcceptStream() (*Stream, error) {
select {
case stream := <-s.acceptCh:
if err := stream.sendWindowUpdate(); err != nil {
return nil, err
}
return stream, nil
case <-s.shutdownCh:
return nil, s.shutdownErr
}
}
// Close is used to close the session and all streams.
// Attempts to send a GoAway before closing the connection.
func (s *Session) Close() error {
s.shutdownLock.Lock()
defer s.shutdownLock.Unlock()
if s.shutdown {
return nil
}
s.shutdown = true
if s.shutdownErr == nil {
s.shutdownErr = ErrSessionShutdown
}
close(s.shutdownCh)
s.conn.Close()
<-s.recvDoneCh
s.streamLock.Lock()
defer s.streamLock.Unlock()
for _, stream := range s.streams {
stream.forceClose()
}
return nil
}
// exitErr is used to handle an error that is causing the
// session to terminate.
func (s *Session) exitErr(err error) {
s.shutdownLock.Lock()
if s.shutdownErr == nil {
s.shutdownErr = err
}
s.shutdownLock.Unlock()
s.Close()
}
// GoAway can be used to prevent accepting further
// connections. It does not close the underlying conn.
func (s *Session) GoAway() error {
return s.waitForSend(s.goAway(goAwayNormal), nil)
}
// goAway is used to send a goAway message
func (s *Session) goAway(reason uint32) header {
atomic.SwapInt32(&s.localGoAway, 1)
hdr := header(make([]byte, headerSize))
hdr.encode(typeGoAway, 0, 0, reason)
return hdr
}
// Ping is used to measure the RTT response time
func (s *Session) Ping() (time.Duration, error) {
// Get a channel for the ping
ch := make(chan struct{})
// Get a new ping id, mark as pending
s.pingLock.Lock()
id := s.pingID
s.pingID++
s.pings[id] = ch
s.pingLock.Unlock()
// Send the ping request
hdr := header(make([]byte, headerSize))
hdr.encode(typePing, flagSYN, 0, id)
if err := s.waitForSend(hdr, nil); err != nil {
return 0, err
}
// Wait for a response
start := time.Now()
select {
case <-ch:
case <-time.After(s.config.ConnectionWriteTimeout):
s.pingLock.Lock()
delete(s.pings, id) // Ignore it if a response comes later.
s.pingLock.Unlock()
return 0, ErrTimeout
case <-s.shutdownCh:
return 0, ErrSessionShutdown
}
// Compute the RTT
return time.Now().Sub(start), nil
}
// keepalive is a long running goroutine that periodically does
// a ping to keep the connection alive.
func (s *Session) keepalive() {
for {
select {
case <-time.After(s.config.KeepAliveInterval):
_, err := s.Ping()
if err != nil {
if err != ErrSessionShutdown {
s.logger.Printf("[ERR] yamux: keepalive failed: %v", err)
s.exitErr(ErrKeepAliveTimeout)
}
return
}
case <-s.shutdownCh:
return
}
}
}
// waitForSendErr waits to send a header, checking for a potential shutdown
func (s *Session) waitForSend(hdr header, body io.Reader) error {
errCh := make(chan error, 1)
return s.waitForSendErr(hdr, body, errCh)
}
// waitForSendErr waits to send a header with optional data, checking for a
// potential shutdown. Since there's the expectation that sends can happen
// in a timely manner, we enforce the connection write timeout here.
func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) error {
t := timerPool.Get()
timer := t.(*time.Timer)
timer.Reset(s.config.ConnectionWriteTimeout)
defer func() {
timer.Stop()
select {
case <-timer.C:
default:
}
timerPool.Put(t)
}()
ready := sendReady{Hdr: hdr, Body: body, Err: errCh}
select {
case s.sendCh <- ready:
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
select {
case err := <-errCh:
return err
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
}
// sendNoWait does a send without waiting. Since there's the expectation that
// the send happens right here, we enforce the connection write timeout if we
// can't queue the header to be sent.
func (s *Session) sendNoWait(hdr header) error {
t := timerPool.Get()
timer := t.(*time.Timer)
timer.Reset(s.config.ConnectionWriteTimeout)
defer func() {
timer.Stop()
select {
case <-timer.C:
default:
}
timerPool.Put(t)
}()
select {
case s.sendCh <- sendReady{Hdr: hdr}:
return nil
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
}
// send is a long running goroutine that sends data
func (s *Session) send() {
for {
select {
case ready := <-s.sendCh:
// Send a header if ready
if ready.Hdr != nil {
sent := 0
for sent < len(ready.Hdr) {
n, err := s.conn.Write(ready.Hdr[sent:])
if err != nil {
s.logger.Printf("[ERR] yamux: Failed to write header: %v", err)
asyncSendErr(ready.Err, err)
s.exitErr(err)
return
}
sent += n
}
}
// Send data from a body if given
if ready.Body != nil {
_, err := io.Copy(s.conn, ready.Body)
if err != nil {
s.logger.Printf("[ERR] yamux: Failed to write body: %v", err)
asyncSendErr(ready.Err, err)
s.exitErr(err)
return
}
}
// No error, successful send
asyncSendErr(ready.Err, nil)
case <-s.shutdownCh:
return
}
}
}
// recv is a long running goroutine that accepts new data
func (s *Session) recv() {
if err := s.recvLoop(); err != nil {
s.exitErr(err)
}
}
// Ensure that the index of the handler (typeData/typeWindowUpdate/etc) matches the message type
var (
handlers = []func(*Session, header) error{
typeData: (*Session).handleStreamMessage,
typeWindowUpdate: (*Session).handleStreamMessage,
typePing: (*Session).handlePing,
typeGoAway: (*Session).handleGoAway,
}
)
// recvLoop continues to receive data until a fatal error is encountered
func (s *Session) recvLoop() error {
defer close(s.recvDoneCh)
hdr := header(make([]byte, headerSize))
for {
// Read the header
if _, err := io.ReadFull(s.bufRead, hdr); err != nil {
if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") {
s.logger.Printf("[ERR] yamux: Failed to read header: %v", err)
}
return err
}
// Verify the version
if hdr.Version() != protoVersion {
s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version())
return ErrInvalidVersion
}
mt := hdr.MsgType()
if mt < typeData || mt > typeGoAway {
return ErrInvalidMsgType
}
if err := handlers[mt](s, hdr); err != nil {
return err
}
}
}
// handleStreamMessage handles either a data or window update frame
func (s *Session) handleStreamMessage(hdr header) error {
// Check for a new stream creation
id := hdr.StreamID()
flags := hdr.Flags()
if flags&flagSYN == flagSYN {
if err := s.incomingStream(id); err != nil {
return err
}
}
// Get the stream
s.streamLock.Lock()
stream := s.streams[id]
s.streamLock.Unlock()
// If we do not have a stream, likely we sent a RST
if stream == nil {
// Drain any data on the wire
if hdr.MsgType() == typeData && hdr.Length() > 0 {
s.logger.Printf("[WARN] yamux: Discarding data for stream: %d", id)
if _, err := io.CopyN(ioutil.Discard, s.bufRead, int64(hdr.Length())); err != nil {
s.logger.Printf("[ERR] yamux: Failed to discard data: %v", err)
return nil
}
} else {
s.logger.Printf("[WARN] yamux: frame for missing stream: %v", hdr)
}
return nil
}
// Check if this is a window update
if hdr.MsgType() == typeWindowUpdate {
if err := stream.incrSendWindow(hdr, flags); err != nil {
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return err
}
return nil
}
// Read the new data
if err := stream.readData(hdr, flags, s.bufRead); err != nil {
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return err
}
return nil
}
// handlePing is invokde for a typePing frame
func (s *Session) handlePing(hdr header) error {
flags := hdr.Flags()
pingID := hdr.Length()
// Check if this is a query, respond back in a separate context so we
// don't interfere with the receiving thread blocking for the write.
if flags&flagSYN == flagSYN {
go func() {
hdr := header(make([]byte, headerSize))
hdr.encode(typePing, flagACK, 0, pingID)
if err := s.sendNoWait(hdr); err != nil {
s.logger.Printf("[WARN] yamux: failed to send ping reply: %v", err)
}
}()
return nil
}
// Handle a response
s.pingLock.Lock()
ch := s.pings[pingID]
if ch != nil {
delete(s.pings, pingID)
close(ch)
}
s.pingLock.Unlock()
return nil
}
// handleGoAway is invokde for a typeGoAway frame
func (s *Session) handleGoAway(hdr header) error {
code := hdr.Length()
switch code {
case goAwayNormal:
atomic.SwapInt32(&s.remoteGoAway, 1)
case goAwayProtoErr:
s.logger.Printf("[ERR] yamux: received protocol error go away")
return fmt.Errorf("yamux protocol error")
case goAwayInternalErr:
s.logger.Printf("[ERR] yamux: received internal error go away")
return fmt.Errorf("remote yamux internal error")
default:
s.logger.Printf("[ERR] yamux: received unexpected go away")
return fmt.Errorf("unexpected go away received")
}
return nil
}
// incomingStream is used to create a new incoming stream
func (s *Session) incomingStream(id uint32) error {
// Reject immediately if we are doing a go away
if atomic.LoadInt32(&s.localGoAway) == 1 {
hdr := header(make([]byte, headerSize))
hdr.encode(typeWindowUpdate, flagRST, id, 0)
return s.sendNoWait(hdr)
}
// Allocate a new stream
stream := newStream(s, id, streamSYNReceived)
s.streamLock.Lock()
defer s.streamLock.Unlock()
// Check if stream already exists
if _, ok := s.streams[id]; ok {
s.logger.Printf("[ERR] yamux: duplicate stream declared")
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return ErrDuplicateStream
}
// Register the stream
s.streams[id] = stream
// Check if we've exceeded the backlog
select {
case s.acceptCh <- stream:
return nil
default:
// Backlog exceeded! RST the stream
s.logger.Printf("[WARN] yamux: backlog exceeded, forcing connection reset")
delete(s.streams, id)
stream.sendHdr.encode(typeWindowUpdate, flagRST, id, 0)
return s.sendNoWait(stream.sendHdr)
}
}
// closeStream is used to close a stream once both sides have
// issued a close. If there was an in-flight SYN and the stream
// was not yet established, then this will give the credit back.
func (s *Session) closeStream(id uint32) {
s.streamLock.Lock()
if _, ok := s.inflight[id]; ok {
select {
case <-s.synCh:
default:
s.logger.Printf("[ERR] yamux: SYN tracking out of sync")
}
}
delete(s.streams, id)
s.streamLock.Unlock()
}
// establishStream is used to mark a stream that was in the
// SYN Sent state as established.
func (s *Session) establishStream(id uint32) {
s.streamLock.Lock()
if _, ok := s.inflight[id]; ok {
delete(s.inflight, id)
} else {
s.logger.Printf("[ERR] yamux: established stream without inflight SYN (no tracking entry)")
}
select {
case <-s.synCh:
default:
s.logger.Printf("[ERR] yamux: established stream without inflight SYN (didn't have semaphore)")
}
s.streamLock.Unlock()
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2012 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using Google.Apis.Requests;
using Google.Apis.Util;
using System;
using System.Collections.Generic;
using System.Net.Http;
using Xunit;
namespace Google.Apis.Tests.Apis.Requests
{
/// <summary>Tests the functionality of <see cref="Google.Apis.Requests.RequestBuilder" />.</summary>
public class RequestBuilderTest
{
/// <summary>Verifies that a basic request is created with "GET" as default HTTP method.</summary>
[Fact]
public void TestBasicWebRequest()
{
var builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.example.com/")
};
var request = builder.CreateRequest();
Assert.Equal(HttpMethod.Get, request.Method);
Assert.Equal(new Uri("http://www.example.com/"), request.RequestUri);
}
/// <summary>Verifies that a basic request is created with "POST" method.</summary>
[Fact]
public void TestPostWebRequest()
{
var builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.example.com/"),
Method = "POST"
};
var request = builder.CreateRequest();
Assert.Equal(HttpMethod.Post, request.Method);
Assert.Equal(new Uri("http://www.example.com/"), request.RequestUri);
}
/// <summary>Verifies that the path is correctly appended to the base URI.</summary>
[Theory]
[InlineData("http://www.example.com/", "test/path", "http://www.example.com/test/path")]
[InlineData("http://www.example.com/", "test/a:path", "http://www.example.com/test/a:path")]
[InlineData("http://www.example.com/", "a:test/path", "http://www.example.com/a:test/path")]
[InlineData("http://www.example.com/", "a:test", "http://www.example.com/a:test")]
[InlineData("http://www.example.com/z", "test/path", "http://www.example.com/test/path")]
[InlineData("http://www.example.com/z", "test/a:path", "http://www.example.com/test/a:path")]
[InlineData("http://www.example.com/z", "a:test/path", "http://www.example.com/a:test/path")]
[InlineData("http://www.example.com/z", "a:test", "http://www.example.com/a:test")]
[InlineData("http://www.example.com/z/", "test/path", "http://www.example.com/z/test/path")]
[InlineData("http://www.example.com/z/", "test/a:path", "http://www.example.com/z/test/a:path")]
[InlineData("http://www.example.com/z/", "a:test/path", "http://www.example.com/z/a:test/path")]
[InlineData("http://www.example.com/z/", "a:test", "http://www.example.com/z/a:test")]
[InlineData("http://www.example.com/z", "/test/path", "http://www.example.com/test/path")]
[InlineData("http://www.example.com/z", "/test/a:path", "http://www.example.com/test/a:path")]
[InlineData("http://www.example.com/z", "/a:test/path", "http://www.example.com/a:test/path")]
[InlineData("http://www.example.com/z", "/a:test", "http://www.example.com/a:test")]
[InlineData("http://www.example.com/z/", "/test/path", "http://www.example.com/test/path")]
[InlineData("http://www.example.com/z/", "/test/a:path", "http://www.example.com/test/a:path")]
[InlineData("http://www.example.com/z/", "/a:test/path", "http://www.example.com/a:test/path")]
[InlineData("http://www.example.com/z/", "/a:test", "http://www.example.com/a:test")]
[InlineData("http://www.example.com/z", "?abc", "http://www.example.com/z?abc")]
[InlineData("http://www.example.com/z", "#abc", "http://www.example.com/z#abc")]
[InlineData("http://www.example.com/z/", "?abc", "http://www.example.com/z/?abc")]
[InlineData("http://www.example.com/z/", "#abc", "http://www.example.com/z/#abc")]
public void TestBasePlusPath(string baseUri, string path, string expectedRequestUri)
{
var builder = new RequestBuilder()
{
BaseUri = new Uri(baseUri),
Path = path,
Method = "PUT"
};
var request = builder.CreateRequest();
Assert.Equal(HttpMethod.Put, request.Method);
// Verify both the URI and the string representation.
// Required because URI equality hides some special character processing.
Assert.Equal(new Uri(expectedRequestUri), request.RequestUri);
Assert.Equal(expectedRequestUri, request.RequestUri.AbsoluteUri);
}
/// <summary>Verifies that a single query parameter is correctly encoded in the request URI.</summary>
[Fact]
public void TestSingleQueryParameter()
{
var builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.example.com/"),
};
builder.AddParameter(RequestParameterType.Query, "testQueryParam", "testValue");
var request = builder.CreateRequest();
Assert.Equal(new Uri("http://www.example.com/?testQueryParam=testValue"), request.RequestUri);
}
/// <summary>Verifies that multiple query parameters are correctly encoded in the request URI.</summary>
[Fact]
public void TestMultipleQueryParameter()
{
var builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.example.com/"),
};
builder.AddParameter(RequestParameterType.Query, "testQueryParamA", "testValueA");
builder.AddParameter(RequestParameterType.Query, "testQueryParamB", "testValueB");
var request = builder.CreateRequest();
Assert.Equal(new Uri("http://www.example.com/?testQueryParamA=testValueA&testQueryParamB=testValueB"), request.RequestUri);
}
/// <summary>Verifies that query parameters are URL encoded.</summary>
[Fact]
public void TestQueryParameterWithUrlEncode()
{
var builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.example.com/"),
};
builder.AddParameter(RequestParameterType.Query, "test Query Param", "test %va/ue");
var request = builder.CreateRequest();
Assert.Equal(new Uri("http://www.example.com/?test%20Query%20Param=test%20%25va%2Fue"), request.RequestUri);
}
/// <summary>Verifies that repeatable query parameters are supported.</summary>
/// <remarks>
/// See Issue #211: http://code.google.com/p/google-api-dotnet-client/issues/detail?id=211
/// </remarks>
[Fact]
public void TestMultipleQueryParameters()
{
var builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.example.com/"),
};
builder.AddParameter(RequestParameterType.Query, "q", "value1");
builder.AddParameter(RequestParameterType.Query, "q", "value2");
var request = builder.CreateRequest();
Assert.Equal(new Uri("http://www.example.com/?q=value1&q=value2"), request.RequestUri);
}
/// <summary>Verifies that empty query parameters are not ignored.</summary>
[Fact]
public void TestNullQueryParameters()
{
var builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.example.com"),
Path = "",
};
builder.AddParameter(RequestParameterType.Query, "q", null);
builder.AddParameter(RequestParameterType.Query, "p", String.Empty);
Assert.Equal("http://www.example.com/?p", builder.BuildUri().AbsoluteUri);
}
/// <summary>Verifies that path parameters are properly inserted into the URI.</summary>
[Fact]
public void TestPathParameter()
{
var builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.example.com/"),
Path = "test/{id}/foo/bar",
};
builder.AddParameter(RequestParameterType.Path, "id", "value");
var request = builder.CreateRequest();
Assert.Equal(new Uri("http://www.example.com/test/value/foo/bar"), request.RequestUri);
}
/// <summary>A test for invalid path parameters.</summary>
[Fact]
public void TestInvalidPathParameters()
{
// A path parameter is missing.
var builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.example.com/"),
Path = "test/{id}/foo/bar",
};
Assert.Throws<ArgumentException>(() =>
{
builder.CreateRequest();
});
// Invalid number after ':' in path parameter.
builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.example.com/"),
Path = "test/{id:SHOULD_BE_NUMBER}/foo/bar",
};
builder.AddParameter(RequestParameterType.Path, "id", "hello");
Assert.Throws<ArgumentException>(() =>
{
builder.CreateRequest();
});
}
/// <summary>Verifies that path parameters are URL encoded.</summary>
[Theory]
[InlineData(" %va/ue", "http://www.example.com/test/%20%25va%2Fue")]
[InlineData("foo/bar/[baz] test.txt", "http://www.example.com/test/foo%2Fbar%2F%5Bbaz%5D%20test.txt")]
public void TestPathParameterWithUrlEncode(string idValue, string expectedRequestUri)
{
var builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.example.com/"),
Path = "test/{id}",
};
builder.AddParameter(RequestParameterType.Path, "id", idValue);
var request = builder.CreateRequest();
// Verify both the URI and the string representation.
// Required because URI equality hides some special character processing.
Assert.Equal(new Uri(expectedRequestUri), request.RequestUri);
Assert.Equal(expectedRequestUri, request.RequestUri.AbsoluteUri);
}
/// <summary>Tests a path parameter which contains '?' with query parameter.</summary>
[Fact]
public void TestQueryAndPathParameters()
{
var builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.test.com"),
Path = "colors{?list}"
};
builder.AddParameter(RequestParameterType.Path, "list", "red");
builder.AddParameter(RequestParameterType.Path, "list", "yellow");
builder.AddParameter(RequestParameterType.Query, "on", "1");
Assert.Equal("http://www.test.com/colors?list=red,yellow&on=1", builder.BuildUri().AbsoluteUri);
}
/// <summary>See Level 1 Examples on http://tools.ietf.org/html/rfc6570#section-1.2 (URI Template).</summary>
[Fact]
public void TestPathParameters_Level1()
{
IDictionary<string, IEnumerable<string>> vars = new Dictionary<string, IEnumerable<string>>();
vars["var"] = new List<string> { "value" };
vars["hello"] = new List<string> { "Hello World!" };
SubtestPathParameters(vars, "{var}", "value");
SubtestPathParameters(vars, "{hello}", "Hello%20World%21");
}
/// <summary>See Level 2 Examples on http://tools.ietf.org/html/rfc6570#section-1.2 (URI Template).</summary>
[Fact]
public void TestPathParameters_Level2()
{
IDictionary<string, IEnumerable<string>> vars = new Dictionary<string, IEnumerable<string>>();
vars["var"] = new List<string> { "value" };
vars["hello"] = new List<string> { "Hello World!" };
vars["path"] = new List<string> { "/foo/bar" };
SubtestPathParameters(vars, "{+var}", "value");
SubtestPathParameters(vars, "{+hello}", "Hello%20World!");
SubtestPathParameters(vars, "{+path}/here", "foo/bar/here");
SubtestPathParameters(vars, "here?ref={+path}", "here?ref=/foo/bar");
}
/// <summary>See Level 3 Examples on http://tools.ietf.org/html/rfc6570#section-1.2 (URI Template).</summary>
[Fact]
public void TestPathParameters_Level3()
{
IDictionary<string, IEnumerable<string>> vars = new Dictionary<string, IEnumerable<string>>();
vars["var"] = new List<string> { "value" };
vars["hello"] = new List<string> { "Hello World!" };
vars["empty"] = new List<string> { "" };
vars["path"] = new List<string> { "/foo/bar" };
vars["x"] = new List<string> { "1024" };
vars["y"] = new List<string> { "768" };
SubtestPathParameters(vars, "map?{x,y}", "map?1024,768");
SubtestPathParameters(vars, "{x,hello,y}", "1024,Hello%20World%21,768");
SubtestPathParameters(vars, "{+x,hello,y}", "1024,Hello%20World!,768");
SubtestPathParameters(vars, "{+path,x}/here", "foo/bar,1024/here");
SubtestPathParameters(vars, "{#x,hello,y}", "#1024,Hello%20World!,768");
SubtestPathParameters(vars, "{#path,x}/here", "#/foo/bar,1024/here");
SubtestPathParameters(vars, "X{.var}", "X.value");
SubtestPathParameters(vars, "X{.x,y}", "X.1024.768");
SubtestPathParameters(vars, "{/var}", "value");
SubtestPathParameters(vars, "{/var,x}/here", "value/1024/here");
SubtestPathParameters(vars, "{;x,y}", ";x=1024;y=768");
SubtestPathParameters(vars, "{;x,y,empty}", ";x=1024;y=768;empty");
SubtestPathParameters(vars, "{?x,y}", "?x=1024&y=768");
SubtestPathParameters(vars, "{?x,y,empty}", "?x=1024&y=768&empty=");
SubtestPathParameters(vars, "?fixed=yes{&x}", "?fixed=yes&x=1024");
SubtestPathParameters(vars, "{&x,y,empty}", "&x=1024&y=768&empty=");
}
/// <summary>See Level 4 Examples on http://tools.ietf.org/html/rfc6570#section-1.4 (URI Template).</summary>
[Fact]
public void TestPathParameters_Level4()
{
IDictionary<string, IEnumerable<string>> vars = new Dictionary<string, IEnumerable<string>>();
vars["var"] = new List<string> { "value" };
vars["hello"] = new List<string> { "Hello World!" };
vars["path"] = new List<string> { "/foo/bar" };
vars["list"] = new List<string> { "red", "green", "blue" };
SubtestPathParameters(vars, "{var:3}", "val");
SubtestPathParameters(vars, "{var:30}", "value");
SubtestPathParameters(vars, "{list}", "red,green,blue");
SubtestPathParameters(vars, "{list*}", "red,green,blue");
SubtestPathParameters(vars, "{+path:6}/here", "foo/b/here");
SubtestPathParameters(vars, "{+list}", "red,green,blue");
SubtestPathParameters(vars, "{+list*}", "red,green,blue");
SubtestPathParameters(vars, "{#path:6}/here", "#/foo/b/here");
SubtestPathParameters(vars, "{#list}", "#red,green,blue");
SubtestPathParameters(vars, "{#list*}", "#red,green,blue");
SubtestPathParameters(vars, "X{.var:3}", "X.val");
SubtestPathParameters(vars, "X{.list}", "X.red,green,blue");
SubtestPathParameters(vars, "X{.list*}", "X.red.green.blue");
SubtestPathParameters(vars, "{/var:1,var}", "v/value");
SubtestPathParameters(vars, "{/list}", "red,green,blue");
SubtestPathParameters(vars, "{/list*}", "red/green/blue");
SubtestPathParameters(vars, "{/list*,path:4}", "red/green/blue/%2Ffoo");
SubtestPathParameters(vars, "{;hello:5}", ";hello=Hello");
SubtestPathParameters(vars, "{;list}", ";list=red,green,blue");
SubtestPathParameters(vars, "{;list*}", ";list=red;list=green;list=blue");
SubtestPathParameters(vars, "{?var:3}", "?var=val");
SubtestPathParameters(vars, "{?list}", "?list=red,green,blue");
SubtestPathParameters(vars, "{?list*}", "?list=red&list=green&list=blue");
SubtestPathParameters(vars, "{&var:3}", "&var=val");
SubtestPathParameters(vars, "{&list}", "&list=red,green,blue");
SubtestPathParameters(vars, "{&list*}", "&list=red&list=green&list=blue");
}
/// <summary>A subtest for path parameters.</summary>
/// <param name="dic">Dictionary that contain all path parameters.</param>
/// <param name="path">Path part.</param>
/// <param name="expected">Expected part after base URI.</param>
private void SubtestPathParameters(IDictionary<string, IEnumerable<string>> dic, string path, string expected)
{
var builder = new RequestBuilder()
{
BaseUri = new Uri("http://www.example.com"),
Path = path,
};
foreach (var pair in dic)
{
foreach (var value in pair.Value)
{
builder.AddParameter(RequestParameterType.Path, pair.Key, value);
}
}
Assert.Equal("http://www.example.com/" + expected, builder.BuildUri().AbsoluteUri);
}
}
}
| {
"pile_set_name": "Github"
} |
%%% -*-mode:erlang;coding:utf-8;tab-width:4;c-basic-offset:4;indent-tabs-mode:()-*-
%%% ex: set ft=erlang fenc=utf-8 sts=4 ts=4 sw=4 et:
%%%
%%% Copyright 2015 Panagiotis Papadomitsos. All Rights Reserved.
%%%
-module(gen_rpc_helper).
-author("Panagiotis Papadomitsos <[email protected]>").
%%% Since a lot of these functions are simple
%%% let's inline them
-compile([inline]).
%%% Include this library's name macro
-include("app.hrl").
%%% Include helpful guard macros
-include("types.hrl").
%%% Public API
-export([peer_to_string/1,
socket_to_string/1,
host_from_node/1,
set_optimal_process_flags/0,
make_process_name/2,
is_driver_enabled/1,
merge_sockopt_lists/2,
get_server_driver_options/1,
get_client_config_per_node/1,
get_client_driver_options/1,
get_connect_timeout/0,
get_send_timeout/1,
get_rpc_module_control/0,
get_authentication_timeout/0,
get_call_receive_timeout/1,
get_sbcast_receive_timeout/0,
get_control_receive_timeout/0,
get_inactivity_timeout/1,
get_async_call_inactivity_timeout/0]).
%%% ===================================================
%%% Public API
%%% ===================================================
%% Return the connected peer's IP
-spec peer_to_string({inet:ip4_address(), inet:port_number()} | inet:ip4_address()) -> string().
peer_to_string({{A,B,C,D}, Port}) when is_integer(A), is_integer(B), is_integer(C), is_integer(D), is_integer(Port) ->
integer_to_list(A) ++ "." ++
integer_to_list(B) ++ "." ++
integer_to_list(C) ++ "." ++
integer_to_list(D) ++ ":" ++
integer_to_list(Port);
peer_to_string({A,B,C,D} = IpAddress) when is_integer(A), is_integer(B), is_integer(C), is_integer(D) ->
peer_to_string({IpAddress, 0}).
-spec socket_to_string(term()) -> string().
socket_to_string(Socket) when is_port(Socket) ->
io_lib:format("~p", [Socket]);
socket_to_string(Socket) when is_tuple(Socket) ->
case Socket of
{sslsocket, _, {TcpSock, _}} ->
io_lib:format("~p", [TcpSock]);
{sslsocket,{_, TcpSock, _, _}, _} ->
io_lib:format("~p", [TcpSock]);
_Else ->
ssl_socket
end.
%% Return the remote Erlang hostname
-spec host_from_node(node()) -> string().
host_from_node(Node) when is_atom(Node) ->
NodeStr = atom_to_list(Node),
[_Name, Host] = string:tokens(NodeStr, [$@]),
Host.
%% Set optimal process flags
-spec set_optimal_process_flags() -> ok.
set_optimal_process_flags() ->
_ = erlang:process_flag(trap_exit, true),
_ = erlang:process_flag(priority, high),
_ = erlang:process_flag(message_queue_data, off_heap),
ok.
%% Return an atom to identify gen_rpc processes
%%
-spec make_process_name(list(), {inet:ip4_address(), inet:port_number()} | node_or_tuple()) -> atom().
make_process_name("client", {Node,Key}) when is_atom(Node) ->
%% This function is going to be called enough to warrant a less pretty
%% process name in order to avoid calling costly functions
KeyStr = erlang:integer_to_list(erlang:phash2(Key)),
NodeStr = erlang:atom_to_list(Node),
erlang:list_to_atom("gen_rpc.client." ++ NodeStr ++ "/" ++ KeyStr);
make_process_name("client", Node) when is_atom(Node) ->
%% This function is going to be called enough to warrant a less pretty
%% process name in order to avoid calling costly functions
NodeStr = erlang:atom_to_list(Node),
erlang:list_to_atom("gen_rpc.client." ++ NodeStr);
make_process_name("server", Driver) when is_atom(Driver) ->
DriverStr = erlang:atom_to_list(Driver),
erlang:list_to_atom("gen_rpc_server_" ++ DriverStr);
make_process_name("acceptor", Peer) when is_tuple(Peer) ->
erlang:list_to_atom("gen_rpc.acceptor." ++ peer_to_string(Peer)).
%% Merge lists that contain both tuples and simple values observing
%% keys in proplists
-spec merge_sockopt_lists(list(), list()) -> list().
merge_sockopt_lists(List1, List2) ->
SList1 = lists:usort(fun hybrid_proplist_compare/2, List1),
SList2 = lists:usort(fun hybrid_proplist_compare/2, List2),
lists:umerge(fun hybrid_proplist_compare/2, SList1, SList2).
-spec is_driver_enabled(atom()) -> boolean().
is_driver_enabled(Driver) when is_atom(Driver) ->
DriverStr = erlang:atom_to_list(Driver),
Setting = erlang:list_to_atom(DriverStr ++ "_server_port"),
case application:get_env(?APP, Setting) of
{ok, false} ->
false;
{ok, _Port} ->
true
end.
-spec get_server_driver_options(atom()) -> tuple().
get_server_driver_options(Driver) when is_atom(Driver) ->
DriverStr = erlang:atom_to_list(Driver),
DriverMod = erlang:list_to_atom("gen_rpc_driver_" ++ DriverStr),
ClosedMsg = erlang:list_to_atom(DriverStr ++ "_closed"),
ErrorMsg = erlang:list_to_atom(DriverStr ++ "_error"),
PortSetting = erlang:list_to_atom(DriverStr ++ "_server_port"),
{ok, DriverPort} = application:get_env(?APP, PortSetting),
{DriverMod, DriverPort, ClosedMsg, ErrorMsg}.
-spec get_client_driver_options(atom()) -> tuple().
get_client_driver_options(Driver) when is_atom(Driver) ->
DriverStr = erlang:atom_to_list(Driver),
DriverMod = erlang:list_to_atom("gen_rpc_driver_" ++ DriverStr),
ClosedMsg = erlang:list_to_atom(DriverStr ++ "_closed"),
ErrorMsg = erlang:list_to_atom(DriverStr ++ "_error"),
{DriverMod, ClosedMsg, ErrorMsg}.
-spec get_client_config_per_node(node_or_tuple()) -> {atom(), inet:port_number()} | {error, {atom(), term()}}.
get_client_config_per_node({Node, _Key}) ->
get_client_config_per_node(Node);
get_client_config_per_node(Node) when is_atom(Node) ->
{ok, NodeConfig} = application:get_env(?APP, client_config_per_node),
case NodeConfig of
{external, Module} when is_atom(Module) ->
try Module:get_config(Node) of
{Driver, Port} when is_atom(Driver), is_integer(Port), Port > 0 ->
{Driver, Port};
{error, Reason} ->
{error, Reason}
catch
Class:Reason ->
{error, {Class,Reason}}
end;
{internal, NodeMap} ->
get_client_config_from_map(Node, NodeMap)
end.
-spec get_connect_timeout() -> timeout().
get_connect_timeout() ->
{ok, ConnTO} = application:get_env(?APP, connect_timeout),
ConnTO.
%% Merges user-defined call receive timeout values with app timeout values
-spec get_call_receive_timeout(undefined | timeout()) -> timeout().
get_call_receive_timeout(undefined) ->
{ok, RecvTO} = application:get_env(?APP, call_receive_timeout),
RecvTO;
get_call_receive_timeout(Else) ->
Else.
-spec get_rpc_module_control() -> {atom(), atom() | sets:set()}.
get_rpc_module_control() ->
case application:get_env(?APP, rpc_module_control) of
{ok, disabled} ->
{disabled, disabled};
{ok, Type} when Type =:= whitelist; Type =:= blacklist ->
{ok, List} = application:get_env(?APP, rpc_module_list),
{Type, sets:from_list(List)}
end.
%% Retrieves the default authentication timeout
-spec get_authentication_timeout() -> timeout().
get_authentication_timeout() ->
{ok, AuthTO} = application:get_env(?APP, authentication_timeout),
AuthTO.
%% Returns the default sbcast receive timeout
-spec get_sbcast_receive_timeout() -> timeout().
get_sbcast_receive_timeout() ->
{ok, RecvTO} = application:get_env(?APP, sbcast_receive_timeout),
RecvTO.
%% Returns the default dispatch receive timeout
-spec get_control_receive_timeout() -> timeout().
get_control_receive_timeout() ->
{ok, RecvTO} = application:get_env(?APP, control_receive_timeout),
RecvTO.
%% Merges user-defined send timeout values with app timeout values
-spec get_send_timeout(undefined | timeout()) -> timeout().
get_send_timeout(undefined) ->
{ok, SendTO} = application:get_env(?APP, send_timeout),
SendTO;
get_send_timeout(Else) ->
Else.
%% Returns default inactivity timeouts for different modules
-spec get_inactivity_timeout(gen_rpc_client | gen_rpc_acceptor) -> timeout().
get_inactivity_timeout(gen_rpc_client) ->
{ok, TTL} = application:get_env(?APP, client_inactivity_timeout),
TTL;
get_inactivity_timeout(gen_rpc_acceptor) ->
{ok, TTL} = application:get_env(?APP, server_inactivity_timeout),
TTL.
-spec get_async_call_inactivity_timeout() -> timeout().
get_async_call_inactivity_timeout() ->
{ok, TTL} = application:get_env(?APP, async_call_inactivity_timeout),
TTL.
%%% ===================================================
%%% Private functions
%%% ===================================================
get_client_config_from_map(Node, NodeConfig) ->
case maps:find(Node, NodeConfig) of
error ->
{ok, Driver} = application:get_env(?APP, default_client_driver),
DriverStr = erlang:atom_to_list(Driver),
PortSetting = erlang:list_to_atom(DriverStr ++ "_client_port"),
{ok, Port} = application:get_env(?APP, PortSetting),
{Driver, Port};
{ok, {Driver,Port}} ->
{Driver, Port};
{ok, Port} ->
{ok, Driver} = application:get_env(?APP, default_client_driver),
{Driver, Port}
end.
hybrid_proplist_compare({K1,_V1}, {K2,_V2}) ->
K1 =< K2;
hybrid_proplist_compare(K1, K2) ->
K1 =< K2.
| {
"pile_set_name": "Github"
} |
# Tenko parser autogenerated test case
- From: tests/testcases/assigns/to_keyword/autogen.md
- Path: tests/testcases/assigns/to_keyword/gen/should_listen_to_use_strict_directive_in_getter_wrapped/do.md
> :: assigns : to keyword : gen : should listen to use strict directive in getter wrapped
>
> ::> do
## Input
`````js
foo = {
get x(){
"use strict";
(do = x);
}
}
`````
## Output
_Note: the whole output block is auto-generated. Manual changes will be overwritten!_
Below follow outputs in five parsing modes: sloppy, sloppy+annexb, strict script, module, module+annexb.
Note that the output parts are auto-generated by the test runner to reflect actual result.
### Sloppy mode
Parsed with script goal and as if the code did not start with strict mode header.
`````
throws: Parser error!
Cannot use this name (`do`) as a variable name because: Cannot never use this reserved word as a variable name
start@1:0, error@4:5
╔══╦════════════════
1 ║ foo = {
2 ║ get x(){
3 ║ "use strict";
4 ║ (do = x);
║ ^^------- error
5 ║ }
6 ║ }
╚══╩════════════════
`````
### Strict mode
Parsed with script goal but as if it was starting with `"use strict"` at the top.
_Output same as sloppy mode._
### Module goal
Parsed with the module goal.
_Output same as sloppy mode._
### Sloppy mode with AnnexB
Parsed with script goal with AnnexB rules enabled and as if the code did not start with strict mode header.
_Output same as sloppy mode._
### Module goal with AnnexB
Parsed with the module goal with AnnexB rules enabled.
_Output same as sloppy mode._
| {
"pile_set_name": "Github"
} |
#include <iostream>
#include <string>
#include <liboauthcpp/liboauthcpp.h>
/* These are input settings that make this demo actually work -- you need to get
* these, e.g. by referring to the Twitter documentation and by registering an
* application with them. Here we have examples from Twitter. If you
* don't enter any, you'll be prompted to enter them at runtime.
*/
std::string consumer_key = ""; // Key from Twitter
std::string consumer_secret = ""; // Secret from Twitter
std::string request_token_url = "https://api.twitter.com/oauth/request_token";
std::string request_token_query_args = "oauth_callback=oob";
std::string authorize_url = "https://api.twitter.com/oauth/authorize";
std::string access_token_url = "https://api.twitter.com/oauth/access_token";
std::string getUserString(std::string prompt) {
std::cout << prompt << " ";
std::string res;
std::cin >> res;
std::cout << std::endl;
return res;
}
int main(int argc, char** argv) {
if (argc > 1 && std::string(argv[1]) == std::string("--debug"))
OAuth::SetLogLevel(OAuth::LogLevelDebug);
// Initialization
if (consumer_key.empty()) consumer_key = getUserString("Enter consumer key:");
if (consumer_secret.empty()) consumer_secret = getUserString("Enter consumer secret:");
OAuth::Consumer consumer(consumer_key, consumer_secret);
OAuth::Client oauth(&consumer);
// Step 1: Get a request token. This is a temporary token that is used for
// having the user authorize an access token and to sign the request to
// obtain said access token.
std::string base_request_token_url = request_token_url + (request_token_query_args.empty() ? std::string("") : (std::string("?")+request_token_query_args) );
std::string oAuthQueryString =
oauth.getURLQueryString( OAuth::Http::Get, base_request_token_url);
std::cout << "Enter the following in your browser to get the request token: " << std::endl;
// Note that getting the query string includes the arguments we
// passed in, so we don't need to include request_token_query_args
// again.
std::cout << request_token_url << "?" << oAuthQueryString << std::endl;
std::cout << std::endl;
// Extract the token and token_secret from the response
std::string request_token_resp = getUserString("Enter the response:");
// This time we pass the response directly and have the library do the
// parsing (see next extractToken call for alternative)
OAuth::Token request_token = OAuth::Token::extract( request_token_resp );
// Get access token and secret from OAuth object
std::cout << "Request Token:" << std::endl;
std::cout << " - oauth_token = " << request_token.key() << std::endl;
std::cout << " - oauth_token_secret = " << request_token.secret() << std::endl;
std::cout << std::endl;
// Step 2: Redirect to the provider. Since this is a CLI script we
// do not redirect. In a web application you would redirect the
// user to the URL below.
std::cout << "Go to the following link in your browser to authorize this application on a user's account:" << std::endl;
std::cout << authorize_url << "?oauth_token=" << request_token.key() << std::endl;
// After the user has granted access to you, the consumer, the
// provider will redirect you to whatever URL you have told them
// to redirect to. You can usually define this in the
// oauth_callback argument as well.
std::string pin = getUserString("What is the PIN?");
request_token.setPin(pin);
// Step 3: Once the consumer has redirected the user back to the
// oauth_callback URL you can request the access token the user
// has approved. You use the request token to sign this
// request. After this is done you throw away the request token
// and use the access token returned. You should store the oauth
// token and token secret somewhere safe, like a database, for
// future use.
oauth = OAuth::Client(&consumer, &request_token);
// Note that we explicitly specify an empty body here (it's a GET) so we can
// also specify to include the oauth_verifier parameter
oAuthQueryString = oauth.getURLQueryString( OAuth::Http::Get, access_token_url, std::string( "" ), true );
std::cout << "Enter the following in your browser to get the final access token & secret: " << std::endl;
std::cout << access_token_url << "?" << oAuthQueryString;
std::cout << std::endl;
// Once they've come back from the browser, extract the token and token_secret from the response
std::string access_token_resp = getUserString("Enter the response:");
// On this extractToken, we do the parsing ourselves (via the library) so we
// can extract additional keys that are sent back, in the case of twitter,
// the screen_name
OAuth::KeyValuePairs access_token_resp_data = OAuth::ParseKeyValuePairs(access_token_resp);
OAuth::Token access_token = OAuth::Token::extract( access_token_resp_data );
std::cout << "Access token:" << std::endl;
std::cout << " - oauth_token = " << access_token.key() << std::endl;
std::cout << " - oauth_token_secret = " << access_token.secret() << std::endl;
std::cout << std::endl;
std::cout << "You may now access protected resources using the access tokens above." << std::endl;
std::cout << std::endl;
std::pair<OAuth::KeyValuePairs::iterator, OAuth::KeyValuePairs::iterator> screen_name_its = access_token_resp_data.equal_range("screen_name");
for(OAuth::KeyValuePairs::iterator it = screen_name_its.first; it != screen_name_its.second; it++)
std::cout << "Also extracted screen name from access token response: " << it->second << std::endl;
// E.g., to use the access token, you'd create a new OAuth using
// it, discarding the request_token:
// oauth = OAuth::Client(&consumer, &access_token);
return 0;
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Ydg-fD-yQy"/>
<viewControllerLayoutGuide type="bottom" id="xbc-2k-c8Z"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
</imageView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
</constraints>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
<resources>
<image name="LaunchImage" width="168" height="185"/>
</resources>
</document>
| {
"pile_set_name": "Github"
} |
// ***************************************************************************
// *
// * Copyright (C) 2010 International Business Machines
// * Corporation and others. All Rights Reserved.
// * Tool: com.ibm.icu.dev.tool.cldr.LDML2ICUConverter.java
// * Source File:<path>/common/main/zh_TW.xml
// *
// ***************************************************************************
zh_Hant_TW{
/**
* empty target resource
*/
___{""}
}
| {
"pile_set_name": "Github"
} |
#!/usr/local/ActiveTcl/bin/tclsh
# ----------------------------------------------------------------- #
# The HMM-Based Speech Synthesis System (HTS) #
# developed by HTS Working Group #
# http://hts.sp.nitech.ac.jp/ #
# ----------------------------------------------------------------- #
# #
# Copyright (c) 2001-2008 Nagoya Institute of Technology #
# Department of Computer Science #
# #
# 2001-2008 Tokyo Institute of Technology #
# Interdisciplinary Graduate School of #
# Science and Engineering #
# #
# 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 the HTS working group 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. #
# ----------------------------------------------------------------- #
#
# This program is based on the program getf0.tcl
# Created by Shinji SAKO Mon Sep 1 18:54:35 JST 2003
# Modified by Heiga ZEN Fri Nov 3 17:28:33 JST 2006
#
# get_mag.tcl : Fourier magnitudes extraction script using snack.
# It has as input the raw signal and its residual signal obtained by
# inverse filtering.
# The residual signal can be generated with SPTK, using inverse filtering, ex:
# x2x +sf tmp.raw | frame +f -p 80 | window -w 1 -n 1 | gcep -g 2 -m 24 > tmp.gcep
# x2x +sf tmp.raw | iglsadf -k -g 2 -m 24 -p 80 tmp.gcep > tmp.residual
#
# Created by Marcela Charfuelan (DFKI) Wed Jun 25 11:00:22 CEST 2008
#
# use:
# tclsh get_mag.tcl -l -H 280 -L 40 -p 80 -r 16000 tmp.raw tmp.residual
package require snack
set method ESPS
set maxpitch 400
set minpitch 60
set numharmonics 10
set framelength 0.005
set frameperiod 80
set samplerate 16000
set encoding Lin16
set endian bigEndian
set outputmode 0
set targetfile ""
set residualfile ""
set outputfile ""
set arg_index $argc
set i 0
set j 0
set help [ format "\nFourier magnitudes extraction script using snack library \nUsage %s \[-H max_f0\] \[-L min_f0\] \[-m number_of_harmonics (default 10=MAGORDER)\] \[-s frame_length (in second)\] \[-p frame_length (in point)\] \[-r samplerate\] \[-l (little endian)\] \[-b (big endian)\] \[-o output_file\] input_speechfile(raw/wav) input_residualfile\n" $argv0 ]
while { $i < $arg_index } {
switch -exact -- [ lindex $argv $i ] {
-H {
incr i
set maxpitch [ lindex $argv $i ]
}
-L {
incr i
set minpitch [ lindex $argv $i ]
}
-m {
incr i
set numharmonics [ lindex $argv $i ]
}
-s {
incr i
set framelength [ lindex $argv $i ]
}
-p {
incr i
set frameperiod [ lindex $argv $i ]
set j 1
}
-o {
incr i
set outputfile [ lindex $argv $i ]
}
-r {
incr i
set samplerate [ lindex $argv $i ]
}
-l {
set endian littleEndian
}
-b {
set endian bigEndian
}
-h {
puts stderr $help
exit 1
}
default {
set targetfile [ lindex $argv $i ]
incr i
set residualfile [ lindex $argv $i ]
}
}
incr i
}
# framelength
if { $j == 1 } {
set framelength [expr {double($frameperiod) / $samplerate}]
}
# if input file does not exist, exit program
if { $targetfile == "" || $residualfile == ""} {
puts stderr $help
exit 0
}
# the original speech signal
snack::sound s
# the residual signal
snack::sound e
# if input file is WAVE (RIFF) format, read it
if { [file isfile $targetfile ] && "[file extension $targetfile]" == ".wav"} {
s read $targetfile
} else {
s read $targetfile -fileformat RAW -rate $samplerate -encoding $encoding -byteorder $endian
}
# read residual, in HTS scripts this is created by SPTK so it contains float values
e read $residualfile -fileformat RAW -rate $samplerate -encoding "float" -byteorder $endian
# if output filename (-o option) is not specified, output result to stdout
set fd stdout
# if output filename is specified, save result to that file
if { $outputfile != "" } then {
set fd [ open $outputfile w ]
}
# extract f0
set tmp [s pitch -method $method -maxpitch $maxpitch -minpitch $minpitch -framelength $framelength]
# n is the index number for a sample
set e_length [e length]
set fftlength 512
set windowlength 400
set sample_start 0
set sample_end 0
set n 0;
# for each frame in f0
foreach line $tmp {
set pitch [lindex $line 0]
# the pitch value returned by snack is in Hz, so here is put in samples
if { $pitch > 0.0 } then {
set f0 [expr $samplerate/$pitch]
set bin_width [expr $fftlength/$f0]
} else {
set f0 0
set bin_width 0
}
# take a window of the residual signal and get its FFT or power spectrum
set sample_start [expr $n *$frameperiod]
set sample_end [expr ($sample_start + $windowlength)-1]
if { $bin_width > 0.0 && $sample_end <= $e_length } then {
# this function computes the FFT power spectrum and returns a list of magnitude values (sqrt(r^2+i^2))
set f [e powerSpectrum -start $sample_start -end $sample_end -windowlength $windowlength -fftlength $fftlength]
set bin [expr round($bin_width)]
set half_bin [expr round($bin_width/2)]
set sumavg 0
set k 1
while { $k <= $numharmonics } {
set ival [expr ($k * $bin_width) - ($bin_width/2) + 1 ]
# -1 because lindex starts in zero
set i [expr round($ival) - 1]
set j [expr $i + $bin ]
# search for the max val in the interval e[i:j] and keep the index
set max_harm [lindex $f $i]
set imax_harm $i
incr i
while { $i <= $j } {
if { [lindex $f $i] > $max_harm } then {
set max_harm [lindex $f $i]
set imax_harm $i
}
incr i
}
set harm($k) $max_harm
# keep a sum for averaging and normalisation
set sumavg [expr $sumavg + ($max_harm * $max_harm)]
incr k
}
# normalise the Fourier magnitudes by the average
set alpha [expr sqrt($sumavg/$numharmonics)]
set k 1
while { $k <= $numharmonics } {
set harm($k) [expr ($harm($k) / $alpha)]
puts "$harm($k)"
incr k
}
} else {
# so it is a non-voiced frame, so the Fourier magnitudes here are set to 1???
# or maybe I should take the first 10 Fourier magnitudes of the window frame ???
set k 1
while { $k <= $numharmonics } {
puts 1
incr k
}
}
incr n
}
exit
| {
"pile_set_name": "Github"
} |
/*
Copyright 2015 The Kubernetes 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.
*/
package test
import (
"fmt"
"reflect"
"strconv"
"strings"
"testing"
"time"
apitesting "k8s.io/apimachinery/pkg/api/testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/apis/testapigroup"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
)
func TestDecodeUnstructured(t *testing.T) {
groupVersionString := "v1"
rawJson := fmt.Sprintf(`{"kind":"Pod","apiVersion":"%s","metadata":{"name":"test"}}`, groupVersionString)
pl := &List{
Items: []runtime.Object{
&testapigroup.Carp{ObjectMeta: metav1.ObjectMeta{Name: "1"}},
&runtime.Unknown{
TypeMeta: runtime.TypeMeta{Kind: "Pod", APIVersion: groupVersionString},
Raw: []byte(rawJson),
ContentType: runtime.ContentTypeJSON,
},
&runtime.Unknown{
TypeMeta: runtime.TypeMeta{Kind: "", APIVersion: groupVersionString},
Raw: []byte(rawJson),
ContentType: runtime.ContentTypeJSON,
},
&unstructured.Unstructured{
Object: map[string]interface{}{
"kind": "Foo",
"apiVersion": "Bar",
"test": "value",
},
},
},
}
if errs := runtime.DecodeList(pl.Items, unstructured.UnstructuredJSONScheme); len(errs) == 1 {
t.Fatalf("unexpected error %v", errs)
}
if pod, ok := pl.Items[1].(*unstructured.Unstructured); !ok || pod.Object["kind"] != "Pod" || pod.Object["metadata"].(map[string]interface{})["name"] != "test" {
t.Errorf("object not converted: %#v", pl.Items[1])
}
if pod, ok := pl.Items[2].(*unstructured.Unstructured); !ok || pod.Object["kind"] != "Pod" || pod.Object["metadata"].(map[string]interface{})["name"] != "test" {
t.Errorf("object not converted: %#v", pl.Items[2])
}
}
func TestDecode(t *testing.T) {
tcs := []struct {
json []byte
want runtime.Object
}{
{
json: []byte(`{"apiVersion": "test", "kind": "test_kind"}`),
want: &unstructured.Unstructured{
Object: map[string]interface{}{"apiVersion": "test", "kind": "test_kind"},
},
},
{
json: []byte(`{"apiVersion": "test", "kind": "test_list", "items": []}`),
want: &unstructured.UnstructuredList{
Object: map[string]interface{}{"apiVersion": "test", "kind": "test_list"},
Items: []unstructured.Unstructured{},
},
},
{
json: []byte(`{"items": [{"metadata": {"name": "object1", "deletionGracePeriodSeconds": 10}, "apiVersion": "test", "kind": "test_kind"}, {"metadata": {"name": "object2"}, "apiVersion": "test", "kind": "test_kind"}], "apiVersion": "test", "kind": "test_list"}`),
want: &unstructured.UnstructuredList{
Object: map[string]interface{}{"apiVersion": "test", "kind": "test_list"},
Items: []unstructured.Unstructured{
{
Object: map[string]interface{}{
"metadata": map[string]interface{}{"name": "object1", "deletionGracePeriodSeconds": int64(10)},
"apiVersion": "test",
"kind": "test_kind",
},
},
{
Object: map[string]interface{}{
"metadata": map[string]interface{}{"name": "object2"},
"apiVersion": "test",
"kind": "test_kind",
},
},
},
},
},
}
for _, tc := range tcs {
got, _, err := unstructured.UnstructuredJSONScheme.Decode(tc.json, nil, nil)
if err != nil {
t.Errorf("Unexpected error for %q: %v", string(tc.json), err)
continue
}
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("Decode(%q) want: %v\ngot: %v", string(tc.json), tc.want, got)
}
}
}
func TestUnstructuredGetters(t *testing.T) {
trueVar := true
ten := int64(10)
unstruct := unstructured.Unstructured{
Object: map[string]interface{}{
"kind": "test_kind",
"apiVersion": "test_version",
"metadata": map[string]interface{}{
"name": "test_name",
"namespace": "test_namespace",
"generateName": "test_generateName",
"uid": "test_uid",
"resourceVersion": "test_resourceVersion",
"generation": ten,
"deletionGracePeriodSeconds": ten,
"selfLink": "test_selfLink",
"creationTimestamp": "2009-11-10T23:00:00Z",
"deletionTimestamp": "2010-11-10T23:00:00Z",
"labels": map[string]interface{}{
"test_label": "test_value",
},
"annotations": map[string]interface{}{
"test_annotation": "test_value",
},
"ownerReferences": []interface{}{
map[string]interface{}{
"kind": "Pod",
"name": "poda",
"apiVersion": "v1",
"uid": "1",
},
map[string]interface{}{
"kind": "Pod",
"name": "podb",
"apiVersion": "v1",
"uid": "2",
// though these fields are of type *bool, but when
// decoded from JSON, they are unmarshalled as bool.
"controller": true,
"blockOwnerDeletion": true,
},
},
"finalizers": []interface{}{
"finalizer.1",
"finalizer.2",
},
"clusterName": "cluster123",
},
},
}
if got, want := unstruct.GetAPIVersion(), "test_version"; got != want {
t.Errorf("GetAPIVersions() = %s, want %s", got, want)
}
if got, want := unstruct.GetKind(), "test_kind"; got != want {
t.Errorf("GetKind() = %s, want %s", got, want)
}
if got, want := unstruct.GetNamespace(), "test_namespace"; got != want {
t.Errorf("GetNamespace() = %s, want %s", got, want)
}
if got, want := unstruct.GetName(), "test_name"; got != want {
t.Errorf("GetName() = %s, want %s", got, want)
}
if got, want := unstruct.GetGenerateName(), "test_generateName"; got != want {
t.Errorf("GetGenerateName() = %s, want %s", got, want)
}
if got, want := unstruct.GetUID(), types.UID("test_uid"); got != want {
t.Errorf("GetUID() = %s, want %s", got, want)
}
if got, want := unstruct.GetResourceVersion(), "test_resourceVersion"; got != want {
t.Errorf("GetResourceVersion() = %s, want %s", got, want)
}
if got, want := unstruct.GetSelfLink(), "test_selfLink"; got != want {
t.Errorf("GetSelfLink() = %s, want %s", got, want)
}
if got, want := unstruct.GetCreationTimestamp(), metav1.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC); !got.Equal(&want) {
t.Errorf("GetCreationTimestamp() = %s, want %s", got, want)
}
if got, want := unstruct.GetDeletionTimestamp(), metav1.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC); got == nil || !got.Equal(&want) {
t.Errorf("GetDeletionTimestamp() = %s, want %s", got, want)
}
if got, want := unstruct.GetLabels(), map[string]string{"test_label": "test_value"}; !reflect.DeepEqual(got, want) {
t.Errorf("GetLabels() = %s, want %s", got, want)
}
if got, want := unstruct.GetAnnotations(), map[string]string{"test_annotation": "test_value"}; !reflect.DeepEqual(got, want) {
t.Errorf("GetAnnotations() = %s, want %s", got, want)
}
refs := unstruct.GetOwnerReferences()
expectedOwnerReferences := []metav1.OwnerReference{
{
Kind: "Pod",
Name: "poda",
APIVersion: "v1",
UID: "1",
},
{
Kind: "Pod",
Name: "podb",
APIVersion: "v1",
UID: "2",
Controller: &trueVar,
BlockOwnerDeletion: &trueVar,
},
}
if got, want := refs, expectedOwnerReferences; !reflect.DeepEqual(got, want) {
t.Errorf("GetOwnerReferences()=%v, want %v", got, want)
}
if got, want := unstruct.GetFinalizers(), []string{"finalizer.1", "finalizer.2"}; !reflect.DeepEqual(got, want) {
t.Errorf("GetFinalizers()=%v, want %v", got, want)
}
if got, want := unstruct.GetClusterName(), "cluster123"; got != want {
t.Errorf("GetClusterName()=%v, want %v", got, want)
}
if got, want := unstruct.GetDeletionGracePeriodSeconds(), &ten; !reflect.DeepEqual(got, want) {
t.Errorf("GetDeletionGracePeriodSeconds()=%v, want %v", got, want)
}
if got, want := unstruct.GetGeneration(), ten; !reflect.DeepEqual(got, want) {
t.Errorf("GetGeneration()=%v, want %v", got, want)
}
}
func TestUnstructuredSetters(t *testing.T) {
unstruct := unstructured.Unstructured{}
trueVar := true
ten := int64(10)
want := unstructured.Unstructured{
Object: map[string]interface{}{
"kind": "test_kind",
"apiVersion": "test_version",
"metadata": map[string]interface{}{
"name": "test_name",
"namespace": "test_namespace",
"generateName": "test_generateName",
"uid": "test_uid",
"resourceVersion": "test_resourceVersion",
"selfLink": "test_selfLink",
"creationTimestamp": "2009-11-10T23:00:00Z",
"deletionTimestamp": "2010-11-10T23:00:00Z",
"deletionGracePeriodSeconds": ten,
"generation": ten,
"labels": map[string]interface{}{
"test_label": "test_value",
},
"annotations": map[string]interface{}{
"test_annotation": "test_value",
},
"ownerReferences": []interface{}{
map[string]interface{}{
"kind": "Pod",
"name": "poda",
"apiVersion": "v1",
"uid": "1",
},
map[string]interface{}{
"kind": "Pod",
"name": "podb",
"apiVersion": "v1",
"uid": "2",
"controller": true,
"blockOwnerDeletion": true,
},
},
"finalizers": []interface{}{
"finalizer.1",
"finalizer.2",
},
"clusterName": "cluster123",
},
},
}
unstruct.SetAPIVersion("test_version")
unstruct.SetKind("test_kind")
unstruct.SetNamespace("test_namespace")
unstruct.SetName("test_name")
unstruct.SetGenerateName("test_generateName")
unstruct.SetUID(types.UID("test_uid"))
unstruct.SetResourceVersion("test_resourceVersion")
unstruct.SetSelfLink("test_selfLink")
unstruct.SetCreationTimestamp(metav1.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC))
date := metav1.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC)
unstruct.SetDeletionTimestamp(&date)
unstruct.SetLabels(map[string]string{"test_label": "test_value"})
unstruct.SetAnnotations(map[string]string{"test_annotation": "test_value"})
newOwnerReferences := []metav1.OwnerReference{
{
Kind: "Pod",
Name: "poda",
APIVersion: "v1",
UID: "1",
},
{
Kind: "Pod",
Name: "podb",
APIVersion: "v1",
UID: "2",
Controller: &trueVar,
BlockOwnerDeletion: &trueVar,
},
}
unstruct.SetOwnerReferences(newOwnerReferences)
unstruct.SetFinalizers([]string{"finalizer.1", "finalizer.2"})
unstruct.SetClusterName("cluster123")
unstruct.SetDeletionGracePeriodSeconds(&ten)
unstruct.SetGeneration(ten)
if !reflect.DeepEqual(unstruct, want) {
t.Errorf("Wanted: \n%s\n Got:\n%s", want, unstruct)
}
}
func TestOwnerReferences(t *testing.T) {
t.Parallel()
trueVar := true
falseVar := false
refs := []metav1.OwnerReference{
{
APIVersion: "v2",
Kind: "K2",
Name: "n2",
UID: types.UID("abc1"),
},
{
APIVersion: "v1",
Kind: "K1",
Name: "n1",
UID: types.UID("abc2"),
Controller: &trueVar,
BlockOwnerDeletion: &falseVar,
},
{
APIVersion: "v3",
Kind: "K3",
Name: "n3",
UID: types.UID("abc3"),
Controller: &falseVar,
BlockOwnerDeletion: &trueVar,
},
}
for i, ref := range refs {
ref := ref
t.Run(strconv.Itoa(i), func(t *testing.T) {
t.Parallel()
u1 := unstructured.Unstructured{
Object: make(map[string]interface{}),
}
refsX := []metav1.OwnerReference{ref}
u1.SetOwnerReferences(refsX)
have := u1.GetOwnerReferences()
if !reflect.DeepEqual(have, refsX) {
t.Errorf("Object references are not the same: %#v != %#v", have, refsX)
}
})
}
}
func TestUnstructuredListGetters(t *testing.T) {
unstruct := unstructured.UnstructuredList{
Object: map[string]interface{}{
"kind": "test_kind",
"apiVersion": "test_version",
"metadata": map[string]interface{}{
"resourceVersion": "test_resourceVersion",
"selfLink": "test_selfLink",
},
},
}
if got, want := unstruct.GetAPIVersion(), "test_version"; got != want {
t.Errorf("GetAPIVersions() = %s, want %s", got, want)
}
if got, want := unstruct.GetKind(), "test_kind"; got != want {
t.Errorf("GetKind() = %s, want %s", got, want)
}
if got, want := unstruct.GetResourceVersion(), "test_resourceVersion"; got != want {
t.Errorf("GetResourceVersion() = %s, want %s", got, want)
}
if got, want := unstruct.GetSelfLink(), "test_selfLink"; got != want {
t.Errorf("GetSelfLink() = %s, want %s", got, want)
}
}
func TestUnstructuredListSetters(t *testing.T) {
unstruct := unstructured.UnstructuredList{}
want := unstructured.UnstructuredList{
Object: map[string]interface{}{
"kind": "test_kind",
"apiVersion": "test_version",
"metadata": map[string]interface{}{
"resourceVersion": "test_resourceVersion",
"selfLink": "test_selfLink",
},
},
}
unstruct.SetAPIVersion("test_version")
unstruct.SetKind("test_kind")
unstruct.SetResourceVersion("test_resourceVersion")
unstruct.SetSelfLink("test_selfLink")
if !reflect.DeepEqual(unstruct, want) {
t.Errorf("Wanted: \n%s\n Got:\n%s", unstruct, want)
}
}
func TestDecodeNumbers(t *testing.T) {
// Start with a valid pod
originalJSON := []byte(`{
"kind":"Carp",
"apiVersion":"v1",
"metadata":{"name":"pod","namespace":"foo"},
"spec":{
"containers":[{"name":"container","image":"container"}],
"activeDeadlineSeconds":1000030003
}
}`)
pod := &testapigroup.Carp{}
_, codecs := TestScheme()
codec := apitesting.TestCodec(codecs, schema.GroupVersion{Group: "", Version: runtime.APIVersionInternal})
err := runtime.DecodeInto(codec, originalJSON, pod)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Round-trip with unstructured codec
unstructuredObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, originalJSON)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
roundtripJSON, err := runtime.Encode(unstructured.UnstructuredJSONScheme, unstructuredObj)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Make sure we serialize back out in int form
if !strings.Contains(string(roundtripJSON), `"activeDeadlineSeconds":1000030003`) {
t.Errorf("Expected %s, got %s", `"activeDeadlineSeconds":1000030003`, string(roundtripJSON))
}
// Decode with structured codec again
obj2, err := runtime.Decode(codec, roundtripJSON)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// ensure pod is still valid
pod2, ok := obj2.(*testapigroup.Carp)
if !ok {
t.Fatalf("expected an *api.Pod, got %#v", obj2)
}
// ensure round-trip preserved large integers
if !reflect.DeepEqual(pod, pod2) {
t.Fatalf("Expected\n\t%#v, got \n\t%#v", pod, pod2)
}
}
// TestAccessorMethods does opaque roundtrip testing against an Unstructured
// instance's Object methods to ensure that what is "Set" matches what you
// subsequently "Get" without any assertions against internal state.
func TestAccessorMethods(t *testing.T) {
int64p := func(i int) *int64 {
v := int64(i)
return &v
}
tests := []struct {
accessor string
val interface{}
nilVal reflect.Value
}{
{accessor: "Namespace", val: "foo"},
{accessor: "Name", val: "bar"},
{accessor: "GenerateName", val: "baz"},
{accessor: "UID", val: types.UID("uid")},
{accessor: "ResourceVersion", val: "1"},
{accessor: "Generation", val: int64(5)},
{accessor: "SelfLink", val: "/foo"},
// TODO: Handle timestamps, which are being marshalled as UTC and
// unmarshalled as Local.
// https://github.com/kubernetes/kubernetes/issues/21402
// {accessor: "CreationTimestamp", val: someTime},
// {accessor: "DeletionTimestamp", val: someTimeP},
{accessor: "DeletionTimestamp", nilVal: reflect.ValueOf((*metav1.Time)(nil))},
{accessor: "DeletionGracePeriodSeconds", val: int64p(10)},
{accessor: "DeletionGracePeriodSeconds", val: int64p(0)},
{accessor: "DeletionGracePeriodSeconds", nilVal: reflect.ValueOf((*int64)(nil))},
{accessor: "Labels", val: map[string]string{"foo": "bar"}},
{accessor: "Annotations", val: map[string]string{"foo": "bar"}},
{accessor: "Initializers", val: &metav1.Initializers{Pending: []metav1.Initializer{{Name: "foo"}}}},
{accessor: "Initializers", val: &metav1.Initializers{}},
{accessor: "Initializers", nilVal: reflect.ValueOf((*metav1.Initializers)(nil))},
{accessor: "Finalizers", val: []string{"foo"}},
{accessor: "OwnerReferences", val: []metav1.OwnerReference{{Name: "foo"}}},
{accessor: "ClusterName", val: "foo"},
}
for i, test := range tests {
t.Logf("evaluating test %d (%s)", i, test.accessor)
u := &unstructured.Unstructured{}
setter := reflect.ValueOf(u).MethodByName("Set" + test.accessor)
getter := reflect.ValueOf(u).MethodByName("Get" + test.accessor)
args := []reflect.Value{}
if test.val != nil {
args = append(args, reflect.ValueOf(test.val))
} else {
args = append(args, test.nilVal)
}
setter.Call(args)
ret := getter.Call([]reflect.Value{})
actual := ret[0].Interface()
var expected interface{}
if test.val != nil {
expected = test.val
} else {
expected = test.nilVal.Interface()
}
if e, a := expected, actual; !reflect.DeepEqual(e, a) {
t.Fatalf("%s: expected %v (%T), got %v (%T)", test.accessor, e, e, a, a)
}
}
}
| {
"pile_set_name": "Github"
} |
package com.github.megatronking.svg.iconlibs;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import com.github.megatronking.svg.support.SVGRenderer;
/**
* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* SVG-Generator. It should not be modified by hand.
*/
public class ic_border_top extends SVGRenderer {
public ic_border_top(Context context) {
super(context);
mAlpha = 1.0f;
mWidth = dip2px(24.0f);
mHeight = dip2px(24.0f);
}
@Override
public void render(Canvas canvas, int w, int h, ColorFilter filter) {
final float scaleX = w / 24.0f;
final float scaleY = h / 24.0f;
mPath.reset();
mRenderPath.reset();
mFinalPathMatrix.setValues(new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f});
mFinalPathMatrix.postScale(scaleX, scaleY);
mPath.moveTo(7.0f, 21.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.lineTo(7.0f, 19.0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(7.0f, 21.0f);
mPath.rMoveTo(0.0f, -8.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.lineTo(7.0f, 11.0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(7.0f, 13.0f);
mPath.rMoveTo(4.0f, 0.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.rLineTo(-2.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(11.0f, 13.0f);
mPath.rMoveTo(0.0f, 8.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.rLineTo(-2.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(11.0f, 21.0f);
mPath.rMoveTo(-8.0f, -4.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.lineTo(3.0f, 15.0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(3.0f, 17.0f);
mPath.rMoveTo(0.0f, 4.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.lineTo(3.0f, 19.0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(3.0f, 21.0f);
mPath.rMoveTo(0.0f, -8.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.lineTo(3.0f, 11.0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(3.0f, 13.0f);
mPath.rMoveTo(0.0f, -4.0f);
mPath.rLineTo(2.0f, 0f);
mPath.lineTo(5.0f, 7.0f);
mPath.lineTo(3.0f, 7.0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(3.0f, 9.0f);
mPath.rMoveTo(8.0f, 8.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.rLineTo(-2.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(11.0f, 17.0f);
mPath.rMoveTo(8.0f, -8.0f);
mPath.rLineTo(2.0f, 0f);
mPath.lineTo(21.0f, 7.0f);
mPath.rLineTo(-2.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(19.0f, 9.0f);
mPath.rMoveTo(0.0f, 4.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.rLineTo(-2.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(19.0f, 13.0f);
mPath.moveTo(3.0f, 3.0f);
mPath.rLineTo(0f, 2.0f);
mPath.rLineTo(18.0f, 0f);
mPath.lineTo(21.0f, 3.0f);
mPath.lineTo(3.0f, 3.0f);
mPath.close();
mPath.moveTo(3.0f, 3.0f);
mPath.rMoveTo(16.0f, 14.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.rLineTo(-2.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(19.0f, 17.0f);
mPath.rMoveTo(-4.0f, 4.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.rLineTo(-2.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(15.0f, 21.0f);
mPath.moveTo(11.0f, 9.0f);
mPath.rLineTo(2.0f, 0f);
mPath.lineTo(13.0f, 7.0f);
mPath.rLineTo(-2.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(11.0f, 9.0f);
mPath.rMoveTo(8.0f, 12.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.rLineTo(-2.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(19.0f, 21.0f);
mPath.rMoveTo(-4.0f, -8.0f);
mPath.rLineTo(2.0f, 0f);
mPath.rLineTo(0f, -2.0f);
mPath.rLineTo(-2.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.close();
mPath.moveTo(15.0f, 13.0f);
mRenderPath.addPath(mPath, mFinalPathMatrix);
if (mFillPaint == null) {
mFillPaint = new Paint();
mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setAntiAlias(true);
}
mFillPaint.setColor(applyAlpha(-16777216, 1.0f));
mFillPaint.setColorFilter(filter);
canvas.drawPath(mRenderPath, mFillPaint);
}
} | {
"pile_set_name": "Github"
} |
// license:BSD-3-Clause
// copyright-holders:Mike Harris, Aaron Giles
/***************************************************************************
Namco 51XX
This custom chip is a Fujitsu MB8843 MCU programmed to act as an I/O
device with built-in coin management. It is also apparently used as a
protection device. It keeps track of the players scores, and checks
if a high score has been obtained or bonus lives should be awarded.
The main CPU has a range of commands to increment/decrement the score
by various fixed amounts.
The device is used to its full potential only by Bosconian; Xevious
uses it too, but only to do a protection check on startup.
CMD = command from main CPU
ANS = answer to main CPU
The chip reads/writes the I/O ports when the /IRQ is pulled down.
Pin 41 determines whether a read or write should happen (1=R, 0=W).
+------+
EX|1 42|Vcc
X|2 41|K3
/RESET|3 40|K2
/IRQ|4 39|K1
SO|5 38|K0
SI|6 37|R15
/SC /TO|7 36|R14
/TC|8 35|R13
P0|9 34|R12
P1|10 33|R11
P2|11 32|R10
P3|12 31|R9
O0|13 30|R8
O1|14 29|R7
O2|15 28|R6
O3|16 27|R5
O4|17 26|R4
O5|18 25|R3
O6|19 24|R2
O7|20 23|R1
GND|21 22|R0
+------+
commands:
00: nop
01 + 4 arguments: set coinage (xevious, possibly because of a bug, is different)
02: go in "credit" mode and enable start buttons
03: disable joystick remapping
04: enable joystick remapping
05: go in "switch" mode
06: nop
07: nop
***************************************************************************/
#include "emu.h"
#include "namco51.h"
#include "screen.h"
WRITE_LINE_MEMBER( namco_51xx_device::reset )
{
// Reset line is active low.
m_cpu->set_input_line(INPUT_LINE_RESET, !state);
}
WRITE_LINE_MEMBER( namco_51xx_device::vblank )
{
// The timer is active on falling edges.
m_cpu->clock_w(!state);
}
WRITE_LINE_MEMBER(namco_51xx_device::rw)
{
machine().scheduler().synchronize(timer_expired_delegate(FUNC(namco_51xx_device::rw_sync),this), state);
}
TIMER_CALLBACK_MEMBER( namco_51xx_device::rw_sync )
{
m_rw = param;
}
WRITE_LINE_MEMBER( namco_51xx_device::chip_select )
{
m_cpu->set_input_line(0, state);
}
uint8_t namco_51xx_device::read()
{
return m_portO;
}
void namco_51xx_device::write(uint8_t data)
{
machine().scheduler().synchronize(timer_expired_delegate(FUNC(namco_51xx_device::write_sync),this), data);
}
TIMER_CALLBACK_MEMBER( namco_51xx_device::write_sync )
{
m_portO = param;
}
uint8_t namco_51xx_device::K_r()
{
return (m_rw << 3) | (m_portO & 0x07);
}
uint8_t namco_51xx_device::R0_r()
{
return m_in[0]();
}
uint8_t namco_51xx_device::R1_r()
{
return m_in[1]();
}
uint8_t namco_51xx_device::R2_r()
{
return m_in[2]();
}
uint8_t namco_51xx_device::R3_r()
{
return m_in[3]();
}
void namco_51xx_device::O_w(uint8_t data)
{
uint8_t out = (data & 0x0f);
if (data & 0x10)
m_portO = (m_portO & 0x0f) | (out << 4);
else
m_portO = (m_portO & 0xf0) | (out);
}
void namco_51xx_device::P_w(uint8_t data)
{
m_out(data);
}
/***************************************************************************
DEVICE INTERFACE
***************************************************************************/
ROM_START( namco_51xx )
ROM_REGION( 0x400, "mcu", 0 )
ROM_LOAD( "51xx.bin", 0x0000, 0x0400, CRC(c2f57ef8) SHA1(50de79e0d6a76bda95ffb02fcce369a79e6abfec) )
ROM_END
DEFINE_DEVICE_TYPE(NAMCO_51XX, namco_51xx_device, "namco51", "Namco 51xx")
namco_51xx_device::namco_51xx_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: device_t(mconfig, NAMCO_51XX, tag, owner, clock)
, m_cpu(*this, "mcu")
, m_portO(0)
, m_rw(0)
, m_in(*this)
, m_out(*this)
, m_lockout(*this)
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void namco_51xx_device::device_start()
{
/* resolve our read callbacks */
m_in.resolve_all_safe(0);
/* resolve our write callbacks */
m_out.resolve_safe();
m_lockout.resolve_safe();
save_item(NAME(m_portO));
save_item(NAME(m_rw));
}
//-------------------------------------------------
// device_add_mconfig - add device configuration
//-------------------------------------------------
void namco_51xx_device::device_add_mconfig(machine_config &config)
{
MB8843(config, m_cpu, DERIVED_CLOCK(1,1)); /* parent clock, internally divided by 6 */
m_cpu->read_k().set(FUNC(namco_51xx_device::K_r));
m_cpu->read_r<0>().set(FUNC(namco_51xx_device::R0_r));
m_cpu->read_r<1>().set(FUNC(namco_51xx_device::R1_r));
m_cpu->read_r<2>().set(FUNC(namco_51xx_device::R2_r));
m_cpu->read_r<3>().set(FUNC(namco_51xx_device::R3_r));
m_cpu->write_o().set(FUNC(namco_51xx_device::O_w));
m_cpu->write_p().set(FUNC(namco_51xx_device::P_w));
}
//-------------------------------------------------
// device_rom_region - return a pointer to the
// the device's ROM definitions
//-------------------------------------------------
const tiny_rom_entry *namco_51xx_device::device_rom_region() const
{
return ROM_NAME(namco_51xx );
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2007 The Guava 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.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A multimap which forwards all its method calls to another multimap.
* Subclasses should override one or more methods to modify the behavior of
* the backing multimap as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Robert Konigsberg
* @since 2.0
*/
@GwtCompatible
public abstract class ForwardingMultimap<K, V> extends ForwardingObject implements Multimap<K, V> {
/** Constructor for use by subclasses. */
protected ForwardingMultimap() {}
@Override
protected abstract Multimap<K, V> delegate();
@Override
public Map<K, Collection<V>> asMap() {
return delegate().asMap();
}
@Override
public void clear() {
delegate().clear();
}
@Override
public boolean containsEntry(@Nullable Object key, @Nullable Object value) {
return delegate().containsEntry(key, value);
}
@Override
public boolean containsKey(@Nullable Object key) {
return delegate().containsKey(key);
}
@Override
public boolean containsValue(@Nullable Object value) {
return delegate().containsValue(value);
}
@Override
public Collection<Entry<K, V>> entries() {
return delegate().entries();
}
@Override
public Collection<V> get(@Nullable K key) {
return delegate().get(key);
}
@Override
public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public Multiset<K> keys() {
return delegate().keys();
}
@Override
public Set<K> keySet() {
return delegate().keySet();
}
@CanIgnoreReturnValue
@Override
public boolean put(K key, V value) {
return delegate().put(key, value);
}
@CanIgnoreReturnValue
@Override
public boolean putAll(K key, Iterable<? extends V> values) {
return delegate().putAll(key, values);
}
@CanIgnoreReturnValue
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
return delegate().putAll(multimap);
}
@CanIgnoreReturnValue
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
return delegate().remove(key, value);
}
@CanIgnoreReturnValue
@Override
public Collection<V> removeAll(@Nullable Object key) {
return delegate().removeAll(key);
}
@CanIgnoreReturnValue
@Override
public Collection<V> replaceValues(K key, Iterable<? extends V> values) {
return delegate().replaceValues(key, values);
}
@Override
public int size() {
return delegate().size();
}
@Override
public Collection<V> values() {
return delegate().values();
}
@Override
public boolean equals(@Nullable Object object) {
return object == this || delegate().equals(object);
}
@Override
public int hashCode() {
return delegate().hashCode();
}
} | {
"pile_set_name": "Github"
} |
#include "test/mocks/router/router_filter_interface.h"
using testing::AnyNumber;
using testing::Return;
using testing::ReturnRef;
namespace Envoy {
namespace Router {
MockRouterFilterInterface::MockRouterFilterInterface()
: config_("prefix.", context_, ShadowWriterPtr(new MockShadowWriter()), router_proto) {
auto cluster_info = new NiceMock<Upstream::MockClusterInfo>();
cluster_info->timeout_budget_stats_ = nullptr;
ON_CALL(*cluster_info, timeoutBudgetStats()).WillByDefault(Return(absl::nullopt));
cluster_info_.reset(cluster_info);
ON_CALL(*this, callbacks()).WillByDefault(Return(&callbacks_));
ON_CALL(*this, config()).WillByDefault(ReturnRef(config_));
ON_CALL(*this, cluster()).WillByDefault(Return(cluster_info_));
ON_CALL(*this, upstreamRequests()).WillByDefault(ReturnRef(requests_));
EXPECT_CALL(callbacks_.dispatcher_, setTrackedObject(_)).Times(AnyNumber());
ON_CALL(*this, routeEntry()).WillByDefault(Return(&route_entry_));
ON_CALL(callbacks_, connection()).WillByDefault(Return(&client_connection_));
route_entry_.connect_config_.emplace(RouteEntry::ConnectConfig());
}
MockRouterFilterInterface::~MockRouterFilterInterface() = default;
} // namespace Router
} // namespace Envoy
| {
"pile_set_name": "Github"
} |
/****************************************************************************
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, 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 "3d/CCBundle3D.h"
#include "3d/CCObjLoader.h"
#include "base/ccMacros.h"
#include "platform/CCFileUtils.h"
#include "renderer/CCGLProgram.h"
#include "CCBundleReader.h"
#include "base/CCData.h"
#include "json/document.h"
#define BUNDLE_TYPE_SCENE 1
#define BUNDLE_TYPE_NODE 2
#define BUNDLE_TYPE_ANIMATIONS 3
#define BUNDLE_TYPE_ANIMATION 4
#define BUNDLE_TYPE_ANIMATION_CHANNEL 5
#define BUNDLE_TYPE_MODEL 10
#define BUNDLE_TYPE_MATERIAL 16
#define BUNDLE_TYPE_EFFECT 18
#define BUNDLE_TYPE_CAMERA 32
#define BUNDLE_TYPE_LIGHT 33
#define BUNDLE_TYPE_MESH 34
#define BUNDLE_TYPE_MESHPART 35
#define BUNDLE_TYPE_MESHSKIN 36
static const char* VERSION = "version";
static const char* ID = "id";
static const char* DEFAULTPART = "body";
static const char* VERTEXSIZE = "vertexsize";
static const char* VERTEX = "vertex";
static const char* VERTICES = "vertices";
static const char* INDEXNUM = "indexnum";
static const char* INDICES = "indices";
static const char* SUBMESH = "submesh";
static const char* ATTRIBUTES = "attributes";
static const char* ATTRIBUTESIZE = "size";
static const char* TYPE = "type";
static const char* ATTRIBUTE = "attribute";
static const char* SKIN = "skin";
static const char* BINDSHAPE = "bindshape";
static const char* MESH = "mesh";
static const char* MESHES = "meshes";
static const char* MESHPARTID = "meshpartid";
static const char* MATERIALID = "materialid";
static const char* NODE = "node";
static const char* NODES = "nodes";
static const char* CHILDREN = "children";
static const char* PARTS = "parts";
static const char* BONES = "bones";
static const char* SKELETON = "skeleton";
static const char* MATERIALS = "materials";
static const char* ANIMATIONS = "animations";
static const char* TRANSFORM = "transform";
static const char* OLDTRANSFORM = "tansform";
static const char* ANIMATION = "animation";
static const char* MATERIAL = "material";
static const char* BASE = "base";
static const char* FILENAME = "filename";
static const char* TEXTURES = "textures";
static const char* LENGTH = "length";
static const char* BONEID = "boneId";
static const char* KEYFRAMES = "keyframes";
static const char* TRANSLATION = "translation";
static const char* ROTATION = "rotation";
static const char* SCALE = "scale";
static const char* KEYTIME = "keytime";
static const char* AABBS = "aabb";
NS_CC_BEGIN
void getChildMap(std::map<int, std::vector<int> >& map, SkinData* skinData, const rapidjson::Value& val)
{
if (!skinData)
return;
// get transform matrix
Mat4 transform;
const rapidjson::Value& parent_tranform = val[OLDTRANSFORM];
for (rapidjson::SizeType j = 0; j < parent_tranform.Size(); j++)
{
transform.m[j] = parent_tranform[j].GetDouble();
}
// set origin matrices
std::string parent_name = val[ID].GetString();
int parent_name_index = skinData->getSkinBoneNameIndex(parent_name);
if (parent_name_index < 0)
{
skinData->addNodeBoneNames(parent_name);
skinData->nodeBoneOriginMatrices.push_back(transform);
parent_name_index = skinData->getBoneNameIndex(parent_name);
}
else if (parent_name_index < static_cast<int>(skinData->skinBoneNames.size()))
{
skinData->skinBoneOriginMatrices[parent_name_index] = transform;
}
// set root bone index
if(skinData->rootBoneIndex < 0)
skinData->rootBoneIndex = parent_name_index;
if (!val.HasMember(CHILDREN))
return;
const rapidjson::Value& children = val[CHILDREN];
for (rapidjson::SizeType i = 0; i < children.Size(); i++)
{
// get child bone name
const rapidjson::Value& child = children[i];
std::string child_name = child[ID].GetString();
int child_name_index = skinData->getSkinBoneNameIndex(child_name);
if (child_name_index < 0)
{
skinData->addNodeBoneNames(child_name);
child_name_index = skinData->getBoneNameIndex(child_name);
}
map[parent_name_index].push_back(child_name_index);
getChildMap(map, skinData, child);
}
}
Bundle3D* Bundle3D::createBundle()
{
auto bundle = new (std::nothrow) Bundle3D();
return bundle;
}
void Bundle3D::destroyBundle(Bundle3D* bundle)
{
delete bundle;
}
void Bundle3D::clear()
{
if (_isBinary)
{
CC_SAFE_DELETE(_binaryBuffer);
CC_SAFE_DELETE_ARRAY(_references);
}
else
{
CC_SAFE_DELETE_ARRAY(_jsonBuffer);
}
}
bool Bundle3D::load(const std::string& path)
{
if (path.empty())
return false;
if (_path == path)
return true;
getModelRelativePath(path);
bool ret = false;
std::string ext = FileUtils::getInstance()->getFileExtension(path);
if (ext == ".c3t")
{
_isBinary = false;
ret = loadJson(path);
}
else if (ext == ".c3b")
{
_isBinary = true;
ret = loadBinary(path);
}
else
{
CCLOG("warning: %s is invalid file formate", path.c_str());
}
ret?(_path = path):(_path = "");
return ret;
}
bool Bundle3D::loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeDatas& nodedatas, const std::string& fullPath, const char* mtl_basepath)
{
meshdatas.resetData();
materialdatas.resetData();
nodedatas.resetData();
std::string mtlPath = "";
if (mtl_basepath)
mtlPath = mtl_basepath;
else
mtlPath = fullPath.substr(0, fullPath.find_last_of("\\/") + 1).c_str();
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
auto ret = tinyobj::LoadObj(shapes, materials, fullPath.c_str(), mtlPath.c_str());
if (ret.empty())
{
//fill data
//convert material
int i = 0;
char str[20];
std::string dir = "";
auto last = fullPath.rfind("/");
if (last != -1)
dir = fullPath.substr(0, last + 1);
for (auto& material : materials) {
NMaterialData materialdata;
NTextureData tex;
tex.filename = material.diffuse_texname.empty() ? material.diffuse_texname : dir + material.diffuse_texname;
tex.type = NTextureData::Usage::Diffuse;
tex.wrapS = GL_CLAMP_TO_EDGE;
tex.wrapT = GL_CLAMP_TO_EDGE;
sprintf(str, "%d", i++);
materialdata.textures.push_back(tex);
materialdata.id = str;
material.name = str;
materialdatas.materials.push_back(materialdata);
}
//convert mesh
i = 0;
for (auto& shape : shapes) {
auto mesh = shape.mesh;
MeshData* meshdata = new (std::nothrow) MeshData();
MeshVertexAttrib attrib;
attrib.size = 3;
attrib.type = GL_FLOAT;
if (mesh.positions.size())
{
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_POSITION;
attrib.attribSizeBytes = attrib.size * sizeof(float);
meshdata->attribs.push_back(attrib);
}
bool hasnormal = false, hastex = false;
if (mesh.normals.size())
{
hasnormal = true;
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_NORMAL;
attrib.attribSizeBytes = attrib.size * sizeof(float);;
meshdata->attribs.push_back(attrib);
}
if (mesh.texcoords.size())
{
hastex = true;
attrib.size = 2;
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_TEX_COORD;
attrib.attribSizeBytes = attrib.size * sizeof(float);
meshdata->attribs.push_back(attrib);
}
auto vertexNum = mesh.positions.size() / 3;
for(unsigned int k = 0; k < vertexNum; k++)
{
meshdata->vertex.push_back(mesh.positions[k * 3]);
meshdata->vertex.push_back(mesh.positions[k * 3 + 1]);
meshdata->vertex.push_back(mesh.positions[k * 3 + 2]);
if (hasnormal)
{
meshdata->vertex.push_back(mesh.normals[k * 3]);
meshdata->vertex.push_back(mesh.normals[k * 3 + 1]);
meshdata->vertex.push_back(mesh.normals[k * 3 + 2]);
}
if (hastex)
{
meshdata->vertex.push_back(mesh.texcoords[k * 2]);
meshdata->vertex.push_back(mesh.texcoords[k * 2 + 1]);
}
}
//split into submesh according to material
std::map<int, std::vector<unsigned short> > subMeshMap;
for (size_t k = 0; k < mesh.material_ids.size(); k++) {
int id = mesh.material_ids[k];
size_t idx = k * 3;
subMeshMap[id].push_back(mesh.indices[idx]);
subMeshMap[id].push_back(mesh.indices[idx + 1]);
subMeshMap[id].push_back(mesh.indices[idx + 2]);
}
auto node = new (std::nothrow) NodeData();
node->id = shape.name;
for (auto& submesh : subMeshMap) {
meshdata->subMeshIndices.push_back(submesh.second);
meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), submesh.second));
sprintf(str, "%d", i++);
meshdata->subMeshIds.push_back(str);
auto modelnode = new (std::nothrow) ModelData();
modelnode->matrialId = submesh.first == -1 ? "" : materials[submesh.first].name;
modelnode->subMeshId = str;
node->modelNodeDatas.push_back(modelnode);
}
nodedatas.nodes.push_back(node);
meshdatas.meshDatas.push_back(meshdata);
}
return true;
}
CCLOG("warning: load %s file error: %s", fullPath.c_str(), ret.c_str());
return false;
}
bool Bundle3D::loadSkinData(const std::string& id, SkinData* skindata)
{
skindata->resetData();
if (_isBinary)
{
return loadSkinDataBinary(skindata);
}
else
{
return loadSkinDataJson(skindata);
}
}
bool Bundle3D::loadAnimationData(const std::string& id, Animation3DData* animationdata)
{
animationdata->resetData();
if (_isBinary)
{
return loadAnimationDataBinary(id,animationdata);
}
else
{
return loadAnimationDataJson(id,animationdata);
}
}
//since 3.3, to support reskin
bool Bundle3D::loadMeshDatas(MeshDatas& meshdatas)
{
meshdatas.resetData();
if (_isBinary)
{
if (_version == "0.1" || _version == "0.2")
{
return loadMeshDatasBinary_0_1(meshdatas);
}
else
{
return loadMeshDatasBinary(meshdatas);
}
}
else
{
if (_version == "1.2" || _version == "0.2")
{
return loadMeshDataJson_0_1(meshdatas);
}
else
{
return loadMeshDatasJson(meshdatas);
}
}
return true;
}
bool Bundle3D::loadMeshDatasBinary(MeshDatas& meshdatas)
{
if (!seekToFirstType(BUNDLE_TYPE_MESH))
return false;
unsigned int meshSize = 0;
if (_binaryReader.read(&meshSize, 4, 1) != 1)
{
CCLOG("warning: Failed to read meshdata: attribCount '%s'.", _path.c_str());
return false;
}
MeshData* meshData = nullptr;
for(unsigned int i = 0; i < meshSize ; i++ )
{
unsigned int attribSize=0;
// read mesh data
if (_binaryReader.read(&attribSize, 4, 1) != 1 || attribSize < 1)
{
CCLOG("warning: Failed to read meshdata: attribCount '%s'.", _path.c_str());
goto FAILED;
}
meshData = new (std::nothrow) MeshData();
meshData->attribCount = attribSize;
meshData->attribs.resize(meshData->attribCount);
for (ssize_t j = 0; j < meshData->attribCount; j++)
{
std::string attribute="";
unsigned int vSize;
if (_binaryReader.read(&vSize, 4, 1) != 1)
{
CCLOG("warning: Failed to read meshdata: usage or size '%s'.", _path.c_str());
goto FAILED;
}
std::string type = _binaryReader.readString();
attribute=_binaryReader.readString();
meshData->attribs[j].size = vSize;
meshData->attribs[j].attribSizeBytes = meshData->attribs[j].size * 4;
meshData->attribs[j].type = parseGLType(type);
meshData->attribs[j].vertexAttrib = parseGLProgramAttribute(attribute);
}
unsigned int vertexSizeInFloat = 0;
// Read vertex data
if (_binaryReader.read(&vertexSizeInFloat, 4, 1) != 1 || vertexSizeInFloat == 0)
{
CCLOG("warning: Failed to read meshdata: vertexSizeInFloat '%s'.", _path.c_str());
goto FAILED;
}
meshData->vertex.resize(vertexSizeInFloat);
if (_binaryReader.read(&meshData->vertex[0], 4, vertexSizeInFloat) != vertexSizeInFloat)
{
CCLOG("warning: Failed to read meshdata: vertex element '%s'.", _path.c_str());
goto FAILED;
}
// Read index data
unsigned int meshPartCount = 1;
_binaryReader.read(&meshPartCount, 4, 1);
for (unsigned int k = 0; k < meshPartCount; ++k)
{
std::vector<unsigned short> indexArray;
std:: string meshPartid = _binaryReader.readString();
meshData->subMeshIds.push_back(meshPartid);
unsigned int nIndexCount;
if (_binaryReader.read(&nIndexCount, 4, 1) != 1)
{
CCLOG("warning: Failed to read meshdata: nIndexCount '%s'.", _path.c_str());
goto FAILED;
}
indexArray.resize(nIndexCount);
if (_binaryReader.read(&indexArray[0], 2, nIndexCount) != nIndexCount)
{
CCLOG("warning: Failed to read meshdata: indices '%s'.", _path.c_str());
goto FAILED;
}
meshData->subMeshIndices.push_back(indexArray);
meshData->numIndex = (int)meshData->subMeshIndices.size();
//meshData->subMeshAABB.push_back(calculateAABB(meshData->vertex, meshData->getPerVertexSize(), indexArray));
if (_version != "0.3" && _version != "0.4" && _version != "0.5")
{
//read mesh aabb
float aabb[6];
if (_binaryReader.read(aabb, 4, 6) != 6)
{
CCLOG("warning: Failed to read meshdata: aabb '%s'.", _path.c_str());
goto FAILED;
}
meshData->subMeshAABB.push_back(AABB(Vec3(aabb[0], aabb[1], aabb[2]), Vec3(aabb[3], aabb[4], aabb[5])));
}
else
{
meshData->subMeshAABB.push_back(calculateAABB(meshData->vertex, meshData->getPerVertexSize(), indexArray));
}
}
meshdatas.meshDatas.push_back(meshData);
}
return true;
FAILED:
{
CC_SAFE_DELETE(meshData);
for (auto& meshdata : meshdatas.meshDatas) {
delete meshdata;
}
meshdatas.meshDatas.clear();
return false;
}
}
bool Bundle3D::loadMeshDatasBinary_0_1(MeshDatas& meshdatas)
{
if (!seekToFirstType(BUNDLE_TYPE_MESH))
return false;
meshdatas.resetData();
MeshData* meshdata = new (std::nothrow) MeshData();
// read mesh data
unsigned int attribSize=0;
if (_binaryReader.read(&attribSize, 4, 1) != 1 || attribSize < 1)
{
CCLOG("warning: Failed to read meshdata: attribCount '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
enum
{
VERTEX_ATTRIB_POSITION,
VERTEX_ATTRIB_COLOR,
VERTEX_ATTRIB_TEX_COORD,
VERTEX_ATTRIB_NORMAL,
VERTEX_ATTRIB_BLEND_WEIGHT,
VERTEX_ATTRIB_BLEND_INDEX,
VERTEX_ATTRIB_MAX,
// backward compatibility
VERTEX_ATTRIB_TEX_COORDS = VERTEX_ATTRIB_TEX_COORD,
};
for (unsigned int i = 0; i < attribSize; i++)
{
unsigned int vUsage, vSize;
if (_binaryReader.read(&vUsage, 4, 1) != 1 || _binaryReader.read(&vSize, 4, 1) != 1)
{
CCLOG("warning: Failed to read meshdata: usage or size '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
MeshVertexAttrib meshVertexAttribute;
meshVertexAttribute.size = vSize;
meshVertexAttribute.attribSizeBytes = vSize * 4;
meshVertexAttribute.type = GL_FLOAT;
if(vUsage == VERTEX_ATTRIB_NORMAL)
{
vUsage= GLProgram::VERTEX_ATTRIB_NORMAL;
}
else if(vUsage == VERTEX_ATTRIB_BLEND_WEIGHT)
{
vUsage= GLProgram::VERTEX_ATTRIB_BLEND_WEIGHT;
}
else if(vUsage == VERTEX_ATTRIB_BLEND_INDEX)
{
vUsage= GLProgram::VERTEX_ATTRIB_BLEND_INDEX;
}
else if(vUsage == VERTEX_ATTRIB_POSITION)
{
vUsage= GLProgram::VERTEX_ATTRIB_POSITION;
}
else if(vUsage == VERTEX_ATTRIB_TEX_COORD)
{
vUsage= GLProgram::VERTEX_ATTRIB_TEX_COORD;
}
meshVertexAttribute.vertexAttrib = vUsage;
meshdata->attribs.push_back(meshVertexAttribute);
}
// Read vertex data
if (_binaryReader.read(&meshdata->vertexSizeInFloat, 4, 1) != 1 || meshdata->vertexSizeInFloat == 0)
{
CCLOG("warning: Failed to read meshdata: vertexSizeInFloat '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
meshdata->vertex.resize(meshdata->vertexSizeInFloat);
if (_binaryReader.read(&meshdata->vertex[0], 4, meshdata->vertexSizeInFloat) != meshdata->vertexSizeInFloat)
{
CCLOG("warning: Failed to read meshdata: vertex element '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
// Read index data
unsigned int meshPartCount = 1;
for (unsigned int i = 0; i < meshPartCount; ++i)
{
unsigned int nIndexCount;
if (_binaryReader.read(&nIndexCount, 4, 1) != 1)
{
CCLOG("warning: Failed to read meshdata: nIndexCount '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
std::vector<unsigned short> indices;
indices.resize(nIndexCount);
if (_binaryReader.read(&indices[0], 2, nIndexCount) != nIndexCount)
{
CCLOG("warning: Failed to read meshdata: indices '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
meshdata->subMeshIndices.push_back(indices);
meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), indices));
}
meshdatas.meshDatas.push_back(meshdata);
return true;
}
bool Bundle3D::loadMeshDatasBinary_0_2(MeshDatas& meshdatas)
{
if (!seekToFirstType(BUNDLE_TYPE_MESH))
return false;
meshdatas.resetData();
MeshData* meshdata = new (std::nothrow) MeshData();
// read mesh data
unsigned int attribSize=0;
if (_binaryReader.read(&attribSize, 4, 1) != 1 || attribSize < 1)
{
CCLOG("warning: Failed to read meshdata: attribCount '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
enum
{
VERTEX_ATTRIB_POSITION,
VERTEX_ATTRIB_COLOR,
VERTEX_ATTRIB_TEX_COORD,
VERTEX_ATTRIB_NORMAL,
VERTEX_ATTRIB_BLEND_WEIGHT,
VERTEX_ATTRIB_BLEND_INDEX,
VERTEX_ATTRIB_MAX,
// backward compatibility
VERTEX_ATTRIB_TEX_COORDS = VERTEX_ATTRIB_TEX_COORD,
};
for (unsigned int i = 0; i < attribSize; i++)
{
unsigned int vUsage, vSize;
if (_binaryReader.read(&vUsage, 4, 1) != 1 || _binaryReader.read(&vSize, 4, 1) != 1)
{
CCLOG("warning: Failed to read meshdata: usage or size '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
MeshVertexAttrib meshVertexAttribute;
meshVertexAttribute.size = vSize;
meshVertexAttribute.attribSizeBytes = vSize * 4;
meshVertexAttribute.type = GL_FLOAT;
if(vUsage == VERTEX_ATTRIB_NORMAL)
{
vUsage= GLProgram::VERTEX_ATTRIB_NORMAL;
}
else if(vUsage == VERTEX_ATTRIB_BLEND_WEIGHT)
{
vUsage= GLProgram::VERTEX_ATTRIB_BLEND_WEIGHT;
}
else if(vUsage == VERTEX_ATTRIB_BLEND_INDEX)
{
vUsage= GLProgram::VERTEX_ATTRIB_BLEND_INDEX;
}
else if(vUsage == VERTEX_ATTRIB_POSITION)
{
vUsage= GLProgram::VERTEX_ATTRIB_POSITION;
}
else if(vUsage == VERTEX_ATTRIB_TEX_COORD)
{
vUsage= GLProgram::VERTEX_ATTRIB_TEX_COORD;
}
meshVertexAttribute.vertexAttrib = vUsage;
meshdata->attribs.push_back(meshVertexAttribute);
}
// Read vertex data
if (_binaryReader.read(&meshdata->vertexSizeInFloat, 4, 1) != 1 || meshdata->vertexSizeInFloat == 0)
{
CCLOG("warning: Failed to read meshdata: vertexSizeInFloat '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
meshdata->vertex.resize(meshdata->vertexSizeInFloat);
if (_binaryReader.read(&meshdata->vertex[0], 4, meshdata->vertexSizeInFloat) != meshdata->vertexSizeInFloat)
{
CCLOG("warning: Failed to read meshdata: vertex element '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
// read submesh
unsigned int submeshCount;
if (_binaryReader.read(&submeshCount, 4, 1) != 1)
{
CCLOG("warning: Failed to read meshdata: submeshCount '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
for (unsigned int i = 0; i < submeshCount; ++i)
{
unsigned int nIndexCount;
if (_binaryReader.read(&nIndexCount, 4, 1) != 1)
{
CCLOG("warning: Failed to read meshdata: nIndexCount '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
std::vector<unsigned short> indices;
indices.resize(nIndexCount);
if (_binaryReader.read(&indices[0], 2, nIndexCount) != nIndexCount)
{
CCLOG("warning: Failed to read meshdata: indices '%s'.", _path.c_str());
CC_SAFE_DELETE(meshdata);
return false;
}
meshdata->subMeshIndices.push_back(indices);
meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), indices));
}
meshdatas.meshDatas.push_back(meshdata);
return true;
}
bool Bundle3D::loadMeshDatasJson(MeshDatas& meshdatas)
{
const rapidjson::Value& mesh_data_array = _jsonReader[MESHES];
for (rapidjson::SizeType index = 0; index < mesh_data_array.Size(); index++)
{
MeshData* meshData = new (std::nothrow) MeshData();
const rapidjson::Value& mesh_data = mesh_data_array[index];
// mesh_vertex_attribute
const rapidjson::Value& mesh_vertex_attribute = mesh_data[ATTRIBUTES];
MeshVertexAttrib tempAttrib;
meshData->attribCount=mesh_vertex_attribute.Size();
meshData->attribs.resize(meshData->attribCount);
for (rapidjson::SizeType i = 0; i < mesh_vertex_attribute.Size(); i++)
{
const rapidjson::Value& mesh_vertex_attribute_val = mesh_vertex_attribute[i];
int size = mesh_vertex_attribute_val[ATTRIBUTESIZE].GetInt();
std::string type = mesh_vertex_attribute_val[TYPE].GetString();
std::string attribute = mesh_vertex_attribute_val[ATTRIBUTE].GetString();
tempAttrib.size = size;
tempAttrib.attribSizeBytes = sizeof(float) * size;
tempAttrib.type = parseGLType(type);
tempAttrib.vertexAttrib = parseGLProgramAttribute(attribute);
meshData->attribs[i]=tempAttrib;
}
// mesh vertices
////////////////////////////////////////////////////////////////////////////////////////////////
const rapidjson::Value& mesh_data_vertex_array = mesh_data[VERTICES];
meshData->vertexSizeInFloat=mesh_data_vertex_array.Size();
for (rapidjson::SizeType i = 0; i < mesh_data_vertex_array.Size(); i++)
{
meshData->vertex.push_back(mesh_data_vertex_array[i].GetDouble());
}
// mesh part
////////////////////////////////////////////////////////////////////////////////////////////////
const rapidjson::Value& mesh_part_array = mesh_data[PARTS];
for (rapidjson::SizeType i = 0; i < mesh_part_array.Size(); i++)
{
std::vector<unsigned short> indexArray;
const rapidjson::Value& mesh_part = mesh_part_array[i];
meshData->subMeshIds.push_back(mesh_part[ID].GetString());
// index_number
const rapidjson::Value& indices_val_array = mesh_part[INDICES];
for (rapidjson::SizeType j = 0; j < indices_val_array.Size(); j++)
indexArray.push_back((unsigned short)indices_val_array[j].GetUint());
meshData->subMeshIndices.push_back(indexArray);
meshData->numIndex = (int)meshData->subMeshIndices.size();
if(mesh_data.HasMember(AABBS))
{
const rapidjson::Value& mesh_part_aabb = mesh_part[AABBS];
if (mesh_part.HasMember(AABBS) && mesh_part_aabb.Size() == 6)
{
Vec3 min(mesh_part_aabb[(rapidjson::SizeType)0].GetDouble(),
mesh_part_aabb[(rapidjson::SizeType)1].GetDouble(), mesh_part_aabb[(rapidjson::SizeType)2].GetDouble());
Vec3 max(mesh_part_aabb[(rapidjson::SizeType)3].GetDouble(),
mesh_part_aabb[(rapidjson::SizeType)4].GetDouble(), mesh_part_aabb[(rapidjson::SizeType)5].GetDouble());
meshData->subMeshAABB.push_back(AABB(min, max));
}
else
{
meshData->subMeshAABB.push_back(calculateAABB(meshData->vertex, meshData->getPerVertexSize(), indexArray));
}
}
else
{
meshData->subMeshAABB.push_back(calculateAABB(meshData->vertex, meshData->getPerVertexSize(), indexArray));
}
}
meshdatas.meshDatas.push_back(meshData);
}
return true;
}
bool Bundle3D::loadNodes(NodeDatas& nodedatas)
{
if (_version == "0.1" || _version == "1.2" || _version == "0.2")
{
SkinData skinData;
if (!loadSkinData("", &skinData))
{
auto node= new (std::nothrow) NodeData();
auto modelnode = new (std::nothrow) ModelData();
modelnode->matrialId = "";
modelnode->subMeshId = "";
node->modelNodeDatas.push_back(modelnode);
nodedatas.nodes.push_back(node);
return true;
}
auto nodeDatas = new (std::nothrow) NodeData*[skinData.skinBoneNames.size() + skinData.nodeBoneNames.size()];
int index = 0;
size_t i;
for (i = 0; i < skinData.skinBoneNames.size(); i++)
{
nodeDatas[index] = new (std::nothrow) NodeData();
nodeDatas[index]->id = skinData.skinBoneNames[i];
nodeDatas[index]->transform = skinData.skinBoneOriginMatrices[i];
index++;
}
for (i = 0; i < skinData.nodeBoneNames.size(); i++)
{
nodeDatas[index] = new (std::nothrow) NodeData();
nodeDatas[index]->id = skinData.nodeBoneNames[i];
nodeDatas[index]->transform = skinData.nodeBoneOriginMatrices[i];
index++;
}
for (const auto& it : skinData.boneChild)
{
const auto& children = it.second;
auto parent = nodeDatas[it.first];
for (const auto& child : children)
{
parent->children.push_back(nodeDatas[child]);
}
}
nodedatas.skeleton.push_back(nodeDatas[skinData.rootBoneIndex]);
auto node= new (std::nothrow) NodeData();
auto modelnode = new (std::nothrow) ModelData();
modelnode->matrialId = "";
modelnode->subMeshId = "";
modelnode->bones = skinData.skinBoneNames;
modelnode->invBindPose = skinData.inverseBindPoseMatrices;
node->modelNodeDatas.push_back(modelnode);
nodedatas.nodes.push_back(node);
delete[] nodeDatas;
}
else
{
if (_isBinary)
{
loadNodesBinary(nodedatas);
}
else
{
loadNodesJson(nodedatas);
}
}
return true;
}
bool Bundle3D::loadMaterials(MaterialDatas& materialdatas)
{
materialdatas.resetData();
if (_isBinary)
{
if (_version == "0.1")
{
return loadMaterialsBinary_0_1(materialdatas);
}
else if (_version == "0.2")
{
return loadMaterialsBinary_0_2(materialdatas);
}
else
{
return loadMaterialsBinary(materialdatas);
}
}
else
{
if (_version == "1.2")
{
return loadMaterialDataJson_0_1(materialdatas);
}
else if (_version == "0.2")
{
return loadMaterialDataJson_0_2(materialdatas);
}
else
{
return loadMaterialsJson(materialdatas);
}
}
return true;
}
bool Bundle3D::loadMaterialsBinary(MaterialDatas& materialdatas)
{
if (!seekToFirstType(BUNDLE_TYPE_MATERIAL))
return false;
unsigned int materialnum = 1;
_binaryReader.read(&materialnum, 4, 1);
for (unsigned int i = 0; i < materialnum; i++)
{
NMaterialData materialData;
materialData.id = _binaryReader.readString();
// skip: diffuse(3), ambient(3), emissive(3), opacity(1), specular(3), shininess(1)
float data[14];
_binaryReader.read(&data,sizeof(float), 14);
unsigned int textruenum = 1;
_binaryReader.read(&textruenum, 4, 1);
for(unsigned int j = 0; j < textruenum ; j++ )
{
NTextureData textureData;
textureData.id = _binaryReader.readString();
if (textureData.id.empty())
{
CCLOG("warning: Failed to read Materialdata: texturePath is empty '%s'.", textureData.id.c_str());
return false;
}
std::string texturePath = _binaryReader.readString();
if (texturePath.empty())
{
CCLOG("warning: Failed to read Materialdata: texturePath is empty '%s'.", _path.c_str());
return false;
}
textureData.filename = texturePath.empty() ? texturePath : _modelPath + texturePath;
float uvdata[4];
_binaryReader.read(&uvdata,sizeof(float), 4);
textureData.type = parseGLTextureType(_binaryReader.readString());
textureData.wrapS= parseGLType(_binaryReader.readString());
textureData.wrapT= parseGLType(_binaryReader.readString());
materialData.textures.push_back(textureData);
}
materialdatas.materials.push_back(materialData);
}
return true;
}
bool Bundle3D::loadMaterialsBinary_0_1(MaterialDatas& materialdatas)
{
if (!seekToFirstType(BUNDLE_TYPE_MATERIAL))
return false;
NMaterialData materialData;
std::string texturePath = _binaryReader.readString();
if (texturePath.empty())
{
CCLOG("warning: Failed to read Materialdata: texturePath is empty '%s'.", _path.c_str());
return false;
}
NTextureData textureData;
textureData.filename = texturePath.empty() ? texturePath : _modelPath + texturePath;
textureData.type= NTextureData::Usage::Diffuse;
textureData.id="";
materialData.textures.push_back(textureData);
materialdatas.materials.push_back(materialData);
return true;
}
bool Bundle3D::loadMaterialsBinary_0_2(MaterialDatas& materialdatas)
{
if (!seekToFirstType(BUNDLE_TYPE_MATERIAL))
return false;
unsigned int materialnum = 1;
_binaryReader.read(&materialnum, 4, 1);
for (unsigned int i = 0; i < materialnum; i++)
{
NMaterialData materialData;
std::string texturePath = _binaryReader.readString();
if (texturePath.empty())
{
CCLOG("warning: Failed to read Materialdata: texturePath is empty '%s'.", _path.c_str());
return true;
}
NTextureData textureData;
textureData.filename = texturePath.empty() ? texturePath : _modelPath + texturePath;
textureData.type= NTextureData::Usage::Diffuse;
textureData.id="";
materialData.textures.push_back(textureData);
materialdatas.materials.push_back(materialData);
}
return true;
}
bool Bundle3D::loadMaterialsJson(MaterialDatas& materialdatas)
{
if (!_jsonReader.HasMember(MATERIALS))
return false;
const rapidjson::Value& material_array = _jsonReader[MATERIALS];
for (rapidjson::SizeType i = 0; i < material_array.Size(); i++)
{
NMaterialData materialData;
const rapidjson::Value& material_val = material_array[i];
materialData.id = material_val[ID].GetString();
if (material_val.HasMember(TEXTURES))
{
const rapidjson::Value& testure_array = material_val[TEXTURES];
for (rapidjson::SizeType j = 0; j < testure_array.Size(); j++)
{
NTextureData textureData;
const rapidjson::Value& texture_val = testure_array[j];
std::string filename = texture_val[FILENAME].GetString();
textureData.filename = filename.empty() ? filename : _modelPath + filename;
textureData.type = parseGLTextureType(texture_val["type"].GetString());
textureData.wrapS = parseGLType(texture_val["wrapModeU"].GetString());
textureData.wrapT = parseGLType(texture_val["wrapModeV"].GetString());
materialData.textures.push_back(textureData);
}
}
materialdatas.materials.push_back(materialData);
}
return true;
}
bool Bundle3D::loadJson(const std::string& path)
{
clear();
Data data = FileUtils::getInstance()->getDataFromFile(path);
ssize_t size = data.getSize();
// json need null-terminated string.
_jsonBuffer = new char[size + 1];
memcpy(_jsonBuffer, data.getBytes(), size);
_jsonBuffer[size] = '\0';
if (_jsonReader.ParseInsitu<0>(_jsonBuffer).HasParseError())
{
clear();
CCLOG("Parse json failed in Bundle3D::loadJson function");
return false;
}
const rapidjson::Value& mash_data_array = _jsonReader[VERSION];
if (mash_data_array.IsArray()) // Compatible with the old version
_version = "1.2";
else
_version = mash_data_array.GetString();
return true;
}
bool Bundle3D::loadBinary(const std::string& path)
{
clear();
// get file data
CC_SAFE_DELETE(_binaryBuffer);
_binaryBuffer = new (std::nothrow) Data();
*_binaryBuffer = FileUtils::getInstance()->getDataFromFile(path);
if (_binaryBuffer->isNull())
{
clear();
CCLOG("warning: Failed to read file: %s", path.c_str());
return false;
}
// Initialise bundle reader
_binaryReader.init( (char*)_binaryBuffer->getBytes(), _binaryBuffer->getSize() );
// Read identifier info
char identifier[] = { 'C', '3', 'B', '\0'};
char sig[4];
if (_binaryReader.read(sig, 1, 4) != 4 || memcmp(sig, identifier, 4) != 0)
{
clear();
CCLOG("warning: Invalid identifier: %s", path.c_str());
return false;
}
// Read version
unsigned char ver[2];
if (_binaryReader.read(ver, 1, 2)!= 2){
CCLOG("warning: Failed to read version:");
return false;
}
char version[20] = {0};
sprintf(version, "%d.%d", ver[0], ver[1]);
_version = version;
// Read ref table size
if (_binaryReader.read(&_referenceCount, 4, 1) != 1)
{
clear();
CCLOG("warning: Failed to read ref table size '%s'.", path.c_str());
return false;
}
// Read all refs
CC_SAFE_DELETE_ARRAY(_references);
_references = new (std::nothrow) Reference[_referenceCount];
for (unsigned int i = 0; i < _referenceCount; ++i)
{
if ((_references[i].id = _binaryReader.readString()).empty() ||
_binaryReader.read(&_references[i].type, 4, 1) != 1 ||
_binaryReader.read(&_references[i].offset, 4, 1) != 1)
{
clear();
CCLOG("warning: Failed to read ref number %u for bundle '%s'.", i, path.c_str());
CC_SAFE_DELETE_ARRAY(_references);
return false;
}
}
return true;
}
bool Bundle3D::loadMeshDataJson_0_1(MeshDatas& meshdatas)
{
const rapidjson::Value& mesh_data_array = _jsonReader[MESH];
MeshData* meshdata= new MeshData();
const rapidjson::Value& mesh_data_val = mesh_data_array[(rapidjson::SizeType)0];
const rapidjson::Value& mesh_data_body_array = mesh_data_val[DEFAULTPART];
const rapidjson::Value& mesh_data_body_array_0 = mesh_data_body_array[(rapidjson::SizeType)0];
// mesh_vertex_attribute
const rapidjson::Value& mesh_vertex_attribute = mesh_data_val[ATTRIBUTES];
meshdata->attribCount = mesh_vertex_attribute.Size();
meshdata->attribs.resize(meshdata->attribCount);
for (rapidjson::SizeType i = 0; i < mesh_vertex_attribute.Size(); i++)
{
const rapidjson::Value& mesh_vertex_attribute_val = mesh_vertex_attribute[i];
meshdata->attribs[i].size = mesh_vertex_attribute_val[ATTRIBUTESIZE].GetUint();
meshdata->attribs[i].attribSizeBytes = meshdata->attribs[i].size * 4;
meshdata->attribs[i].type = parseGLType(mesh_vertex_attribute_val[TYPE].GetString());
meshdata->attribs[i].vertexAttrib = parseGLProgramAttribute(mesh_vertex_attribute_val[ATTRIBUTE].GetString());
}
// vertices
meshdata->vertexSizeInFloat = mesh_data_body_array_0[VERTEXSIZE].GetInt();
meshdata->vertex.resize(meshdata->vertexSizeInFloat);
const rapidjson::Value& mesh_data_body_vertices = mesh_data_body_array_0[VERTICES];
for (rapidjson::SizeType i = 0; i < mesh_data_body_vertices.Size(); i++)
meshdata->vertex[i] = mesh_data_body_vertices[i].GetDouble();
// index_number
unsigned int indexnum = mesh_data_body_array_0[INDEXNUM].GetUint();
// indices
std::vector<unsigned short> indices;
indices.resize(indexnum);
const rapidjson::Value& indices_val_array = mesh_data_body_array_0[INDICES];
for (rapidjson::SizeType i = 0; i < indices_val_array.Size(); i++)
indices[i] = (unsigned short)indices_val_array[i].GetUint();
meshdata->subMeshIndices.push_back(indices);
meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), indices));
meshdatas.meshDatas.push_back(meshdata);
return true;
}
bool Bundle3D::loadMeshDataJson_0_2(MeshDatas& meshdatas)
{
MeshData* meshdata= new MeshData();
const rapidjson::Value& mesh_array = _jsonReader[MESH];
const rapidjson::Value& mesh_array_0 = mesh_array[(rapidjson::SizeType)0];
// mesh_vertex_attribute
const rapidjson::Value& mesh_vertex_attribute = mesh_array_0[ATTRIBUTES];
meshdata->attribCount = mesh_vertex_attribute.Size();
meshdata->attribs.resize(meshdata->attribCount);
for (rapidjson::SizeType i = 0; i < mesh_vertex_attribute.Size(); i++)
{
const rapidjson::Value& mesh_vertex_attribute_val = mesh_vertex_attribute[i];
meshdata->attribs[i].size = mesh_vertex_attribute_val[ATTRIBUTESIZE].GetUint();
meshdata->attribs[i].attribSizeBytes = meshdata->attribs[i].size * 4;
meshdata->attribs[i].type = parseGLType(mesh_vertex_attribute_val[TYPE].GetString());
meshdata->attribs[i].vertexAttrib = parseGLProgramAttribute(mesh_vertex_attribute_val[ATTRIBUTE].GetString());
}
// vertices
const rapidjson::Value& mesh_data_vertex = mesh_array_0[VERTEX];
const rapidjson::Value& mesh_data_vertex_0 = mesh_data_vertex[(rapidjson::SizeType)0];
meshdata->vertexSizeInFloat = mesh_data_vertex_0[VERTEXSIZE].GetInt();
meshdata->vertex.resize(meshdata->vertexSizeInFloat);
const rapidjson::Value& mesh_data_body_vertices = mesh_data_vertex_0[VERTICES];
for (rapidjson::SizeType i = 0; i < mesh_data_body_vertices.Size(); i++)
meshdata->vertex[i] = mesh_data_body_vertices[i].GetDouble();
// submesh
const rapidjson::Value& mesh_submesh_array = mesh_array_0[SUBMESH];
for (rapidjson::SizeType i = 0; i < mesh_submesh_array.Size(); i++)
{
const rapidjson::Value& mesh_submesh_val = mesh_submesh_array[i];
//std::string id = mesh_submesh_val[ID].GetString();
// index_number
unsigned int indexnum = mesh_submesh_val[INDEXNUM].GetUint();
// indices
std::vector<unsigned short> indices;
indices.resize(indexnum);
const rapidjson::Value& indices_val_array = mesh_submesh_val[INDICES];
for (rapidjson::SizeType j = 0; j < indices_val_array.Size(); j++)
indices[j] = (unsigned short)indices_val_array[j].GetUint();
meshdata->subMeshIndices.push_back(indices);
meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), indices));
}
meshdatas.meshDatas.push_back(meshdata);
return true;
}
bool Bundle3D::loadSkinDataJson(SkinData* skindata)
{
if (!_jsonReader.HasMember(SKIN )) return false;
const rapidjson::Value& skin_data_array = _jsonReader[SKIN ];
CCASSERT(skin_data_array.IsArray(), "skin data is not an array");
const rapidjson::Value& skin_data_array_val_0 = skin_data_array[(rapidjson::SizeType)0];
if (!skin_data_array_val_0.HasMember(BONES))
return false;
const rapidjson::Value& skin_data_bones = skin_data_array_val_0[BONES];
for (rapidjson::SizeType i = 0; i < skin_data_bones.Size(); i++)
{
const rapidjson::Value& skin_data_bone = skin_data_bones[i];
std::string name = skin_data_bone[NODE].GetString();
skindata->addSkinBoneNames(name);
Mat4 mat_bind_pos;
const rapidjson::Value& bind_pos = skin_data_bone[BINDSHAPE];
for (rapidjson::SizeType j = 0; j < bind_pos.Size(); j++)
{
mat_bind_pos.m[j] = bind_pos[j].GetDouble();
}
skindata->inverseBindPoseMatrices.push_back(mat_bind_pos);
}
// set root bone information
const rapidjson::Value& skin_data_1 = skin_data_array[1];
// parent and child relationship map
skindata->skinBoneOriginMatrices.resize(skindata->skinBoneNames.size());
getChildMap(skindata->boneChild, skindata, skin_data_1);
return true;
}
bool Bundle3D::loadSkinDataBinary(SkinData* skindata)
{
if (!seekToFirstType(BUNDLE_TYPE_MESHSKIN))
return false;
std::string boneName = _binaryReader.readString();
// transform
float bindShape[16];
if (!_binaryReader.readMatrix(bindShape))
{
CCLOG("warning: Failed to read SkinData: bindShape matrix '%s'.", _path.c_str());
return false;
}
// bone count
unsigned int boneNum;
if (!_binaryReader.read(&boneNum))
{
CCLOG("warning: Failed to read SkinData: boneNum '%s'.", _path.c_str());
return false;
}
// Fix bug: check if the bone number is 0.
if (boneNum == 0)
return false;
// bone names and bind pos
float bindpos[16];
for (unsigned int i = 0; i < boneNum; i++)
{
std::string skinBoneName = _binaryReader.readString();
skindata->skinBoneNames.push_back(skinBoneName);
if (!_binaryReader.readMatrix(bindpos))
{
CCLOG("warning: Failed to load SkinData: bindpos '%s'.", _path.c_str());
return false;
}
skindata->inverseBindPoseMatrices.push_back(bindpos);
}
skindata->skinBoneOriginMatrices.resize(boneNum);
boneName = _binaryReader.readString();
// bind shape
_binaryReader.readMatrix(bindShape);
int rootIndex = skindata->getSkinBoneNameIndex(boneName);
if(rootIndex < 0)
{
skindata->addNodeBoneNames(boneName);
rootIndex = skindata->getBoneNameIndex(boneName);
skindata->nodeBoneOriginMatrices.push_back(bindShape);
}
else
{
skindata->skinBoneOriginMatrices[rootIndex] = bindShape;
}
// set root bone index
skindata->rootBoneIndex = rootIndex;
// read parent and child relationship map
float transform[16];
unsigned int linkNum;
_binaryReader.read(&linkNum);
for (unsigned int i = 0; i < linkNum; ++i)
{
std::string id = _binaryReader.readString();
int index = skindata->getSkinBoneNameIndex(id);
std::string parentid = _binaryReader.readString();
if (!_binaryReader.readMatrix(transform))
{
CCLOG("warning: Failed to load SkinData: transform '%s'.", _path.c_str());
return false;
}
if(index < 0)
{
skindata->addNodeBoneNames(id);
index = skindata->getBoneNameIndex(id);
skindata->nodeBoneOriginMatrices.push_back(transform);
}
else
{
skindata->skinBoneOriginMatrices[index] = transform;
}
int parentIndex = skindata->getSkinBoneNameIndex(parentid);
if(parentIndex < 0)
{
skindata->addNodeBoneNames(parentid);
parentIndex = skindata->getBoneNameIndex(parentid);
}
skindata->boneChild[parentIndex].push_back(index);
}
return true;
}
bool Bundle3D::loadMaterialDataJson_0_1(MaterialDatas& materialdatas)
{
if (!_jsonReader.HasMember(MATERIAL))
return false;
NMaterialData materialData;
const rapidjson::Value& material_data_array = _jsonReader[MATERIAL];
if (material_data_array.Size() > 0)
{
const rapidjson::Value& material_data_array_0 = material_data_array[(rapidjson::SizeType)0];
if (material_data_array_0.HasMember(BASE))
{
const rapidjson::Value& material_data_base_array = material_data_array_0[BASE];
const rapidjson::Value& material_data_base_array_0 = material_data_base_array[(rapidjson::SizeType)0];
NTextureData textureData;
// set texture
std::string filename = material_data_base_array_0[FILENAME].GetString();
textureData.filename = filename.empty() ? filename : _modelPath + filename;
textureData.type= NTextureData::Usage::Diffuse;
textureData.id="";
materialData.textures.push_back(textureData);
materialdatas.materials.push_back(materialData);
}
}
return true;
}
bool Bundle3D::loadMaterialDataJson_0_2(MaterialDatas& materialdatas)
{
if (!_jsonReader.HasMember(MATERIAL))
return false;
NMaterialData materialData;
const rapidjson::Value& material_array = _jsonReader[MATERIAL];
for (rapidjson::SizeType i = 0; i < material_array.Size(); i++)
{
NTextureData textureData;
const rapidjson::Value& material_val = material_array[i];
// set texture
std::string filename = material_val[TEXTURES].GetString();
textureData.filename = filename.empty() ? filename : _modelPath + filename;
textureData.type= NTextureData::Usage::Diffuse;
textureData.id="";
materialData.textures.push_back(textureData);
}
materialdatas.materials.push_back(materialData);
return true;
}
bool Bundle3D::loadAnimationDataJson(const std::string& id, Animation3DData* animationdata)
{
std::string anim = "";
if (_version == "1.2" || _version == "0.2")
anim = ANIMATION;
else
anim = ANIMATIONS;
if (!_jsonReader.HasMember(anim.c_str())) return false;
int the_index = -1;
const rapidjson::Value& animation_data_array = _jsonReader[anim.c_str()];
if (animation_data_array.Size()==0) return false;
if(!id.empty())
{
for (rapidjson::SizeType i = 0; i < animation_data_array.Size(); i++)
{
if(animation_data_array[i][ID].GetString() == id)
{
the_index = static_cast<int>(i);
}
}
if(the_index < 0) return false;
}else{
the_index = 0;
}
const rapidjson::Value& animation_data_array_val_0 = animation_data_array[(rapidjson::SizeType)the_index];
animationdata->_totalTime = animation_data_array_val_0[LENGTH].GetDouble();
const rapidjson::Value& bones = animation_data_array_val_0[BONES];
for (rapidjson::SizeType i = 0; i < bones.Size(); i++)
{
const rapidjson::Value& bone = bones[i];
std::string bone_name = bone[BONEID].GetString();
if ( bone.HasMember(KEYFRAMES))
{
const rapidjson::Value& bone_keyframes = bone[KEYFRAMES];
rapidjson::SizeType keyframe_size = bone_keyframes.Size();
animationdata->_rotationKeys[bone_name].reserve(keyframe_size);
animationdata->_scaleKeys[bone_name].reserve(keyframe_size);
animationdata->_translationKeys[bone_name].reserve(keyframe_size);
for (rapidjson::SizeType j = 0; j < keyframe_size; j++)
{
const rapidjson::Value& bone_keyframe = bone_keyframes[j];
if ( bone_keyframe.HasMember(TRANSLATION))
{
const rapidjson::Value& bone_keyframe_translation = bone_keyframe[TRANSLATION];
float keytime = bone_keyframe[KEYTIME].GetDouble();
Vec3 val(bone_keyframe_translation[(rapidjson::SizeType)0].GetDouble(), bone_keyframe_translation[1].GetDouble(), bone_keyframe_translation[2].GetDouble());
animationdata->_translationKeys[bone_name].push_back(Animation3DData::Vec3Key(keytime,val));
}
if ( bone_keyframe.HasMember(ROTATION))
{
const rapidjson::Value& bone_keyframe_rotation = bone_keyframe[ROTATION];
float keytime = bone_keyframe[KEYTIME].GetDouble();
Quaternion val = Quaternion(bone_keyframe_rotation[(rapidjson::SizeType)0].GetDouble(),bone_keyframe_rotation[1].GetDouble(),bone_keyframe_rotation[2].GetDouble(),bone_keyframe_rotation[3].GetDouble());
animationdata->_rotationKeys[bone_name].push_back(Animation3DData::QuatKey(keytime,val));
}
if ( bone_keyframe.HasMember(SCALE))
{
const rapidjson::Value& bone_keyframe_scale = bone_keyframe[SCALE];
float keytime = bone_keyframe[KEYTIME].GetDouble();
Vec3 val(bone_keyframe_scale[(rapidjson::SizeType)0].GetDouble(), bone_keyframe_scale[1].GetDouble(), bone_keyframe_scale[2].GetDouble());
animationdata->_scaleKeys[bone_name].push_back(Animation3DData::Vec3Key(keytime,val));
}
}
}
}
return true;
}
bool Bundle3D::loadAnimationDataBinary(const std::string& id, Animation3DData* animationdata)
{
if( _version == "0.1"|| _version == "0.2" || _version == "0.3"|| _version == "0.4")
{
if (!seekToFirstType(BUNDLE_TYPE_ANIMATIONS))
return false;
}
else
{
// if id is not a null string, we need to add a suffix of "animation" for seeding.
std::string id_ = id;
if(id != "") id_ = id + "animation";
if (!seekToFirstType(BUNDLE_TYPE_ANIMATIONS, id_))
return false;
}
unsigned int animNum = 1;
if( _version == "0.3"|| _version == "0.4")
{
if (!_binaryReader.read(&animNum))
{
CCLOG("warning: Failed to read AnimationData: animNum '%s'.", _path.c_str());
return false;
}
}
bool has_found =false;
for(unsigned int k = 0; k < animNum ; k++ )
{
animationdata->resetData();
std::string animId = _binaryReader.readString();
if (!_binaryReader.read(&animationdata->_totalTime))
{
CCLOG("warning: Failed to read AnimationData: totalTime '%s'.", _path.c_str());
return false;
}
unsigned int nodeAnimationNum;
if (!_binaryReader.read(&nodeAnimationNum))
{
CCLOG("warning: Failed to read AnimationData: animNum '%s'.", _path.c_str());
return false;
}
for (unsigned int i = 0; i < nodeAnimationNum; ++i)
{
std::string boneName = _binaryReader.readString();
unsigned int keyframeNum;
if (!_binaryReader.read(&keyframeNum))
{
CCLOG("warning: Failed to read AnimationData: keyframeNum '%s'.", _path.c_str());
return false;
}
animationdata->_rotationKeys[boneName].reserve(keyframeNum);
animationdata->_scaleKeys[boneName].reserve(keyframeNum);
animationdata->_translationKeys[boneName].reserve(keyframeNum);
for (unsigned int j = 0; j < keyframeNum; ++j)
{
float keytime;
if (!_binaryReader.read(&keytime))
{
CCLOG("warning: Failed to read AnimationData: keytime '%s'.", _path.c_str());
return false;
}
// transform flag
unsigned char transformFlag(0);
if (_version != "0.1" && _version != "0.2" && _version != "0.3")
{
if (!_binaryReader.read(&transformFlag))
{
CCLOG("warning: Failed to read AnimationData: transformFlag '%s'.", _path.c_str());
return false;
}
}
// rotation
bool hasRotate = true;
if (_version != "0.1" && _version != "0.2" && _version != "0.3")
hasRotate = transformFlag & 0x01;
if (hasRotate)
{
Quaternion rotate;
if (_binaryReader.read(&rotate, 4, 4) != 4)
{
CCLOG("warning: Failed to read AnimationData: rotate '%s'.", _path.c_str());
return false;
}
animationdata->_rotationKeys[boneName].push_back(Animation3DData::QuatKey(keytime, rotate));
}
// scale
bool hasScale = true;
if (_version != "0.1" && _version != "0.2" && _version != "0.3")
hasScale = (transformFlag >> 1) & 0x01;
if (hasScale)
{
Vec3 scale;
if (_binaryReader.read(&scale, 4, 3) != 3)
{
CCLOG("warning: Failed to read AnimationData: scale '%s'.", _path.c_str());
return false;
}
animationdata->_scaleKeys[boneName].push_back(Animation3DData::Vec3Key(keytime, scale));
}
// translation
bool hasTranslation = true;
if (_version != "0.1" && _version != "0.2" && _version != "0.3")
hasTranslation = (transformFlag >> 2) & 0x01;
if (hasTranslation)
{
Vec3 position;
if (_binaryReader.read(&position, 4, 3) != 3)
{
CCLOG("warning: Failed to read AnimationData: position '%s'.", _path.c_str());
return false;
}
animationdata->_translationKeys[boneName].push_back(Animation3DData::Vec3Key(keytime, position));
}
}
}
if( id == animId || id.empty())
{
has_found = true;
break;
}
}
if(!has_found)
{
animationdata->resetData();
return false;
}
return true;
}
bool Bundle3D::loadNodesJson(NodeDatas& nodedatas)
{
if (!_jsonReader.HasMember(NODES)) return false;
const rapidjson::Value& nodes = _jsonReader[NODES];
if(!nodes.IsArray()) return false;
// traverse the nodes again
for (rapidjson::SizeType i = 0; i < nodes.Size(); i++)
{
const rapidjson::Value& jnode = nodes[i];
std::string id = jnode[ID].GetString();
NodeData* nodedata = parseNodesRecursivelyJson(jnode, nodes.Size() == 1);
bool isSkeleton = jnode[SKELETON].GetBool();
if (isSkeleton)
nodedatas.skeleton.push_back(nodedata);
else
nodedatas.nodes.push_back(nodedata);
}
return true;
}
NodeData* Bundle3D::parseNodesRecursivelyJson(const rapidjson::Value& jvalue, bool singleSprite)
{
NodeData* nodedata = new (std::nothrow) NodeData();;
// id
nodedata->id = jvalue[ID].GetString();
// transform
Mat4 transform;
const rapidjson::Value& jtransform = jvalue[TRANSFORM];
for (rapidjson::SizeType j = 0; j < jtransform.Size(); j++)
{
transform.m[j] = jtransform[j].GetDouble();
}
nodedata->transform = transform;
bool isSkin = false;
// parts
if (jvalue.HasMember(PARTS))
{
const rapidjson::Value& parts = jvalue[PARTS];
for (rapidjson::SizeType i = 0; i < parts.Size(); i++)
{
auto modelnodedata = new (std::nothrow) ModelData();;
const rapidjson::Value& part = parts[i];
modelnodedata->subMeshId = part[MESHPARTID].GetString();
modelnodedata->matrialId = part[MATERIALID].GetString();
if (modelnodedata->subMeshId == "" || modelnodedata->matrialId == "")
{
CCLOG("warning: Node %s part is missing meshPartId or materialId", nodedata->id.c_str());
CC_SAFE_DELETE(modelnodedata);
CC_SAFE_DELETE(nodedata);
return nullptr;
}
if (part.HasMember(BONES))
{
const rapidjson::Value& bones = part[BONES];
for (rapidjson::SizeType j = 0; j < bones.Size(); j++)
{
const rapidjson::Value& bone = bones[j];
// node
if (!bone.HasMember(NODE))
{
CCLOG("warning: Bone node ID missing");
CC_SAFE_DELETE(modelnodedata);
CC_SAFE_DELETE(nodedata);
return nullptr;
}
modelnodedata->bones.push_back(bone[NODE].GetString());
Mat4 invbindpos;
const rapidjson::Value& jinvbindpos = bone[TRANSFORM];
for (rapidjson::SizeType k = 0; k < jinvbindpos.Size(); k++)
{
invbindpos.m[k] = jinvbindpos[k].GetDouble();
}
//invbindpos.inverse();
modelnodedata->invBindPose.push_back(invbindpos);
}
if (bones.Size() > 0)
isSkin = true;
}
nodedata->modelNodeDatas.push_back(modelnodedata);
}
}
// set transform
if(_version == "0.1" || _version == "0.2" || _version == "0.3" || _version == "0.4" || _version == "0.5" || _version == "0.6")
{
if(isSkin || singleSprite)
{
nodedata->transform = Mat4::IDENTITY;
}
else
{
nodedata->transform = transform;
}
}
else
{
nodedata->transform = transform;
}
if (jvalue.HasMember(CHILDREN))
{
const rapidjson::Value& children = jvalue[CHILDREN];
for (rapidjson::SizeType i = 0; i < children.Size(); i++)
{
const rapidjson::Value& child = children[i];
NodeData* tempdata = parseNodesRecursivelyJson(child, singleSprite);
nodedata->children.push_back(tempdata);
}
}
return nodedata;
}
bool Bundle3D::loadNodesBinary(NodeDatas& nodedatas)
{
if (!seekToFirstType(BUNDLE_TYPE_NODE))
return false;
unsigned int nodeSize = 0;
if (_binaryReader.read(&nodeSize, 4, 1) != 1)
{
CCLOG("warning: Failed to read nodes");
return false;
}
// traverse the nodes again
for (rapidjson::SizeType i = 0; i < nodeSize; i++)
{
bool skeleton = false;
NodeData* nodedata = parseNodesRecursivelyBinary(skeleton, nodeSize == 1);
if (skeleton)
nodedatas.skeleton.push_back(nodedata);
else
nodedatas.nodes.push_back(nodedata);
}
return true;
}
NodeData* Bundle3D::parseNodesRecursivelyBinary(bool& skeleton, bool singleSprite)
{
// id
std::string id = _binaryReader.readString();
// is skeleton
bool skeleton_;
if (_binaryReader.read(&skeleton_, 1, 1) != 1)
{
CCLOG("warning: Failed to read is skeleton");
return nullptr;
}
if (skeleton_)
skeleton = true;
// transform
Mat4 transform;
if (!_binaryReader.readMatrix(transform.m))
{
CCLOG("warning: Failed to read transform matrix");
return nullptr;
}
// parts
unsigned int partsSize = 0;
if (_binaryReader.read(&partsSize, 4, 1) != 1)
{
CCLOG("warning: Failed to read meshdata: attribCount '%s'.", _path.c_str());
return nullptr;
}
NodeData* nodedata = new (std::nothrow) NodeData();
nodedata->id = id;
bool isSkin = false;
if (partsSize > 0)
{
for (unsigned int i = 0; i < partsSize; i++)
{
auto modelnodedata = new (std::nothrow) ModelData();
modelnodedata->subMeshId = _binaryReader.readString();
modelnodedata->matrialId = _binaryReader.readString();
if (modelnodedata->subMeshId == "" || modelnodedata->matrialId == "")
{
std::string err = "Node " + nodedata->id + " part is missing meshPartId or materialId";
CCLOG("Node %s part is missing meshPartId or materialId", nodedata->id.c_str());
CC_SAFE_DELETE(modelnodedata);
CC_SAFE_DELETE(nodedata);
return nullptr;
}
// read bone
unsigned int bonesSize = 0;
if (_binaryReader.read(&bonesSize, 4, 1) != 1)
{
CCLOG("warning: Failed to read meshdata: attribCount '%s'.", _path.c_str());
CC_SAFE_DELETE(modelnodedata);
CC_SAFE_DELETE(nodedata);
return nullptr;
}
if (bonesSize > 0)
{
for (unsigned int j = 0; j < bonesSize; j++)
{
std::string name = _binaryReader.readString();
modelnodedata->bones.push_back(name);
Mat4 invbindpos;
if (!_binaryReader.readMatrix(invbindpos.m))
{
CC_SAFE_DELETE(modelnodedata);
CC_SAFE_DELETE(nodedata);
return nullptr;
}
modelnodedata->invBindPose.push_back(invbindpos);
}
isSkin = true;
}
unsigned int uvMapping = 0;
if (_binaryReader.read(&uvMapping, 4, 1) != 1)
{
CCLOG("warning: Failed to read nodedata: uvMapping '%s'.", _path.c_str());
CC_SAFE_DELETE(modelnodedata);
CC_SAFE_DELETE(nodedata);
return nullptr;
}
for(unsigned int j = 0; j < uvMapping; j++)
{
unsigned int textureIndexSize=0;
if (_binaryReader.read(&textureIndexSize, 4, 1) != 1)
{
CCLOG("warning: Failed to read meshdata: attribCount '%s'.", _path.c_str());
CC_SAFE_DELETE(modelnodedata);
CC_SAFE_DELETE(nodedata);
return nullptr;
}
for(unsigned int k = 0; k < textureIndexSize; k++)
{
unsigned int index=0;
if (_binaryReader.read(&index, 4, 1) != 1)
{
CC_SAFE_DELETE(modelnodedata);
CC_SAFE_DELETE(nodedata);
return nullptr;
}
}
}
nodedata->modelNodeDatas.push_back(modelnodedata);
}
}
// set transform
if(_version == "0.1" || _version == "0.2" || _version == "0.3" || _version == "0.4" || _version == "0.5" || _version == "0.6")
{
if(isSkin || singleSprite)
{
nodedata->transform = Mat4::IDENTITY;
}
else
{
nodedata->transform = transform;
}
}
else
{
nodedata->transform = transform;
}
unsigned int childrenSize = 0;
if (_binaryReader.read(&childrenSize, 4, 1) != 1)
{
CCLOG("warning: Failed to read meshdata: attribCount '%s'.", _path.c_str());
CC_SAFE_DELETE(nodedata);
return nullptr;
}
if (childrenSize > 0)
{
for (unsigned int i = 0; i < childrenSize; i++)
{
NodeData* tempdata = parseNodesRecursivelyBinary(skeleton, singleSprite);
nodedata->children.push_back(tempdata);
}
}
return nodedata;
}
GLenum Bundle3D::parseGLType(const std::string& str)
{
if (str == "GL_BYTE")
{
return GL_BYTE;
}
else if(str == "GL_UNSIGNED_BYTE")
{
return GL_UNSIGNED_BYTE;
}
else if(str == "GL_SHORT")
{
return GL_SHORT;
}
else if(str == "GL_UNSIGNED_SHORT")
{
return GL_UNSIGNED_SHORT;
}
else if(str == "GL_INT")
{
return GL_INT;
}
else if (str == "GL_UNSIGNED_INT")
{
return GL_UNSIGNED_INT;
}
else if (str == "GL_FLOAT")
{
return GL_FLOAT;
}
else if (str == "REPEAT")
{
return GL_REPEAT;
}
else if (str == "CLAMP")
{
return GL_CLAMP_TO_EDGE;
}
else
{
CCASSERT(false, "Invalid GL type");
return 0;
}
}
NTextureData::Usage Bundle3D::parseGLTextureType(const std::string& str)
{
if (str == "AMBIENT")
{
return NTextureData::Usage::Ambient;
}
else if(str == "BUMP")
{
return NTextureData::Usage::Bump;
}
else if(str == "DIFFUSE")
{
return NTextureData::Usage::Diffuse;
}
else if(str == "EMISSIVE")
{
return NTextureData::Usage::Emissive;
}
else if(str == "NONE")
{
return NTextureData::Usage::None;
}
else if (str == "NORMAL")
{
return NTextureData::Usage::Normal;
}
else if (str == "REFLECTION")
{
return NTextureData::Usage::Reflection;
}
else if (str == "SHININESS")
{
return NTextureData::Usage::Shininess;
}
else if (str == "SPECULAR")
{
return NTextureData::Usage::Specular;
}
else if (str == "TRANSPARENCY")
{
return NTextureData::Usage::Transparency;
}
else
{
CCASSERT(false, "Wrong Texture type");
return NTextureData::Usage::Unknown;
}
}
unsigned int Bundle3D::parseGLProgramAttribute(const std::string& str)
{
if (str == "VERTEX_ATTRIB_POSITION")
{
return GLProgram::VERTEX_ATTRIB_POSITION;
}
else if (str == "VERTEX_ATTRIB_COLOR")
{
return GLProgram::VERTEX_ATTRIB_COLOR;
}
else if (str == "VERTEX_ATTRIB_TEX_COORD")
{
return GLProgram::VERTEX_ATTRIB_TEX_COORD;
}
else if (str == "VERTEX_ATTRIB_TEX_COORD1")
{
return GLProgram::VERTEX_ATTRIB_TEX_COORD1;
}
else if (str == "VERTEX_ATTRIB_TEX_COORD2")
{
return GLProgram::VERTEX_ATTRIB_TEX_COORD2;
}
else if (str == "VERTEX_ATTRIB_TEX_COORD3")
{
return GLProgram::VERTEX_ATTRIB_TEX_COORD3;
}
//comment out them
// else if (str == "VERTEX_ATTRIB_TEX_COORD4")
// {
// return GLProgram::VERTEX_ATTRIB_TEX_COORD4;
// }
// else if (str == "VERTEX_ATTRIB_TEX_COORD5")
// {
// return GLProgram::VERTEX_ATTRIB_TEX_COORD5;
// }
// else if (str == "VERTEX_ATTRIB_TEX_COORD6")
// {
// return GLProgram::VERTEX_ATTRIB_TEX_COORD6;
// }
// else if (str == "VERTEX_ATTRIB_TEX_COORD7")
// {
// return GLProgram::VERTEX_ATTRIB_TEX_COORD7;
// }
else if (str == "VERTEX_ATTRIB_NORMAL")
{
return GLProgram::VERTEX_ATTRIB_NORMAL;
}
else if (str == "VERTEX_ATTRIB_BLEND_WEIGHT")
{
return GLProgram::VERTEX_ATTRIB_BLEND_WEIGHT;
}
else if (str == "VERTEX_ATTRIB_BLEND_INDEX")
{
return GLProgram::VERTEX_ATTRIB_BLEND_INDEX;
}
else if (str == "VERTEX_ATTRIB_TANGENT")
{
return GLProgram::VERTEX_ATTRIB_TANGENT;
}
else if (str == "VERTEX_ATTRIB_BINORMAL")
{
return GLProgram::VERTEX_ATTRIB_BINORMAL;
}
else
{
CCASSERT(false, "Wrong Attribute type");
return -1;
}
}
void Bundle3D::getModelRelativePath(const std::string& path)
{
ssize_t index = path.find_last_of('/');
std::string fullModelPath;
_modelPath = path.substr(0, index + 1);
}
Reference* Bundle3D::seekToFirstType(unsigned int type, const std::string& id)
{
// for each Reference
for (unsigned int i = 0; i < _referenceCount; ++i)
{
Reference* ref = &_references[i];
if (ref->type == type)
{
// if id is not a null string, we also need to check the Reference's id.
if (id != "" && id != ref->id)
{
continue;
}
// Found a match
if (_binaryReader.seek(ref->offset, SEEK_SET) == false)
{
CCLOG("warning: Failed to seek to object '%s' in bundle '%s'.", ref->id.c_str(), _path.c_str());
return nullptr;
}
return ref;
}
}
return nullptr;
}
std::vector<Vec3> Bundle3D::getTrianglesList(const std::string& path)
{
std::vector<Vec3> trianglesList;
if (path.length() <= 4)
return trianglesList;
auto bundle = Bundle3D::createBundle();
std::string ext = FileUtils::getInstance()->getFileExtension(path);
MeshDatas meshs;
if (ext == ".obj")
{
MaterialDatas materials;
NodeDatas nodes;
if (!Bundle3D::loadObj(meshs, materials, nodes, path))
{
Bundle3D::destroyBundle(bundle);
return trianglesList;
}
}
else
{
if (!bundle->load(path))
{
Bundle3D::destroyBundle(bundle);
return trianglesList;
}
bundle->loadMeshDatas(meshs);
}
Bundle3D::destroyBundle(bundle);
for (auto iter : meshs.meshDatas){
int preVertexSize = iter->getPerVertexSize() / sizeof(float);
for (auto indexArray : iter->subMeshIndices){
for (auto i : indexArray){
trianglesList.push_back(Vec3(iter->vertex[i * preVertexSize], iter->vertex[i * preVertexSize + 1], iter->vertex[i * preVertexSize + 2]));
}
}
}
return trianglesList;
}
Bundle3D::Bundle3D()
: _modelPath(""),
_path(""),
_version(""),
_jsonBuffer(nullptr),
_binaryBuffer(nullptr),
_referenceCount(0),
_references(nullptr),
_isBinary(false)
{
}
Bundle3D::~Bundle3D()
{
clear();
}
cocos2d::AABB Bundle3D::calculateAABB( const std::vector<float>& vertex, int stride, const std::vector<unsigned short>& index )
{
AABB aabb;
stride /= 4;
for (const auto& it : index)
{
Vec3 point(vertex[it * stride], vertex[it * stride + 1], vertex[it * stride + 2]);
aabb.updateMinMax(&point, 1);
}
return aabb;
}
NS_CC_END
| {
"pile_set_name": "Github"
} |
package com.hry.spring.spel.multiway.xml;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 通过注解使用Spring EL
*
* @author hry
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes=SpELXmlApplication.class)
public class SpELAnnotationExampleTest {
@Autowired
private SpELXMLExample spELXMLExample;
@Test
public void println(){
System.out.println(spELXMLExample.toString());
}
}
| {
"pile_set_name": "Github"
} |
import string;
import behaviour;
import runtime;
import ds/tree;
import math/geometry;
// This is a variant of behaviours where transforms are "distinct" and the transform
// functions can be fused together. Things are guaranteed to be leak free when you
// only use these functions and remember to free the result from "fuse" which instantiates
// the transform into a real behaviour.
export {
// Example: fselect(b, FLift(\bv -> whatever));
// fselect and friends are distinct for output value.
fselect : (b : Transform<??>, fn : FFn<??, ?>) -> Transform<?>;
fselect2 : (b1 : Transform<??>, b2 : Transform<???>, fn : FFn2<??, ???, ?>) -> Transform<?>;
fselect3(v1 : Transform<??>, v2 : Transform<???>, v3 : Transform<????>, fn : (??, ???, ????) -> ?) -> Transform<?>;
fselect4(v1 : Transform<??>, v2 : Transform<???>, v3 : Transform<????>, v4 : Transform<?????>, fn : (??, ???, ????, ?????) -> ?) -> Transform<?>;
fselect5(v1 : Transform<??>, v2 : Transform<???>, v3 : Transform<????>, v4 : Transform<?????>, v5 : Transform<??????>,
fn : (??, ???, ????, ?????, ??????) -> ?) -> Transform<?>;
fselect6(v1 : Transform<??>, v2 : Transform<???>, v3 : Transform<????>, v4 : Transform<?????>, v5 : Transform<??????>, v6 : Transform<???????>,
fn : (??, ???, ????, ?????, ??????, ???????) -> ?) -> Transform<?>;
fselect7(v1 : Transform<??>, v2 : Transform<???>, v3 : Transform<????>, v4 : Transform<?????>, v5 : Transform<??????>, v6 : Transform<???????>,
v7 : Transform<????????>, fn : (??, ???, ????, ?????, ??????, ???????, ????????) -> ?) -> Transform<?>;
fselect8(v1 : Transform<??>, v2 : Transform<???>, v3 : Transform<????>, v4 : Transform<?????>, v5 : Transform<??????>, v6 : Transform<???????>,
v7 : Transform<????????>, v8 : Transform<?????????>, fn : (??, ???, ????, ?????, ??????, ???????, ????????, ?????????) -> ?) -> Transform<?>;
fselect9(v1 : Transform<??>, v2 : Transform<???>, v3 : Transform<????>, v4 : Transform<?????>, v5 : Transform<??????>, v6 : Transform<???????>,
v7 : Transform<????????>, v8 : Transform<?????????>, v9 : Transform<??????????>,
fn : (??, ???, ????, ?????, ??????, ???????, ????????, ?????????, ??????????) -> ?) -> Transform<?>;
fsubselect : (b : Transform<??>, fn : FFn<??, Transform<?>>) -> Transform<?>;
fsubselect2 : (b1 : Transform<??>, b2 : Transform<???>, fn : (??, ???) -> Transform<?>) -> Transform<?>;
fsubselect3 : (b1 : Transform<??>, b2 : Transform<???>, b3 : Transform<????>, fn : (??, ???, ????) -> Transform<?>) -> Transform<?>;
// disposer is called after last unsubcription from b Transform
fdisposable(b : Transform<?>, disposer : () -> void) -> Transform<?>;
fconstructable(b : Transform<?>, constructor : () -> () -> void) -> Transform<?>;
// Converts a Transform to a Behaviour, along with any unsubscribers
fuse(t : Transform<?>) -> Pair<Behaviour<?>, [() -> void]>;
// Uses init as additional layer to prevent multiple Transform function calls. Do not forget use fguard.second into MConstruct.
// If t is Behaviour itself, just returns it.
fguard(t : Transform<?>, init : DynamicBehaviour<?>) -> Pair<Behaviour<?>, () -> () -> void>;
fsubscribe(t : Transform<?>, fn : (?) -> void) -> List<() -> void>;
fsubscribe2(t : Transform<?>, fn : (?) -> void) -> List<() -> void>;
// Same as when in transforms.flow
fwhen(t : Transform<bool>, fn : () -> void) -> () -> void;
// Helpers for fsubscribe that returns () -> void disposer when called.
// These guys are distinctive, so f will not fire on updating v with the same value.
makeSubscribe(v : Transform<?>, f : (?) -> void) -> () -> () -> void;
makeSubscribe2(v : Transform<?>, f : (?) -> void) -> () -> () -> void;
make2Subscribe(v1 : Transform<?>, v2 : Transform<??>, f : (?, ??) -> void) -> () -> () -> void;
make2Subscribe2(v1 : Transform<?>, v2 : Transform<??>, f : (?, ??) -> void) -> () -> () -> void;
make3Subscribe(v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, f : (?, ??, ???) -> void) -> () -> () -> void;
make3Subscribe2(v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, f : (?, ??, ???) -> void) -> () -> () -> void;
make4Subscribe(v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>,
f : (?, ??, ???, ????) -> void) -> () -> () -> void;
make4Subscribe2(v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>,
f : (?, ??, ???, ????) -> void) -> () -> () -> void;
make5Subscribe(v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>, v5 : Transform<?????>,
f : (?, ??, ???, ????, ?????) -> void) -> () -> () -> void;
make5Subscribe2(v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>, v5 : Transform<?????>,
f : (?, ??, ???, ????, ?????) -> void) -> () -> () -> void;
// Same as makeSubscribes only you return an array of disposers which are disposed every time transform changes
makeSubscribeUns(v : Transform<?>, f : (?) -> [() -> void]) -> () -> () -> void;
makeSubscribeUnsTimer(v : Transform<?>, ms : int, f : (?) -> [() -> void]) -> () -> () -> void;
makeSubscribe2Uns(v : Transform<?>, f : (?) -> [() -> void]) -> () -> () -> void;
makeSubscribe2UnsTimer(v : Transform<?>, ms : int, f : (?) -> [() -> void]) -> () -> () -> void;
make2SubscribeUns(v1 : Transform<?>, v2 : Transform<??>, f : (?, ??) -> [() -> void]) -> () -> () -> void;
make2Subscribe2Uns(v1 : Transform<?>, v2 : Transform<??>, f : (?, ??) -> [() -> void]) -> () -> () -> void;
// Same as makeSubscribes only you pass a trigger which enables or disables this subscription
// Useful when you have to watch complex transforms, but need to handle them only when some expression is true
makeSubscribeTrigger(trigger : Transform<bool>, v : Transform<?>, f : (?) -> void) -> () -> () -> void;
makeSubscribe2Trigger(trigger : Transform<bool>, v : Transform<?>, f : (?) -> void) -> () -> () -> void;
make2SubscribeTrigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, f : (?, ??) -> void) -> () -> () -> void;
make2Subscribe2Trigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, f : (?, ??) -> void) -> () -> () -> void;
make3SubscribeTrigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>,
f : (?, ??, ???) -> void) -> () -> () -> void;
make3Subscribe2Trigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>,
f : (?, ??, ???) -> void) -> () -> () -> void;
make4SubscribeTrigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>,
f : (?, ??, ???, ????) -> void) -> () -> () -> void;
make4Subscribe2Trigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>,
f : (?, ??, ???, ????) -> void) -> () -> () -> void;
make5SubscribeTrigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>,
v5 : Transform<?????>, f : (?, ??, ???, ????, ?????) -> void) -> () -> () -> void;
make5Subscribe2Trigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>,
v5 : Transform<?????>, f : (?, ??, ???, ????, ?????) -> void) -> () -> () -> void;
makeSubscribeDelayedDispose(t : Transform<?>, delay : int, fn : (?) -> void) -> () -> () -> void;
// Helpers for ref unsubscribers disposal
dispUns(uns : ref () -> void) -> void;
dispUns2(uns : ref Maybe<() -> void>) -> void;
dispUnsA(uns : ref [() -> void]) -> void;
dispUnsTree(uns : ref Tree<?, () -> void>, key : ?) -> void;
// Relatively expensive if Transform has no subscribers
fgetValue(t : Transform<?>) -> ?;
// Extract all dynamic behaviours from the transform
fgetDynamicBehaviours(t : Transform<?>) -> [DynamicBehaviour];
// Check if transform has any dynamic behaviours
isFConst(t : Transform<?>) -> bool;
// Do not construct FSelect and friends directly - use the functions above instead.
Transform<?> ::= ConstBehaviour<?>, DynamicBehaviour<?>, FSelect<?>, FSelect2<?>, FSubSelect<?>,
// To ensure that behaviour is a subtype, we explicitly list it as well
Behaviour<?>, FConstructable<?>;
// Common functions. Use FLift for other functions
faddition(b1 : Transform<double>, b2 : Transform<double>) -> Transform<double>;
fsubtract(b1 : Transform<double>, b2 : Transform<double>) -> Transform<double>;
fmultiply(b1 : Transform<double>, b2 : Transform<double>) -> Transform<double>;
fadditioni(b1 : Transform<int>, b2 : Transform<int>) -> Transform<int>;
fsubtracti(b1 : Transform<int>, b2 : Transform<int>) -> Transform<int>;
fmultiplyi(b1 : Transform<int>, b2 : Transform<int>) -> Transform<int>;
fgreater(b1 : Transform<double>, b2 : Transform<double>) -> Transform<bool>;
fless(b1 : Transform<double>, b2 : Transform<double>) -> Transform<bool>;
fgreateri(b1 : Transform<int>, b2 : Transform<int>) -> Transform<bool>;
flessi(b1 : Transform<int>, b2 : Transform<int>) -> Transform<bool>;
// If b2 is 0, then the result is 0
fdivide(b1 : Transform<double>, b2 : Transform<double>) -> Transform<double>;
fnegate(b1 : Transform<double>) -> Transform<double>;
fdividei(b1 : Transform<int>, b2 : Transform<int>) -> Transform<int>;
fnegatei(b1 : Transform<int>) -> Transform<int>;
fmax(b1 : Transform<?>, b2 : Transform<?>) -> Transform<?>; // For bools, this is OR
fmin(b1 : Transform<?>, b2 : Transform<?>) -> Transform<?>; // For bools, this is AND
fmax3(b1 : Transform<?>, b2 : Transform<?>, b3 : Transform<?>) -> Transform<?>; // For bools, this is OR
fmin3(b1 : Transform<?>, b2 : Transform<?>, b3 : Transform<?>) -> Transform<?>; // For bools, this is AND
fmaxA(v : [Transform<?>], def : ?) -> Transform<?>;
fminA(v : [Transform<?>], def : ?) -> Transform<?>;
farray(v1 : Transform<?>) -> Transform<[?]>;
fconcat(v1 : Transform<[?]>, v2 : Transform<[?]>) -> Transform<[?]>;
farrayPush(v1 : Transform<[?]>, v2 : Transform<?>) -> Transform<[?]>;
fconcatA(v : Transform<[[?]]>) -> Transform<[?]>;
fcontains(v1 : Transform<[?]>, v2 : Transform<?>) -> Transform<bool>;
fcompose(f1 : FFn<flow, ??>, f2 : FFn<?, flow>) -> FFn<?, ??>;
fif(b1 : Transform<bool>, then1 : Transform<?>, else1 : Transform<?>) -> Transform<?>;
feq(b : Transform<?>, v : ?) -> Transform<bool>;
fneq(a : Transform<?>, v : ?) -> Transform<bool>;
fequal(a : Transform<?>, b : Transform<?>) -> Transform<bool>;
fnotequal(a : Transform<?>, b : Transform<?>) -> Transform<bool>;
fnot(b : Transform<bool>) -> Transform<bool>;
fand(a : Transform<bool>, b : Transform<bool>) -> Transform<bool>;
fOr(a : Transform<bool>, b : Transform<bool>) -> Transform<bool>;
fxor(a : Transform<bool>, b : Transform<bool>) -> Transform<bool>;
fabs(a : Transform<double>) -> Transform<double>;
fpair(v1 : Transform<?>, v2 : Transform<??>) -> Transform<Pair<?, ??>>;
// ftriple -> see fusion_utils.flow
// fquadruple -> see fusion_utils.flow
fwidthheight(wd : Transform<double>, hgt : Transform<double>) -> Transform<WidthHeight>;
fwh(wd : Transform<double>, hgt : Transform<double>) -> Transform<WidthHeight> { fwidthheight(wd, hgt); };
fpoint(x : Transform<double>, y : Transform<double>) -> Transform<Point>;
fpointX(point : Transform<Point>) -> Transform<double>;
fpointY(point : Transform<Point>) -> Transform<double>;
ffactor(x : Transform<double>, y : Transform<double>) -> Transform<Factor>;
ffactor2(f : Transform<double>) -> Transform<Factor>;
ffactorX(factor : Transform<Factor>) -> Transform<double>;
ffactorY(factor : Transform<Factor>) -> Transform<double>;
fwidth(wh : Transform<WidthHeight>) -> Transform<double>;
fheight(wh : Transform<WidthHeight>) -> Transform<double>;
fconnect(v1 : Transform<?>, v2 : DynamicBehaviour<?>) -> () -> void;
fconnectSelect(v1 : Transform<?>, v2 : DynamicBehaviour<??>, fn : (?) -> ??) -> () -> void;
fconnect2Select(t1 : Transform<?>, t2 : Transform<??>, v : DynamicBehaviour<???>, fn : (?, ??) -> ???) -> () -> void;
fmerge(v : [Transform<?>]) -> Transform<[?]>;
fmergeTree(v : Tree<??, Transform<?>>) -> Transform<Tree<??, ?>>;
fsum(v : [Transform<double>]) -> Transform<double>;
fsumi(v : [Transform<int>]) -> Transform<int>;
faverage(a : [Transform<double>]) -> Transform<double>;
ftransistor(g : Transform<bool>, v: Transform<?>) -> Transform<?>;
fthrottle(v : Transform<?>, samplingRate : int) -> Transform<?>;
fthrottle2(v : Transform<?>, maxDelta : int) -> Transform<?>;
fthrottleNextFrame(v : Transform<?>) -> Transform<?>;
fthrottle2NextFrame(v : Transform<?>) -> Transform<?>;
fselectWithLast(b : Transform<??>, fn : FFn2<??, ??, ?>) -> Transform<?>;
fdelay(v : Transform<?>, ms : int) -> Transform<?>;
fstall(v : Transform<?>, ms : int) -> Transform<?>;
fBidirectionalLink(v1 : Transform<?>, v2 : Transform<??>, fn1 : (?) -> void, fn2 : (??) -> void) -> () -> void;
// This instantiates a FFn to a real function, performing fusion
instantiateFn(f : FFn<?, ??>) -> (?) -> ??;
instantiateFn2(fn : FFn2<?, ??, ???>) -> (?, ??) -> ???;
// For debugging
transform2string(s : Transform<?>) -> string;
// Builtin functions - use the functions above instead
FFn<?, ??> ::= FLift<?, ??>, FCompose<?, ??>, FIdentity, FNegate,
FAddConst, FMulConst, FMaxConst, FMinConst, FEqual, FIf<??>;
// This is for using any other transform function
FLift(fn : (?) -> ??);
FAddConst(c : double);
FMulConst(c : double);
FMaxConst(c : ?);
FMinConst(c : ?);
FIf(then : ?, else_ : ?);
// Trivial function
FIdentity();
FFn2<?, ??, ???> ::= FLift2<?, ??, ???>, FIdentity2, FAddition, FSubtract,
FMultiply, FDivide, FMax, FMin,
FusionAnd, FusionOr, FusionXor, FusionWidthHeight;
// This is for using any other transform function
FLift2(fn : (?, ??) -> ???);
FMax();
FMin();
FIdentity2();
// f1 o f2 == f1(f2(x))
FCompose(f1 : FFn<flow, ??>, f2 : FFn<?, flow>);
FAddition();
FSubtract();
FMultiply();
FDivide();
FNegate();
FEqual(v : ?);
FusionAnd();
FusionOr();
FusionXor();
FusionWidthHeight();
}
FBehaviour<?> ::= FDestroyed, FInitialized<?>;
FInitialized(subs : ref int, disp : () -> void, dyn : DynamicBehaviour<?>);
FDestroyed();
// These guys use flow to make sure the Transform union only has one polymorphic variable.
// Since we use the helpers fselect, fselect2, fsubselect, we will inductively get the
// necessary type guarantees anyways.
FSelect(b : Transform<flow>, fn : FFn<flow, ?>, mutable beh : FBehaviour<?>);
FSelect2(b1 : Transform<flow>, b2 : Transform<flow>, fn : FFn2<flow, flow, ?>, mutable beh : FBehaviour<?>);
FSubSelect(b : Transform<flow>, fn : FFn<flow, Transform<?>>, mutable beh : FBehaviour<?>);
FConstructable(b : Transform<?>, constructor : () -> () -> void, mutable beh : FBehaviour<?>);
fselect(b : Transform<??>, fn : FFn<??, ?>) -> Transform<?> {
switch (b : Transform<??>) {
ConstBehaviour(v): ConstBehaviour(instantiateFn(fn)(v));
FSelect(nb, fn2, __): {
// select(select(a, f2), f1) = select(a, f1 o f2)
// OK, try to compose them. If it helps resolve anything, then do it.
// Notice that this composition might unmask useful stop changes from the first behaviour
// that map to the same second value.
c = fcompose(fn, fn2);
switch (c) {
FCompose(__, __): FSelect(b, fn, FDestroyed()); // Turns out there was no benefit, so don't do it!
default: FSelect(nb, c, FDestroyed());
}
}
default: {
FSelect(b, fn, FDestroyed());
}
}
}
fselect2(b1 : Transform<??>, b2 : Transform<???>, fn : FFn2<??, ???, ?>) -> Transform<?> {
t = FSelect2(b1, b2, fn, FDestroyed());
switch (b1 : Transform<??>) {
ConstBehaviour(v1): {
ifn = instantiateFn2(fn);
switch (b2 : Transform<???>) {
ConstBehaviour(v2): ConstBehaviour(ifn(v1, v2));
default: fselect(b2, FLift(\v -> ifn(v1, v)));
}
}
FSelect(nb1, nf1, __): {
ifn = instantiateFn2(fn);
switch (b2 : Transform<???>) {
FSelect(nb2, nf2, __): {
ifn1 = instantiateFn(nf1);
ifn2 = instantiateFn(nf2);
FSelect2(nb1, nb2, FLift2(\f, s -> ifn(ifn1(f), ifn2(s))), FDestroyed());
}
default: {
ifn1 = instantiateFn(nf1);
FSelect2(nb1, b2, FLift2(\f, s -> ifn(ifn1(f), s)), FDestroyed());
}
}
}
default: {
switch (b2 : Transform<???>) {
ConstBehaviour(v2): {
ifn = instantiateFn2(fn);
fselect(b1, FLift(\v -> ifn(v, v2)));
}
FSelect(nb, nf2, __): {
ifn = instantiateFn2(fn);
ifn2 = instantiateFn(nf2);
FSelect2(b1, nb, FLift2(\f, s -> ifn(f, ifn2(s))), FDestroyed());
}
default: {
FSelect2(b1, b2, fn, FDestroyed());
}
}
}
}
}
fsubselect(b : Transform<??>, fn : FFn<??, Transform<?>>) -> Transform<?> {
switch (b) {
ConstBehaviour(v): {
instantiateFn(fn)(v);
}
FSelect(a, f2, __): {
c = fcompose(fn, f2);
switch (c) {
FCompose(cf1, cf2): FSubSelect(b, fn, FDestroyed());
default: fsubselect(a, c);
}
}
default: FSubSelect(b, fn, FDestroyed());
}
}
fdisposable(b : Transform<?>, disposer : () -> void) -> Transform<?> {
switch (b) {
ConstBehaviour(v): b;
default: FConstructable(b, \ -> disposer, FDestroyed());
}
}
fconstructable(b : Transform<?>, constructor : () -> () -> void) -> Transform<?> {
switch (b) {
ConstBehaviour(v): b;
default: FConstructable(b, constructor, FDestroyed());
}
}
fselect3(v1 : Transform<??>, v2 : Transform<???>, v3 : Transform<????>, fn : (??, ???, ????) -> ?) -> Transform<?> {
fselect2(fpair(v1, v2), v3, FLift2(\vv12 : Pair<??, ???>, vv3 : ???? ->
fn(firstOfPair(vv12), secondOfPair(vv12), vv3))
)
}
fselect4(v1 : Transform<??>, v2 : Transform<???>, v3 : Transform<????>, v4 : Transform<?????>, fn : (??, ???, ????, ?????) -> ?) -> Transform<?> {
fselect2(fpair(v1, v2), fpair(v3, v4), FLift2(\vv12 : Pair<??, ???>, vv34 : Pair<????, ?????> ->
fn(firstOfPair(vv12), secondOfPair(vv12), firstOfPair(vv34), secondOfPair(vv34)))
)
}
fselect5(v1 : Transform<??>, v2 : Transform<???>, v3 : Transform<????>, v4 : Transform<?????>, v5 : Transform<??????>,
fn : (??, ???, ????, ?????, ??????) -> ?) -> Transform<?> {
fselect2(fpair(fpair(v1, v2), fpair(v3, v4)), v5, FLift2(\vv1234 : Pair<Pair<??, ???>, Pair<????, ?????>>, vv5 : ?????? ->
fn(vv1234.first.first, vv1234.first.second, vv1234.second.first, vv1234.second.second, vv5))
)
}
fselect6(
v1 : Transform<??>,
v2 : Transform<???>,
v3 : Transform<????>,
v4 : Transform<?????>,
v5 : Transform<??????>,
v6 : Transform<???????>,
fn : (??, ???, ????, ?????, ??????, ???????) -> ?
) -> Transform<?> {
fselect2(fpair(fpair(v1, v2), fpair(v3, v4)), fpair(v5, v6),
FLift2(\vv1234 : Pair<Pair<??, ???>, Pair<????, ?????>>, vv56 : Pair<??????, ???????> ->
fn(vv1234.first.first, vv1234.first.second, vv1234.second.first, vv1234.second.second, vv56.first, vv56.second)
)
)
}
fselect7(
v1 : Transform<??>,
v2 : Transform<???>,
v3 : Transform<????>,
v4 : Transform<?????>,
v5 : Transform<??????>,
v6 : Transform<???????>,
v7 : Transform<????????>,
fn : (??, ???, ????, ?????, ??????, ???????, ????????) -> ?
) -> Transform<?> {
fselect2(fpair(fpair(v1, v2), fpair(v3, v4)), fpair(fpair(v5, v6), v7),
FLift2(\vv1234 : Pair<Pair<??, ???>, Pair<????, ?????>>, vv567 : Pair<Pair<??????, ???????>, ????????> ->
fn(vv1234.first.first, vv1234.first.second, vv1234.second.first, vv1234.second.second,
vv567.first.first, vv567.first.second, vv567.second)
)
)
}
fselect8(
v1 : Transform<??>,
v2 : Transform<???>,
v3 : Transform<????>,
v4 : Transform<?????>,
v5 : Transform<??????>,
v6 : Transform<???????>,
v7 : Transform<????????>,
v8 : Transform<?????????>,
fn : (??, ???, ????, ?????, ??????, ???????, ????????, ?????????) -> ?
) -> Transform<?> {
fselect2(fpair(fpair(v1, v2), fpair(v3, v4)), fpair(fpair(v5, v6), fpair(v7, v8)),
FLift2(\vv1234 : Pair<Pair<??, ???>, Pair<????, ?????>>, vv5678 : Pair<Pair<??????, ???????>, Pair<????????, ?????????>> ->
fn(vv1234.first.first, vv1234.first.second, vv1234.second.first, vv1234.second.second,
vv5678.first.first, vv5678.first.second, vv5678.second.first, vv5678.second.second)
)
)
}
fselect9(
v1 : Transform<??>,
v2 : Transform<???>,
v3 : Transform<????>,
v4 : Transform<?????>,
v5 : Transform<??????>,
v6 : Transform<???????>,
v7 : Transform<????????>,
v8 : Transform<?????????>,
v9 : Transform<??????????>,
fn : (??, ???, ????, ?????, ??????, ???????, ????????, ?????????, ??????????) -> ?
) -> Transform<?> {
fselect2(fpair(fpair(v1, v2), fpair(v3, v4)), fpair(fpair(v5, v6), fpair(v7, fpair(v8, v9))),
FLift2(\vv1234 : Pair<Pair<??, ???>, Pair<????, ?????>>, vv56789 : Pair<Pair<??????, ???????>, Pair<????????, Pair<?????????, ??????????>>> ->
fn(vv1234.first.first, vv1234.first.second, vv1234.second.first, vv1234.second.second,
vv56789.first.first, vv56789.first.second, vv56789.second.first, vv56789.second.second.first, vv56789.second.second.second)
)
)
}
fsubselect2(b1 : Transform<??>, b2 : Transform<???>, fn : (??, ???) -> Transform<?>) -> Transform<?> {
fsubselect(fpair(b1, b2), FLift(\p : Pair<??, ???> -> fn(firstOfPair(p), secondOfPair(p))));
}
fsubselect3(b1 : Transform<??>, b2 : Transform<???>, b3 : Transform<????>, fn : (??, ???, ????) -> Transform<?>) -> Transform<?> {
fsubselect(fpair(fpair(b1, b2), b3), FLift(\p : Pair<Pair<??, ???>, ????> -> fn(firstOfPair(firstOfPair(p)), secondOfPair(firstOfPair(p)), secondOfPair(p))));
}
//indentation = ref "";
fuse(t : Transform<?>) -> Pair<Behaviour<?>, [() -> void]> {
// println("Fuse on " + transform2string(t));
r = doFuse(t);
// Keep the closure small
ds = secondOfPair(r);
Pair(firstOfPair(r), [\ -> ds()]);
}
fguard(t : Transform<?>, init : DynamicBehaviour<?>) -> Pair<Behaviour<?>, () -> () -> void> {
switch (t : Transform<?>) {
ConstBehaviour(v): Pair(t, \ -> nop);
DynamicBehaviour(v, s): Pair(t, \ -> nop);
default: {
Pair(
init,
\ -> fconnect(t, init)
)
}
}
}
fsubscribe(t : Transform<?>, fn : (?) -> void) -> List<() -> void> {
r = doFuse(t);
u = subscribe(firstOfPair(r), fn);
Cons(u, Cons(secondOfPair(r), EmptyList()))
}
fsubscribe2(t : Transform<?>, fn : (?) -> void) -> List<() -> void> {
r = doFuse(t);
u = subscribe2(firstOfPair(r), fn);
Cons(u, Cons(secondOfPair(r), EmptyList()))
}
fwhen(t : Transform<bool>, fn : () -> void) -> () -> void {
uns = ref nop;
uns := makeSubscribe(t, \v -> if (v) { ^uns(); uns := nop; fn(); })();
\ -> ^uns()
}
makeSubscribe(t : Transform<?>, fn : (?) -> void) -> () -> () -> void {
\ -> {
r = doFuse(t);
u = subscribe(firstOfPair(r), fn);
// Extract to avoid keeping too big a closure
disp = secondOfPair(r);
\ -> {u(); disp()}
}
}
makeSubscribe2(t : Transform<?>, fn : (?) -> void) -> () -> () -> void {
\ -> {
r = doFuse(t);
u = subscribe2(firstOfPair(r), fn);
disp = secondOfPair(r);
\ -> {u(); disp();}
}
}
make2Subscribe(v1 : Transform<?>, v2 : Transform<??>, f : (?, ??) -> void) -> () -> () -> void {
makeSubscribe(fpair(v1, v2), \v12 : Pair<?, ??> -> f(firstOfPair(v12), secondOfPair(v12)))
}
make2Subscribe2(v1 : Transform<?>, v2 : Transform<??>, f : (?, ??) -> void) -> () -> () -> void {
makeSubscribe2(fpair(v1, v2), \v12 : Pair<?, ??> -> f(firstOfPair(v12), secondOfPair(v12)))
}
make3Subscribe(v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, f : (?, ??, ???) -> void) -> () -> () -> void {
makeSubscribe(fpair(fpair(v1, v2), v3), \v123 : Pair<Pair<?, ??>, ???> -> f(v123.first.first, v123.first.second, v123.second))
}
make3Subscribe2(v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, f : (?, ??, ???) -> void) -> () -> () -> void {
makeSubscribe2(fpair(fpair(v1, v2), v3), \v123 : Pair<Pair<?, ??>, ???> -> f(v123.first.first, v123.first.second, v123.second))
}
make4Subscribe(v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>, f : (?, ??, ???, ????) -> void) -> () -> () -> void {
makeSubscribe(fpair(fpair(v1, v2), fpair(v3, v4)), \v1234 : Pair<Pair<?, ??>, Pair<???, ????>> ->
f(v1234.first.first, v1234.first.second, v1234.second.first, v1234.second.second))
}
make4Subscribe2(v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>, f : (?, ??, ???, ????) -> void) -> () -> () -> void {
makeSubscribe2(fpair(fpair(v1, v2), fpair(v3, v4)), \v1234 : Pair<Pair<?, ??>, Pair<???, ????>> ->
f(v1234.first.first, v1234.first.second, v1234.second.first, v1234.second.second))
}
make5Subscribe(v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>, v5 : Transform<?????>,
f : (?, ??, ???, ????, ?????) -> void) -> () -> () -> void {
makeSubscribe(fpair(fpair(v1, v2), fpair(fpair(v3, v4), v5)), \v12345 : Pair<Pair<?, ??>, Pair<Pair<???, ????>, ?????>> ->
f(v12345.first.first, v12345.first.second, v12345.second.first.first, v12345.second.first.second, v12345.second.second))
}
make5Subscribe2(v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>, v5 : Transform<?????>,
f : (?, ??, ???, ????, ?????) -> void) -> () -> () -> void {
makeSubscribe2(fpair(fpair(v1, v2), fpair(fpair(v3, v4), v5)), \v12345 : Pair<Pair<?, ??>, Pair<Pair<???, ????>, ?????>> ->
f(v12345.first.first, v12345.first.second, v12345.second.first.first, v12345.second.first.second, v12345.second.second))
}
makeSubscribeUns(v : Transform<?>, f : (?) -> [() -> void]) -> () -> () -> void {
\ -> {
uns = ref [];
uns2 = makeSubscribe2(v, \val -> {
dispUnsA(uns);
uns := f(val);
})();
uns := f(fgetValue(v));
\ -> {
uns2();
dispUnsA(uns);
}
}
}
makeSubscribeUnsTimer(v : Transform<?>, ms : int, f : (?) -> [() -> void]) -> () -> () -> void {
\ -> {
uns = ref [];
uns2 = ref nop;
uns3 = makeSubscribe(v, \val -> {
dispUns(uns2);
dispUnsA(uns);
uns2 := interruptibleTimer(ms, \ -> uns := f(val));
})();
\ -> {
dispUns(uns2);
uns3();
dispUnsA(uns);
}
}
}
makeSubscribe2Uns(v : Transform<?>, f : (?) -> [() -> void]) -> () -> () -> void {
\ -> {
uns = ref [];
uns2 = makeSubscribe2(v, \val -> {
dispUnsA(uns);
uns := f(val);
})();
\ -> {
uns2();
dispUnsA(uns);
}
}
}
makeSubscribe2UnsTimer(v : Transform<?>, ms : int, f : (?) -> [() -> void]) -> () -> () -> void {
\ -> {
uns = ref [];
uns2 = ref nop;
uns3 = makeSubscribe2(v, \val -> {
dispUns(uns2);
dispUnsA(uns);
uns2 := interruptibleTimer(ms, \ -> uns := f(val));
})();
\ -> {
dispUns(uns2);
uns3();
dispUnsA(uns);
}
}
}
make2SubscribeUns(v1 : Transform<?>, v2 : Transform<??>, f : (?, ??) -> [() -> void]) -> () -> () -> void {
\ -> {
uns = ref [];
uns2 = make2Subscribe2(v1, v2, \val1, val2 -> {
dispUnsA(uns);
uns := f(val1, val2);
})();
uns := f(fgetValue(v1), fgetValue(v2));
\ -> {
uns2();
dispUnsA(uns);
}
}
}
make2Subscribe2Uns(v1 : Transform<?>, v2 : Transform<??>, f : (?, ??) -> [() -> void]) -> () -> () -> void {
\ -> {
uns = ref [];
uns2 = make2Subscribe2(v1, v2, \val1, val2 -> {
dispUnsA(uns);
uns := f(val1, val2);
})();
\ -> {
uns2();
dispUnsA(uns);
}
}
}
makeSubscribeTrigger(trigger : Transform<bool>, v : Transform<?>, f : (?) -> void) -> () -> () -> void {
makeSubscribeUns(trigger, \tr -> if (tr) [makeSubscribe(v, f)()] else []);
}
makeSubscribe2Trigger(trigger : Transform<bool>, v : Transform<?>, f : (?) -> void) -> () -> () -> void {
makeSubscribeUns(trigger, \tr -> if (tr) [makeSubscribe2(v, f)()] else []);
}
make2SubscribeTrigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, f : (?, ??) -> void) -> () -> () -> void {
makeSubscribeUns(trigger, \tr -> if (tr) [make2Subscribe(v1, v2, f)()] else []);
}
make2Subscribe2Trigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, f : (?, ??) -> void) -> () -> () -> void {
makeSubscribeUns(trigger, \tr -> if (tr) [make2Subscribe2(v1, v2, f)()] else []);
}
make3SubscribeTrigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>,
f : (?, ??, ???) -> void) -> () -> () -> void {
makeSubscribeUns(trigger, \tr -> if (tr) [make3Subscribe(v1, v2, v3, f)()] else []);
}
make3Subscribe2Trigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>,
f : (?, ??, ???) -> void) -> () -> () -> void {
makeSubscribeUns(trigger, \tr -> if (tr) [make3Subscribe2(v1, v2, v3, f)()] else []);
}
make4SubscribeTrigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>,
f : (?, ??, ???, ????) -> void) -> () -> () -> void {
makeSubscribeUns(trigger, \tr -> if (tr) [make4Subscribe(v1, v2, v3, v4, f)()] else []);
}
make4Subscribe2Trigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>,
f : (?, ??, ???, ????) -> void) -> () -> () -> void {
makeSubscribeUns(trigger, \tr -> if (tr) [make4Subscribe2(v1, v2, v3, v4, f)()] else []);
}
make5SubscribeTrigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>,
v5 : Transform<?????>, f : (?, ??, ???, ????, ?????) -> void) -> () -> () -> void {
makeSubscribeUns(trigger, \tr -> if (tr) [make5Subscribe(v1, v2, v3, v4, v5, f)()] else []);
}
make5Subscribe2Trigger(trigger : Transform<bool>, v1 : Transform<?>, v2 : Transform<??>, v3 : Transform<???>, v4 : Transform<????>,
v5 : Transform<?????>, f : (?, ??, ???, ????, ?????) -> void) -> () -> () -> void {
makeSubscribeUns(trigger, \tr -> if (tr) [make5Subscribe2(v1, v2, v3, v4, v5, f)()] else []);
}
makeSubscribeDelayedDispose(t : Transform<?>, delay : int, fn : (?) -> void) -> () -> () -> void {
timerUns = ref None();
disposer = ref None();
subsCounter = ref 0;
\ -> {
subsCounter := ^subsCounter + 1;
eitherFn(
^timerUns,
\uns -> {
uns();
},
\ -> {
if (isNone(^disposer)) {
u = makeSubscribe(t, fn)();
disposer :=
Some(\ -> {
if (^subsCounter == 0) {
disposer := None();
u();
}
});
}
}
);
\ -> {
subsCounter := ^subsCounter - 1;
timerUns :=
Some(interruptibleTimer(delay, \ -> {
timerUns := None();
maybeApply(^disposer, apply0);
}));
}
}
}
dispUns(uns : ref () -> void) -> void {
^uns();
uns := nop;
}
dispUns2(uns : ref Maybe<() -> void>) -> void {
// a version of dispUns() without functions comparison
switch (^uns) {
Some(f): {
f();
uns := None();
}
None(): {}
}
}
dispUnsA(uns : ref [() -> void]) -> void {
if (length(^uns) > 0) {
applyall(^uns);
uns := [];
}
}
dispUnsTree(uns : ref Tree<?, () -> void>, key : ?) -> void {
maybeApply(lookupTree(^uns, key), \v -> v());
uns := removeFromTree(^uns, key);
}
fgetValue(t : Transform<?>) -> ? {
switch (t : Transform<?>) {
ConstBehaviour(b):
b;
DynamicBehaviour(b, s):
^b;
FSelect(b, fn, beh):
switch (beh) {
FInitialized(__, __, dyn): cast(getValue(dyn) : flow -> ?);
FDestroyed(): {
ffn = instantiateFn(fn);
bb = fgetValue(b);
ffn(bb);
// instantiateFn(fn)(fgetValue(b));
}
}
FSelect2(b1, b2, fn, beh):
switch (beh) {
FInitialized(__, __, dyn): getValue(dyn);
FDestroyed(): instantiateFn2(fn)(fgetValue(b1), fgetValue(b2));
}
FSubSelect(b, fn, beh):
switch (beh) {
FInitialized(__, __, dyn): getValue(dyn);
FDestroyed(): fgetValue(instantiateFn(fn)(fgetValue(b)));
}
FConstructable(b, constructor, beh):
switch (beh) {
FInitialized(__, __, dyn): getValue(dyn);
FDestroyed(): {
d = constructor();
r = fgetValue(b);
d();
r;
}
}
}
}
fgetDynamicBehaviours(t : Transform<?>) -> [DynamicBehaviour] {
switch (t) {
ConstBehaviour(b): [];
DynamicBehaviour(b, s): [t];
FSelect(b, f1, __): fgetDynamicBehaviours(b);
FSelect2(b1, b2, f1, __): concat(fgetDynamicBehaviours(b1), fgetDynamicBehaviours(b2));
FSubSelect(b, f1, __): fgetDynamicBehaviours(b);
FConstructable(b, __, __): fgetDynamicBehaviours(b);
}
}
isFConst(t : Transform<?>) -> bool {
switch (t) {
ConstBehaviour(v): true;
default: false;
}
}
doFuse(t : Transform<?>) -> Pair<Behaviour<?>, () -> void> {
switch (t : Transform<?>) {
ConstBehaviour(b): Pair(t, nop);
default: doFuseDynamic(t);
}
}
doFuseDynamic(t : Transform<?>) -> Pair<DynamicBehaviour<?>, () -> void> {
switch (t : Transform<?>) {
ConstBehaviour(b): Pair(make(b), nop);
DynamicBehaviour(b, s): {
provider = make(^b);
// We make all behaviours distinct!
u = subscribe2(t, \v -> nextDistinct(provider, v));
Pair(provider, u);
}
FSelect(b, fn, beh): {
switch (beh) {
FInitialized(subs, disp, dyn): {
subs := ^subs + 1;
Pair(dyn, disp);
}
FDestroyed(): {
ifn = instantiateFn(fn);
switch (b : Transform<??>) {
DynamicBehaviour(dv, __): {
subs = ref 1;
dyn = make(ifn(^dv));
u = subscribe2(b, \v : ?? -> nextDistinct(dyn, ifn(v)));
disp = \ -> {subs := ^subs - 1; if (^subs == 0) {u(); t.beh ::= FDestroyed();}};
t.beh ::= FInitialized(subs, disp, dyn);
Pair(dyn, disp)
}
default: {
cb = doFuseDynamic(b);
subs = ref 1;
dyn = make(ifn(getValue(firstOfPair(cb))));
u = subscribe2(firstOfPair(cb), \v : ?? -> nextDistinct(dyn, ifn(v)));
disp = \ -> {subs := ^subs - 1; if (^subs == 0) {u(); secondOfPair(cb)(); t.beh ::= FDestroyed();}};
t.beh ::= FInitialized(subs, disp, dyn);
Pair(dyn, disp)
}
}
}
}
}
FSelect2(b1, b2, fn, beh): {
switch (beh) {
FInitialized(subs, disp, dyn): {
subs := ^subs + 1;
Pair(dyn, disp);
}
FDestroyed(): {
ifn = instantiateFn2(fn);
switch (b1 : Transform<?>) {
DynamicBehaviour(dv1, __): {
switch (b2 : Transform<??>) {
DynamicBehaviour(dv2, __): {
subs = ref 1;
dyn = make(ifn(^dv1, ^dv2));
disp =
if (flow(b1) == b2) {
u = subscribe2(b1, \b -> nextDistinct(dyn, ifn(b, flow(b))));
\ -> {subs := ^subs - 1; if (^subs == 0) {u(); t.beh ::= FDestroyed();}};
} else {
updating = ref 0;
u1 = subscribe2(b1, \b -> {
if (^updating == 0) {
updating := ^updating + 1;
nextDistinct(dyn, ifn(b, ^dv2));
updating := ^updating - 1;
} else {
// println("Nested update, probably wrong layout");
// println(transform2string(t));
// printCallstack();
}
});
u2 = subscribe2(b2, \b -> {
if (^updating == 0) {
updating := ^updating + 1;
nextDistinct(dyn, ifn(^dv1, b));
updating := ^updating - 1;
} else {
// println("Nested update, probably wrong layout");
// println(transform2string(t));
// printCallstack();
}
});
\ -> {subs := ^subs - 1; if (^subs == 0) {u1(); u2(); t.beh ::= FDestroyed();}};
};
t.beh ::= FInitialized(subs, disp, dyn);
Pair(dyn, disp)
}
default: {
cb = doFuseDynamic(b2);
subs = ref 1;
dyn = make(ifn(^dv1, getValue(firstOfPair(cb))));
updating = ref 0;
u1 = subscribe2(b1, \b -> {
if (^updating == 0) {
updating := ^updating + 1;
nextDistinct(dyn, ifn(b, getValue(firstOfPair(cb))));
updating := ^updating - 1;
} else {
// println("Nested update, probably wrong layout");
// println(transform2string(t));
// printCallstack();
}
});
u2 = subscribe2(firstOfPair(cb), \b -> {
if (^updating == 0) {
updating := ^updating + 1;
nextDistinct(dyn, ifn(^dv1, b));
updating := ^updating - 1;
} else {
// println("Nested update, probably wrong layout");
// println(transform2string(t));
// printCallstack();
}
});
disp = \ -> {subs := ^subs - 1; if (^subs == 0) {u1(); u2(); secondOfPair(cb)(); t.beh ::= FDestroyed();}};
t.beh ::= FInitialized(subs, disp, dyn);
Pair(dyn, disp)
}
}
}
default: {
switch (b2 : Transform<??>) {
DynamicBehaviour(dv2, __): {
cb = doFuseDynamic(b1);
subs = ref 1;
dyn = make(ifn(getValue(firstOfPair(cb)), ^dv2));
updating = ref 0;
u1 = subscribe2(firstOfPair(cb), \b -> {
if (^updating == 0) {
updating := ^updating + 1;
nextDistinct(dyn, ifn(b, ^dv2));
updating := ^updating - 1;
} else {
// println("Nested update, probably wrong layout");
// println(transform2string(t));
// printCallstack();
}
});
u2 = subscribe2(b2, \b -> {
if (^updating == 0) {
updating := ^updating + 1;
nextDistinct(dyn, ifn(getValue(firstOfPair(cb)), b));
updating := ^updating - 1;
} else {
// println("Nested update, probably wrong layout");
// println(transform2string(t));
// printCallstack();
}
});
disp = \ -> {subs := ^subs - 1; if (^subs == 0) {u1(); u2(); secondOfPair(cb)(); t.beh ::= FDestroyed();}};
t.beh ::= FInitialized(subs, disp, dyn);
Pair(dyn, disp)
}
default: {
if (b1 == b2) {
cb1 = doFuseDynamic(b1);
subs = ref 1;
dyn = make(ifn(getValue(firstOfPair(cb1)), getValue(firstOfPair(cb1))));
u = subscribe2(firstOfPair(cb1), \b -> nextDistinct(dyn, ifn(b, b)));
disp = \ -> {subs := ^subs - 1; if (^subs == 0) {u(); secondOfPair(cb1)(); t.beh ::= FDestroyed();}};
t.beh ::= FInitialized(subs, disp, dyn);
Pair(dyn, disp)
} else {
cb1 = doFuseDynamic(b1);
cb2 = doFuseDynamic(b2);
subs = ref 1;
dyn = make(ifn(getValue(firstOfPair(cb1)), getValue(firstOfPair(cb2))));
updating = ref 0;
u1 = subscribe2(firstOfPair(cb1), \b -> {
if (^updating == 0) {
updating := ^updating + 1;
nextDistinct(dyn, ifn(b, getValue(firstOfPair(cb2))));
updating := ^updating - 1;
} else {
// println("Nested update, probably wrong layout");
// println(transform2string(t));
// printCallstack();
}
});
u2 = subscribe2(firstOfPair(cb2), \b -> {
if (^updating == 0) {
updating := ^updating + 1;
nextDistinct(dyn, ifn(getValue(firstOfPair(cb1)), b));
updating := ^updating - 1;
} else {
// println("Nested update, probably wrong layout");
// println(transform2string(t));
// printCallstack();
}
});
disp = \ -> {subs := ^subs - 1; if (^subs == 0) {u1(); u2(); secondOfPair(cb1)(); secondOfPair(cb2)();
t.beh ::= FDestroyed();}};
t.beh ::= FInitialized(subs, disp, dyn);
Pair(dyn, disp)
};
}
}
}
}
}
}
}
FSubSelect(b, fn, beh): {
switch (beh) {
FInitialized(subs, disp, dyn): {
subs := ^subs + 1;
Pair(dyn, disp);
}
FDestroyed(): {
ifn = instantiateFn(fn);
switch (b : Transform<??>) {
DynamicBehaviour(dv, __): {
subs = ref 1;
bf0 = doFuse(ifn(^dv));
dyn = make(getValue(firstOfPair(bf0)));
u0 = subscribe2(firstOfPair(bf0), \v2 -> nextDistinct(dyn, v2));
disconnect = ref \ -> {
secondOfPair(bf0)();
u0();
}
u = subscribe2(b, \v1 -> {
bf = doFuse(ifn(v1));
u2 = subscribe(firstOfPair(bf), \v2 -> nextDistinct(dyn, v2));
^disconnect();
disconnect := \ -> {
secondOfPair(bf)();
u2();
};
});
disp = \ -> {subs := ^subs - 1; if (^subs == 0) {u(); ^disconnect(); t.beh ::= FDestroyed();}};
t.beh ::= FInitialized(subs, disp, dyn);
Pair(dyn, disp)
}
default: {
cb = doFuseDynamic(b);
subs = ref 1;
bf0 = doFuse(ifn(getValue(firstOfPair(cb))));
dyn = make(getValue(firstOfPair(bf0)));
u0 = subscribe2(firstOfPair(bf0), \v2 -> nextDistinct(dyn, v2));
disconnect = ref \ -> {
secondOfPair(bf0)();
u0();
}
u = subscribe2(firstOfPair(cb), \v1 -> {
bf = doFuse(ifn(v1));
u2 = subscribe(firstOfPair(bf), \v2 -> nextDistinct(dyn, v2));
^disconnect();
disconnect := \ -> {
secondOfPair(bf)();
u2();
};
});
disp = \ -> {subs := ^subs - 1; if (^subs == 0) {u(); ^disconnect(); secondOfPair(cb)(); t.beh ::= FDestroyed();}};
t.beh ::= FInitialized(subs, disp, dyn);
Pair(dyn, disp)
}
}
}
}
}
FConstructable(b, constructor, beh): {
switch (beh) {
FInitialized(subs, disp, dyn): {
subs := ^subs + 1;
Pair(dyn, disp);
}
FDestroyed(): {
d = constructor();
cb = doFuseDynamic(b);
subs = ref 1;
dyn = firstOfPair(cb);
disp = \ -> {subs := ^subs - 1; if (^subs == 0) {secondOfPair(cb)(); d(); t.beh ::= FDestroyed();}};
t.beh ::= FInitialized(subs, disp, dyn);
Pair(dyn, disp);
}
}
}
}
}
transform2string(s : Transform<?>) -> string {
switch (s : Transform<?>) {
ConstBehaviour(v): {
dv = v;
if (isSameStructType(dv, dv))
"const " + flow(dv).structname + "(...)"
else {
"const " + safeToString(dv);
}
}
DynamicBehaviour(v, b): {
"dyn " + safeToString(^v);
}
FSelect(b, fn, __): {
//"select(" + transform2string(b) + ", " + ffn2string(fn) + ")";
"S(" + transform2string(b) + " |> " + ffn2string(fn) + ")";
}
FSelect2(b1, b2, fn, __): {
// "select2(" + transform2string(b1) + "," + transform2string(b2) + ", " + ffn2string(fn) + ")";
"S2(" + transform2string(b1) + ", " + transform2string(b2) + " |> " + ffn22string(fn) + ")";
}
FSubSelect(b, fn, __): {
// "subselect(" + transform2string(b) + ", " + ffn2string(fn) + ")";
transform2string(b) + "=>" + transform2string(instantiateFn(fn)(fgetValue(b))); // ffn2string(fn);
}
FConstructable(b, __, __): transform2string(b);
}
}
transformLength(s : Transform<?>) -> int {
switch (s : Transform<?>) {
ConstBehaviour(v): {
0;
}
DynamicBehaviour(v, b): {
1;
}
FSelect(b, fn, __): {
transformLength(b);
}
FSelect2(b1, b2, fn, __): {
transformLength(b1) + transformLength(b2);
}
FSubSelect(b, fn, __): {
transformLength(b) + transformLength(instantiateFn(fn)(fgetValue(b)));
}
FConstructable(b, constructor, beh): {
if (beh == FDestroyed()) {
d = constructor();
r = transformLength(b);
d();
r;
} else {
transformLength(b);
}
}
}
}
faddition(b1 : Transform<double>, b2 : Transform<double>) -> Transform<double> {
if (isSameObj(b1, b2))
fselect(b1, FLift(\v : double -> v + v))
else if (isSameObj(b1, zero))
b2
else if (isSameObj(b2, zero))
b1
else {
switch (b1) {
ConstBehaviour(v1): {
if (v1 == doubleMax) {
ConstBehaviour(v1)
} else switch (b2) {
ConstBehaviour(v2): {
// While the default case effectively reduces to this case,
// it does so after a lot of garbage is made, so let us just
// handle this common case directly
ConstBehaviour(v1 + v2);
}
default: {
fselect(b2, FAddConst(v1))
}
}
}
default: {
switch (b2) {
ConstBehaviour(v): {
if (v == doubleMax) {
ConstBehaviour(v);
} else {
fselect(b1, FAddConst(v));
}
}
default: {
// println(transform2string(b1) + " + " + transform2string(b2));
fselect2(b1, b2, FAddition());
}
}
}
}
}
}
fsubtract(b1 : Transform<double>, b2 : Transform<double>) -> Transform<double> {
if (isSameObj(b1, b2))
zero
else if (isSameObj(b1, zero))
fnegate(b2)
else if (isSameObj(b2, zero))
b1
else {
switch (b1) {
ConstBehaviour(v): {
fselect(fnegate(b2), FAddConst(v));
}
default: {
switch (b2) {
ConstBehaviour(v): {
fselect(b1, FAddConst(-v));
}
default: fselect2(b1, b2, FSubtract());
}
}
}
}
}
fmultiply(b1 : Transform<double>, b2 : Transform<double>) -> Transform<double> {
if (isSameObj(b1, b2))
fselect(b1, FLift(\v : double -> v * v))
else if (isSameObj(b1, zero) || isSameObj(b2, zero))
zero
else if (b1 == ConstBehaviour(1.0))
b2
else if (b2 == ConstBehaviour(1.0))
b1
else {
switch (b1) {
ConstBehaviour(v1): {
switch (b2) {
ConstBehaviour(v2): {
// While the default case effectively reduces to this case,
// it does so after a lot of garbage is made, so let us just
// handle this common case directly
ConstBehaviour(v1 * v2);
}
default: {
fselect(b2, FMulConst(v1))
}
}
}
default: {
switch (b2) {
ConstBehaviour(v): {
fselect(b1, FMulConst(v))
}
default: {
// println(transform2string(b1) + " + " + transform2string(b2));
fselect2(b1, b2, FMultiply());
}
}
}
}
}
}
fadditioni(b1 : Transform<int>, b2 : Transform<int>) -> Transform<int> {
fselect2(b1, b2, FLift2(\v1, v2 -> v1 + v2));
}
fsubtracti(b1 : Transform<int>, b2 : Transform<int>) -> Transform<int> {
fselect2(b1, b2, FLift2(\v1, v2 -> v1 - v2));
}
fmultiplyi(b1 : Transform<int>, b2 : Transform<int>) -> Transform<int> {
fselect2(b1, b2, FLift2(\v1, v2 -> v1 * v2));
}
fgreater(b1 : Transform<double>, b2 : Transform<double>) -> Transform<bool> {
fselect2(b1, b2, FLift2(\v1, v2 -> v1 > v2));
}
fless(b1 : Transform<double>, b2 : Transform<double>) -> Transform<bool> {
fselect2(b1, b2, FLift2(\v1, v2 -> v1 < v2));
}
fgreateri(b1 : Transform<int>, b2 : Transform<int>) -> Transform<bool> {
fselect2(b1, b2, FLift2(\v1, v2 -> v1 > v2));
}
flessi(b1 : Transform<int>, b2 : Transform<int>) -> Transform<bool> {
fselect2(b1, b2, FLift2(\v1, v2 -> v1 < v2));
}
fdivide(b1 : Transform<double>, b2 : Transform<double>) -> Transform<double> {
if (isSameObj(b1, b2))
fselect(b1, FLift(\v -> if (v == 0.) 0. else 1.))
else if (isSameObj(b1, zero) || isSameObj(b2, zero))
zero
else if (b2 == ConstBehaviour(1.0))
b1
else {
switch (b2) {
ConstBehaviour(v): {
if (v == 0.0) {
zero
} else {
fselect(b1, FMulConst(1.0 / v))
}
}
default: {
// println(transform2string(b1) + " + " + transform2string(b2));
fselect2(b1, b2, FDivide());
}
}
}
}
fnegate(b1 : Transform<double>) -> Transform<double> {
fselect(b1, FNegate())
}
fdividei(b1 : Transform<int>, b2 : Transform<int>) -> Transform<int> {
fselect2(b1, b2, FLift2(\v1, v2 -> v1 / v2));
}
fnegatei(b1 : Transform<int>) -> Transform<int> {
fselect(b1, FLift(\v : int -> -v));
}
fmax(b1 : Transform<?>, b2 : Transform<?>) -> Transform<?> {
if (isSameObj(b1, b2))
b1
else switch (b1 : Transform<?>) {
ConstBehaviour(v1): {
switch (b2 : Transform<?>) {
ConstBehaviour(v2): {
// While the default case effectively reduces to this case,
// it does so after a lot of garbage is made, so let us just
// handle this common case directly
ConstBehaviour(max(v1, v2));
}
default: {
if (flow(v1) == true || flow(v1) == doubleMax) {
ConstBehaviour(flow(v1))
} else {
fselect(b2, FMaxConst(v1));
}
}
}
}
default: {
switch (b2) {
ConstBehaviour(v2): {
if (flow(v2) == true || flow(v2) == doubleMax) {
ConstBehaviour(flow(v2))
} else {
fselect(b1, FMaxConst(v2));
}
}
default: {
fselect2(b1, b2, FMax());
}
}
}
}
}
fmax3(b1 : Transform<?>, b2 : Transform<?>, b3 : Transform<?>) -> Transform<?> {
fmax(b1, fmax(b2, b3));
}
fmin(b1 : Transform<?>, b2 : Transform<?>) -> Transform<?> {
if (isSameObj(b1, b2))
b1
else switch (b1) {
ConstBehaviour(v1): {
switch (b2) {
ConstBehaviour(v2): {
// While the default case effectively reduces to this case,
// it does so after a lot of garbage is made, so let us just
// handle this common case directly
ConstBehaviour(min(v1, v2));
}
default: {
if (flow(v1) == false) {
ConstBehaviour(flow(v1))
} else {
fselect(b2, FMinConst(v1));
}
}
}
}
default: {
switch (b2) {
ConstBehaviour(v2): {
if (flow(v2) == false) {
ConstBehaviour(flow(v2))
} else {
fselect(b1, FMinConst(v2));
}
}
default: {
fselect2(b1, b2, FMin());
}
}
}
}
}
fmin3(b1 : Transform<?>, b2 : Transform<?>, b3 : Transform<?>) -> Transform<?> {
fmin(b1, fmin(b2, b3));
}
fmaxA(v : [Transform<?>], def : ?) -> Transform<?> {
if (length(v) > 0)
fold(tail(v), v[0], \acc, v1 ->
fmax(acc, v1)
)
else
ConstBehaviour(def)
}
fminA(v : [Transform<?>], def : ?) -> Transform<?> {
if (length(v) > 0)
fold(tail(v), v[0], \acc, v1 ->
fmin(acc, v1)
)
else
ConstBehaviour(def)
}
farray(v1 : Transform<?>) -> Transform<[?]> {
fselect(v1, FLift(\v -> [v]))
}
fconcat(v1 : Transform<[?]>, v2 : Transform<[?]>) -> Transform<[?]> {
fselect2(v1, v2, concat |> FLift2)
}
farrayPush(v1 : Transform<[?]>, v2 : Transform<?>) -> Transform<[?]> {
fselect2(v1, v2, arrayPush |> FLift2)
}
fconcatA(v : Transform<[[?]]>) -> Transform<[?]> {
fselect(v, concatA |> FLift)
}
fcontains(v1 : Transform<[?]>, v2 : Transform<?>) -> Transform<bool> {
fselect2(v1, v2, contains |> FLift2)
}
fcompose(f1 : FFn<flow, ??>, f2 : FFn<?, flow>) -> FFn<?, ??> {
switch (f1 : FFn<flow, ??>) {
FAddConst(c1): {
switch (f2 : FFn<?, flow>) {
FAddConst(c2): {
FAddConst(c1 + c2);
}
FCompose(f3, f4): {
switch (f3) {
FAddConst(c3): {
fcompose(FAddConst(c1 + c3), f4)
}
default: {
FCompose(f1, f2);
}
}
}
FIdentity(): f1;
default: {
FCompose(f1, f2);
}
}
}
FMulConst(c1): {
switch (f2 : FFn<?, flow>) {
FMulConst(c2): {
FMulConst(c1 * c2);
}
FCompose(f3, f4): {
switch (f3) {
FMulConst(c3): {
fcompose(FMulConst(c1 * c3), f4)
}
default: {
FCompose(f1, f2);
}
}
}
FIdentity(): f1;
default: {
FCompose(f1, f2);
}
}
}
FMaxConst(c1): {
switch (f2 : FFn<?, flow>) {
FMaxConst(c2): {
v : ? = max(c1, c2);
FMaxConst(v);
}
FCompose(f3, f4): {
switch (f3) {
FMaxConst(c3): {
fcompose(FMaxConst(max(c1, c3)), f4)
}
default: {
FCompose(f1, f2);
}
}
}
FIdentity(): f1;
default: {
FCompose(f1, f2);
}
}
}
FMinConst(c1): {
switch (f2 : FFn<?, flow>) {
FMinConst(c2): {
v : ? = min(c1, c2);
FMinConst(v);
}
FCompose(f3, f4): {
switch (f3) {
FMinConst(c3): {
fcompose(FMinConst(min(c1, c3)), f4)
}
default: {
FCompose(f1, f2);
}
}
}
FIdentity(): f1;
default: {
FCompose(f1, f2);
}
}
}
FIdentity(): f2;
default: {
switch (f2 : FFn<?, flow>) {
FIdentity(): f1;
default:{
// println("Compose: " + ffn2string(f1) + " o " + ffn2string(f2));
FCompose(f1, f2);
}
}
}
}
}
fif(b1 : Transform<bool>, then1 : Transform<?>, else1 : Transform<?>) -> Transform<?> {
if (isSameObj(then1, else1))
then1
else {
switch (b1) {
ConstBehaviour(v): {
if (v) then1 else else1;
}
default: {
tmp : FFn<flow, Transform<?>> = FIf(then1, else1);
fsubselect(b1, tmp);
}
}
}
}
feq(b : Transform<?>, v : ?) -> Transform<bool> {
switch (b) {
ConstBehaviour(c): ConstBehaviour(c == v);
default: fselect(b, FEqual(v));
}
}
fneq(b : Transform<?>, v : ?) -> Transform<bool> {
switch (b) {
ConstBehaviour(c): ConstBehaviour(c != v);
default: fnot(fselect(b, FEqual(v)));
}
}
fequal(a : Transform<?>, b : Transform<?>) {
fselect2(a, b, FLift2(\va, vb -> va == vb))
}
fnotequal(a : Transform<?>, b : Transform<?>) {
fselect2(a, b, FLift2(\va, vb -> va != vb))
}
fnot(b : Transform<bool>) -> Transform<bool> {
feq(b, false)
}
fand(a : Transform<bool>, b : Transform<bool>) -> Transform<bool> {
if (ConstBehaviour(false) == a || ConstBehaviour(false) == b)
ConstBehaviour(false)
else
fselect2(a, b, FusionAnd());
}
fOr(a : Transform<bool>, b : Transform<bool>) -> Transform<bool> {
if (a == ConstBehaviour(true) || b == ConstBehaviour(true))
ConstBehaviour(true)
else
fselect2(a, b, FusionOr());
}
fxor(a : Transform<bool>, b : Transform<bool>) -> Transform<bool> {
fselect2(a, b, FusionXor());
}
fabs(a : Transform<double>) -> Transform<double> {
fselect(a, abs |> FLift);
}
fpair(v1 : Transform<?>, v2 : Transform<??>) -> Transform<Pair<?, ??>> {
fselect2(v1, v2, FIdentity2())
}
fwidthheight(wd : Transform<double>, hgt : Transform<double>) -> Transform<WidthHeight> {
fselect2(wd, hgt, FusionWidthHeight());
}
fpoint(x : Transform<double>, y : Transform<double>) -> Transform<Point> {
fselect2(x, y, FLift2(\vx, vy -> Point(vx, vy)));
}
fpointX(point : Transform<Point>) -> Transform<double> {
fselect(point, FLift(\p -> p.x))
}
fpointY(point : Transform<Point>) -> Transform<double> {
fselect(point, FLift(\p -> p.y))
}
ffactor(x : Transform<double>, y : Transform<double>) -> Transform<Factor> {
fselect2(x, y, FLift2(\vx, vy -> Factor(vx, vy)));
}
ffactor2(f : Transform<double>) -> Transform<Factor> {
fselect(f, FLift(\vf -> Factor(vf, vf)));
}
ffactorX(factor : Transform<Factor>) -> Transform<double> {
fselect(factor, FLift(\f -> f.x))
}
ffactorY(factor : Transform<Factor>) -> Transform<double> {
fselect(factor, FLift(\f -> f.y))
}
fwidth(wh : Transform<WidthHeight>) -> Transform<double> {
switch (wh : Transform<WidthHeight>) {
FSelect2(b, __, fn, __): {
switch (fn : FFn2<double, double, WidthHeight>) {
FusionWidthHeight(): {
b;
}
default: fselect(wh, FLift(\whv -> whv.width));
}
}
default: fselect(wh, FLift(\whv -> whv.width));
}
}
fheight(wh : Transform<WidthHeight>) -> Transform<double> {
switch (wh : Transform<WidthHeight>) {
FSelect2(__, b, fn, __): {
switch (fn : FFn2<double, double, WidthHeight>) {
FusionWidthHeight(): {
b;
}
default: fselect(wh, FLift(\whv -> whv.height));
}
}
default: fselect(wh, FLift(\whv -> whv.height));
}
}
fconnect(v1 : Transform<?>, v2 : DynamicBehaviour<?>) -> () -> void {
makeSubscribe(v1, \v -> nextDistinct(v2, v))();
}
fconnectSelect(v1 : Transform<?>, v2 : DynamicBehaviour<??>, fn : (?) -> ??) -> () -> void {
makeSubscribe(v1, \v -> nextDistinct(v2, fn(v)))();
}
fconnect2Select(t1 : Transform<?>, t2 : Transform<??>, v : DynamicBehaviour<???>, fn : (?, ??) -> ???) -> () -> void {
make2Subscribe(t1, t2, \v1, v2 -> nextDistinct(v, fn(v1, v2)))();
}
fmerge(a : [Transform<?>]) -> Transform<[?]> {
if (length(a) > 0)
foldTreeBinary(pairs2tree(mapi(a, \k, v -> Pair(k, v))), \__, vv, ll, rr -> fselect3(ll, vv, rr, \l, v, r -> concat3(l, [v], r)), ConstBehaviour([]))
else
ConstBehaviour([])
}
fmergeTree(tree : Tree<??, Transform<?>>) -> Transform<Tree<??, ?>> {
if (sizeTree(tree) > 0)
fselect(
foldTreeBinary(tree, \k, vv, ll, rr -> fselect3(ll, vv, rr, \l, v, r -> concat3(l, [Pair(k, v)], r)), ConstBehaviour([])),
pairs2tree |> FLift
)
else
ConstBehaviour(makeTree())
}
fsum(a : [Transform<double>]) -> Transform<double> {
if (length(a) > 0)
foldTreeBinary(pairs2tree(mapi(a, \k, v -> Pair(k, v))), \__, vv, ll, rr -> fselect3(ll, vv, rr, \l, v, r -> l + v + r), ConstBehaviour(0.0))
else
ConstBehaviour(0.0)
}
fsumi(a : [Transform<int>]) -> Transform<int> {
if (length(a) > 0)
foldTreeBinary(pairs2tree(mapi(a, \k, v -> Pair(k, v))), \__, vv, ll, rr -> fselect3(ll, vv, rr, \l, v, r -> l + v + r), ConstBehaviour(0))
else
ConstBehaviour(0)
}
faverage(a : [Transform<double>]) -> Transform<double> {
if (length(a) > 0)
foldTreeBinary(
pairs2tree(mapi(a, \k, v -> Pair(k, Pair(1, v)))),
\__, vv : Pair<int, Transform<double>>, ll : Pair<int, Transform<double>>, rr : Pair<int, Transform<double>> -> {
Pair(ll.first + vv.first + rr.first, fselect3(ll.second, vv.second, rr.second, \l, v, r -> l + v + r));
},
Pair(0, ConstBehaviour(0.0))
)
|> (\t -> fdivide(t.second, ConstBehaviour(i2d(t.first))))
else
ConstBehaviour(0.0)
}
ftransistor(g : Transform<bool>, v: Transform<?>) -> Transform<?> {
currentV : ref ? = ref fgetValue(v);
newV =
fselect(v, FLift(\v0 -> {
currentV := v0;
v0
}));
fsubselect(g, FLift(\b ->
if (b) {
newV;
} else {
ConstBehaviour(^currentV);
}
))
}
fthrottleTimer(
pendingV : ref Maybe<?>,
newV : DynamicBehaviour<?>,
samplingRate : int) -> void {
timer(samplingRate, \ -> {
maybeApply(
^pendingV,
\pv -> if (pv != getValue(newV)) {
next(newV, pv);
fthrottleTimer(pendingV, newV, samplingRate)
} else {
pendingV := None();
}
);
});
}
fthrottle(v : Transform<?>, samplingRate : int) -> Transform<?> {
switch (v) {
ConstBehaviour(__): v;
default: {
newV = make(fgetValue(v));
pendingV = ref None();
fsubselect(v, FLift(\v0 -> {
eitherFn(
^pendingV,
\pv -> {
pendingV := Some(v0);
},
\ -> {
pendingV := Some(v0);
next(newV, v0);
fthrottleTimer(
pendingV,
newV,
samplingRate
);
}
);
newV
}))
}
}
}
fthrottle2(v : Transform<?>, maxDelta : int) -> Transform<?> {
switch (v) {
ConstBehaviour(__): v;
default: {
newV = make(fgetValue(v));
uns = ref nop;
fsubselect(v, FLift(\v0 -> {
^uns();
uns := interruptibleTimer(maxDelta, \ -> next(newV, v0));
newV
}))
}
}
}
fthrottleNextFrameTimer(pendingV : ref Maybe<?>, newV : DynamicBehaviour<?>) -> void {
deferUntilNextFrameRendered(\ -> {
maybeApply(
^pendingV,
\pv -> if (pv != getValue(newV)) {
next(newV, pv);
fthrottleNextFrameTimer(pendingV, newV)
} else {
pendingV := None();
}
);
});
}
fthrottleNextFrame(v : Transform<?>) -> Transform<?> {
switch (v) {
ConstBehaviour(__): v;
default: {
newV = make(fgetValue(v));
pendingV = ref None();
fsubselect(v, FLift(\v0 -> {
eitherFn(
^pendingV,
\pv -> {
pendingV := Some(v0);
},
\ -> {
pendingV := Some(v0);
next(newV, v0);
fthrottleNextFrameTimer(pendingV, newV);
}
);
newV
}))
}
}
}
fthrottle2NextFrame(v : Transform<?>) -> Transform<?> {
switch (v) {
ConstBehaviour(__): v;
default: {
newV = make(fgetValue(v));
uns = ref nop;
fsubselect(v, FLift(\v0 -> {
^uns();
uns := interruptibleDeferUntilNextFrameRendered(\ -> next(newV, v0));
newV
}))
}
}
}
fselectWithLast(b : Transform<??>, fn : FFn2<??, ??, ?>) -> Transform<?> {
ifn = instantiateFn2(fn);
lastV = ref None();
fselect(b, FLift(\v ->
switch (^lastV) {
Some(prevV): {
r = ifn(prevV, v);
lastV := Some(v);
r
}
None(): {
lastV := Some(v);
ifn(v, v);
}
}
))
}
fdelay(v : Transform<?>, ms : int) -> Transform<?> {
switch (v) {
ConstBehaviour(__): v;
default: {
provider : DynamicBehaviour<?> = make(fgetValue(v));
fsubselect(v, FLift(\v0 -> {
timer(ms, \ -> next(provider, v0));
provider
}))
}
}
}
fstall(v : Transform<?>, ms : int) -> Transform<?> {
switch (v) {
ConstBehaviour(__): v;
default: {
provider : DynamicBehaviour<?> = make(fgetValue(v));
fsubselect(v, FLift(\v0 -> {
timer(ms, \ -> nextDistinct(provider, fgetValue(v)));
provider
}))
}
}
}
fBidirectionalLink(v1 : Transform<?>, v2 : Transform<??>, fn1 : (?) -> void, fn2 : (??) -> void) -> () -> void {
nested = ref false;
u1 = fsubscribe(v1, \v -> if (!^nested) {
nested := true;
fn1(v);
nested := false;
});
u2 = fsubscribe2(v2, \v -> if (!^nested) {
nested := true;
fn2(v);
nested := false;
});
\ -> applyList(concatList(u1, u2), apply0)
}
instantiateFn(fn : FFn<?, ??>) -> (?) -> ?? {
// println(ffn2string(fn));
switch (fn : FFn<?, ??>) {
FLift(f): f;
FCompose(f1, f2): {
// TODO: If f1 or f2 are lifted, we can do better
//lf1 : (???) -> ?? = instantiateFn(f1);
//lf2 : (?) -> ??? = instantiateFn(f2);
lf1 : (???) -> ?? = instantiateFn(f1);
lf2 = instantiateFn(f2);
r : (?)->?? = \v : ? -> lf1(lf2(v));
r;
}
FIdentity(): flow(idfn);
FNegate(): flow(\p : double -> -p);
FAddConst(v): flow(\p : double -> p + v);
FMulConst(v): flow(\p : double -> p * v);
FMaxConst(v): flow(\p -> cast(flow(max(p, v)) : flow -> ??));
FMinConst(v): flow(\p -> min(p, v));
FEqual(v): flow(\p -> p == v);
FIf(t, e): flow(\c : bool -> if (c) t else e);
}
}
instantiateFn2(fn : FFn2<?, ??, ???>) -> (?, ??) -> ??? {
// println(ffn2string(fn));
switch (fn : FFn2<?, ??, ???>) {
FLift2(f): f;
FIdentity2(): flow(\f, s -> Pair(f, s));
FAddition(): flow(\f: double, s: double -> f + s);
FSubtract(): flow(\f : double, s : double-> f - s);
FMultiply(): flow(\f: double, s : double-> f * s);
FDivide(): {
flow(\f, s -> if (s == 0.0) 0.0 else f / s);
}
FMax(): flow(max);
FMin(): flow(min);
FusionAnd() : flow(\a, b -> a && b);
FusionOr() : flow(\a, b -> a || b);
FusionXor() : flow(\a, b -> a != b);
FusionWidthHeight() : flow(\a, b -> WidthHeight(a, b));
}
}
ffn2string(fn : FFn<?, ??>) -> string {
switch (fn) {
FLift(fl): trim2(takeAfter(safeToString(fn), ": ", safeToString(fn)), ")>");
FCompose(f1, f2): "(" + ffn2string(f1) + ")o(" + ffn2string(f2) + ")";
FIdentity(): "id";
FNegate(): "~";
FAddConst(d): "+#" + d2s(d);
FMulConst(d): "*#" + d2s(d);
FMaxConst(d): "max#" + safeToString(d);
FMinConst(d): "min#" + safeToString(d);
FEqual(v): "==" + safeToString(v);
FIf(t, e): "?" + safeToString(t) + ":" + safeToString(e);
}
}
ffn22string(fn : FFn2<?, ??, ???>) -> string {
switch (fn) {
FIdentity2(): "id";
FLift2(fl): trim2(takeAfter(safeToString(fn), ": ", safeToString(fn)), ")>");
FAddition(): "+";
FSubtract(): "-";
FMultiply(): "*";
FDivide(): "/";
FMax(): "max";
FMin(): "min";
FusionAnd() : "&&";
FusionOr() : "||";
FusionXor() : "^";
FusionWidthHeight() : "wh";
}
}
safeToString(t : flow) -> string {
if (isSameStructType(t, FLift(idfn))
|| isSameStructType(t, FLift2(\x, y -> x))) {
toString(t.fn)
} else if (isSameStructType(t, zero)) {
ct : ConstBehaviour<flow> = cast(t : flow -> ConstBehaviour<flow>);
"const(" + safeToString(getValue(ct)) + ")";
} else if (isSameStructType(t, FSelect(ConstBehaviour(flow(0)), FIdentity(), FDestroyed()))
|| isSameStructType(t, FSelect2(ConstBehaviour(flow(0)), ConstBehaviour(flow(0)), FAddition(), FDestroyed()))
|| isSameStructType(t, FSubSelect(ConstBehaviour(flow(0)), FIdentity(), FDestroyed()))
) {
ct : Transform<flow> = fselect(cast(t : flow -> Transform<?>), FLift(\v : ? -> cast(v : ? -> flow)));
transform2string(ct)
} else if (isArray(t)) "array"
else if (isSameStructType(t, t)) {
t.structname + "()"
} else toString(t);
}
/*
main() {
a = make(0);
b = make(1);
c = fselect2(a, b, FTuple2());
c0 = fselect(c, FTuple2Get0());
c1 = fselect(c, FTuple2Get1());
fc = fuse(c);
subscribe(fc.first, println);
fc0 = fuse(c0);
subscribe(fc0.first, println);
fc1 = fuse(c1);
subscribe(fc1.first, println);
next(a, 2);
next(b, 5);
}
*/
| {
"pile_set_name": "Github"
} |
config BR2_PACKAGE_LIBURCU
bool "liburcu"
depends on BR2_arm || BR2_armeb || BR2_i386 || BR2_powerpc || BR2_x86_64
depends on BR2_TOOLCHAIN_HAS_THREADS
help
Userspace implementation of the Read-Copy-Update (RCU)
synchronization mechanism. This library is mainly used by
the LTTng tracing infrastructure, but can be used for other
purposes as well.
http://lttng.org/urcu
comment "liburcu needs a toolchain w/ threads"
depends on BR2_arm || BR2_armeb || BR2_i386 || BR2_powerpc || BR2_x86_64
depends on !BR2_TOOLCHAIN_HAS_THREADS
| {
"pile_set_name": "Github"
} |
// externalfile.h -- Serve static files through HTTP/HTTPS
// Copyright (C) 2008-2009 Markus Gutschke <[email protected]>
//
// 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// In addition to these license terms, the author grants the following
// additional rights:
//
// If you modify this program, or any covered work, by linking or
// combining it with the OpenSSL project's OpenSSL library (or a
// modified version of that library), containing parts covered by the
// terms of the OpenSSL or SSLeay licenses, the author
// grants you additional permission to convey the resulting work.
// Corresponding Source for a non-source form of such a combination
// shall include the source code for the parts of OpenSSL used as well
// as that of the covered work.
//
// You may at your option choose to remove this additional permission from
// the work, or from any part of it.
//
// It is possible to build this program in a way that it loads OpenSSL
// libraries at run-time. If doing so, the following notices are required
// by the OpenSSL and SSLeay licenses:
//
// This product includes software developed by the OpenSSL Project
// for use in the OpenSSL Toolkit. (http://www.openssl.org/)
//
// This product includes cryptographic software written by Eric Young
// ([email protected])
//
//
// The most up-to-date version of this program is always available from
// http://shellinabox.com
#ifndef EXTERNALFILE_H__
#define EXTERNALFILE_H__
struct ExternalFileState {
int fd;
int totalSize;
int partialSize;
};
int registerExternalFiles(void *arg, const char *key, char **value);
#endif
| {
"pile_set_name": "Github"
} |
#
# MIT - (c) 2016 ThomasTJ (TTJ)
#
[FRAMEWORK]
NAME = WMDframe
VERSION = 1.0
DATE = 2017/01/01
AUTHOR = ThomasTJdev
[ENVIRONMENT]
# Your local update command
UPDATE_COMM = yaourt -S
#UPDATE_COMM = pacman -S
#UPDATE_COMM = apt-get update
#UPDATE_COMM = yum update
# Your local install command
INSTALL_COMM = yaourt -S
#INSTALL_COMM = pacman -S
#INSTALL_COMM = apt-get install
#INSTALL_COMM = yum install
# Your local editor
EDITOR = nano
#EDITOR = vim
#EDITOR = emacs
#EDITOR = atom
[NETWORK]
# Network connection
INTERFACE_NET = eno1
# Monitoring device
INTERFACE_MON = wlp0s29u1u1
# Interface where VPN is being initiated
INTERFACE_VPN = tun,ppp
[FILES]
CONFIG_LOGGING = core/config_logging.ini
MACS = files/macs.txt
PROXYLIST =files/proxies.txt
USERAGENTS = files/user_agents.txt
[SOFTWARE]
BETTERCAP = /usr/bin/bettercap
CREATEAP = /usr/bin/create_ap
DNSRECON = /usr/bin/dnsrecon
DNSMAP = /usr/bin/dnsmap
JOHN = /usr/bin/john
NMAP = /usr/bin/nmap
SPOOFCHECK = /usr/bin/spoofcheck
SQLMAP = /usr/bin/sqlmap
[TOOLS]
# Having weird installationpath, change SYM accordingly
ADMINFINDER_SYM = admin-finder
ADMINFINDER_GIT = https://github.com/Spaddex/Admin-Finder.git
ADMINFINDER_GITNAME = Admin-Finder
ADMINFINDER_GITRUN = AdminFinder.py
AIRCRACKNG_SYM = aircrack-ng
AIRCRACKNG_GIT =
AIRCRACKNG_GITNAME =
AIRCRACKNG_GITRUN =
AIRMONNG_SYM = airmon-ng
AIRMONNG_GIT =
AIRMONNG_GITNAME =
AIRMONNG_GITRUN =
AIRODUMPNG_SYM = airodump-ng
AIRODUMPNG_GIT =
AIRODUMPNG_GITNAME =
AIRODUMPNG_GITRUN =
AIROLIBNG_SYM = airolib-ng
AIROLIBNG_GIT =
AIROLIBNG_GITNAME =
AIROLIBNG_GITRUN =
AIREPLAYNG_SYM = aireplay-ng
AIREPLAYNG_GIT =
AIREPLAYNG_GITNAME =
AIREPLAYNG_GITRUN =
ARP_SYM = arp
ARP_GIT =
ARP_GITNAME =
ARP_GITRUN =
ARPSPOOF_SYM = arpspoof
ARPSPOOF_GIT =
ARPSPOOF_GITNAME =
ARPSPOOF_GITRUN =
BEEF_SYM = beef
BEEF_GIT =
BEEF_GITNAME =
BEEF_GITRUN =
BETTERCAP_SYM = bettercap
BETTERCAP_GIT =
BETTERCAP_GITNAME =
BETTERCAP_GITRUN =
CHANGEME_SYM =
CHANGEME_GIT = https://github.com/ztgrace/changeme.git
CHANGEME_GITNAME = changeme
CHANGEME_GITRUN = changeme.py
CREATEAP_SYM = create_ap
CREATEAP_GIT =
CREATEAP_GITNAME =
CREATEAP_GITRUN =
CRACKMAPEXEC_SYM = crackmapexec
CRACKMAPEXEC_GIT =
CRACKMAPEXEC_GITNAME =
CRACKMAPEXEC_GITRUN =
DIG_SYM = dig
DIG_GIT =
DIG_GITNAME =
DIG_GITRUN =
DNSMAP_SYM = dnsmap
DNSMAP_GIT =
DNSMAP_GITNAME =
DNSMAP_GITRUN =
DNSRECON_SYM = dnsrecon
DNSRECON_GIT = https://github.com/darkoperator/dnsrecon.git
DNSRECON_GITNAME = dnsrecon
DNSRECON_GITRUN = dnsrecon.py
EXPLOITDB_SYM = exploitdb
EXPLOITDB_GIT = https://github.com/mattoufoutu/exploitdb.git
EXPLOITDB_GITNAME = exploitdb
EXPLOITDB_GITRUN = exploitdb.py
HASHID_SYM = hashid
HASHID_GIT = https://github.com/psypanda/hashID.git
HASHID_GITNAME = hashID
HASHID_GITRUN = hashid.py
INSTABOT_SYM =
INSTABOT_GIT = https://github.com/LevPasha/instabot.py.git
INSTABOT_GITNAME = instabot.py
INSTABOT_GITRUN = example.py
JOHN_SYM = john
JOHN_GIT =
JOHN_GITNAME =
JOHN_GITRUN =
MACCHANGER_SYM = macchanger
MACCHANGER_GIT =
MACCHANGER_GITNAME =
MACCHANGER_GITRUN =
METASPLOIT_SYM = msfconsole
METASPLOIT_GIT =
METASPLOIT_GITNAME =
METASPLOIT_GITRUN =
NMAP_SYM = nmap
NMAP_GIT =
NMAP_GITNAME =
NMAP_GITRUN =
ROUTERSPLOIT_SYM = routersploit
ROUTERSPLOIT_GIT = https://github.com/reverse-shell/routersploit.git
ROUTERSPLOIT_GITNAME = routersploit
ROUTERSPLOIT_GITRUN = rsf.py
SPARTA_SYM = sparta
SPARTA_GIT =
SPARTA_GITNAME =
SPARTA_GITRUN =
SPOOFCHECK_SYM = spoofcheck
SPOOFCHECK_GIT = https://github.com/BishopFox/spoofcheck.git
SPOOFCHECK_GITNAME = spoofcheck
SPOOFCHECK_GITRUN = spoofcheck.py
SQLMAP_SYM = sqlmap
SQLMAP_GIT =
SQLMAP_GITNAME =
SQLMAP_GITRUN =
XSSER_SYM = xsser
XSSER_GIT = https://github.com/epsylon/xsser/tree/master/xsser-public
XSSER_GITNAME = xsser
XSSER_GITRUN = core/main.py
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<title>about - jekyll-3.2.1 Documentation</title>
<link type="text/css" media="screen" href="../../rdoc.css" rel="stylesheet">
<script type="text/javascript">
var rdoc_rel_prefix = "../../";
</script>
<script type="text/javascript" charset="utf-8" src="../../js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../../js/navigation.js"></script>
<script type="text/javascript" charset="utf-8" src="../../js/search_index.js"></script>
<script type="text/javascript" charset="utf-8" src="../../js/search.js"></script>
<script type="text/javascript" charset="utf-8" src="../../js/searcher.js"></script>
<script type="text/javascript" charset="utf-8" src="../../js/darkfish.js"></script>
<body class="file">
<nav id="metadata">
<nav id="home-section" class="section">
<h3 class="section-header">
<a href="../../index.html">Home</a>
<a href="../../table_of_contents.html#classes">Classes</a>
<a href="../../table_of_contents.html#methods">Methods</a>
</h3>
</nav>
<nav id="search-section" class="section project-section" class="initially-hidden">
<form action="#" method="get" accept-charset="utf-8">
<h3 class="section-header">
<input type="text" name="search" placeholder="Search" id="search-field"
title="Type to search, Up and Down to navigate, Enter to load">
</h3>
</form>
<ul id="search-results" class="initially-hidden"></ul>
</nav>
<div id="project-metadata">
<nav id="fileindex-section" class="section project-section">
<h3 class="section-header">Pages</h3>
<ul>
<li class="file"><a href="../../LICENSE.html">LICENSE</a>
<li class="file"><a href="../../README_markdown.html">README.markdown</a>
<li class="file"><a href="../../lib/jekyll/mime_types.html">mime.types</a>
<li class="file"><a href="../../lib/site_template/about_md.html">about</a>
<li class="file"><a href="../../lib/site_template/css/main_scss.html">main.scss</a>
<li class="file"><a href="../../lib/site_template/feed_xml.html">feed.xml</a>
<li class="file"><a href="../../lib/site_template/index_html.html">index.html</a>
<li class="file"><a href="../../lib/theme_template/Gemfile.html">Gemfile</a>
<li class="file"><a href="../../lib/theme_template/_layouts/default_html.html">default.html</a>
<li class="file"><a href="../../lib/theme_template/_layouts/page_html.html">page.html</a>
<li class="file"><a href="../../lib/theme_template/_layouts/post_html.html">post.html</a>
<li class="file"><a href="../../lib/theme_template/example/_post_md.html">_post</a>
<li class="file"><a href="../../lib/theme_template/example/index_html.html">index.html</a>
<li class="file"><a href="../../lib/theme_template/example/style_scss.html">style.scss</a>
</ul>
</nav>
<nav id="classindex-section" class="section project-section">
<h3 class="section-header">Class and Module Index</h3>
<ul class="link-list">
<li><a href="../../Jekyll.html">Jekyll</a>
<li><a href="../../Jekyll/Cleaner.html">Jekyll::Cleaner</a>
<li><a href="../../Jekyll/Collection.html">Jekyll::Collection</a>
<li><a href="../../Jekyll/CollectionReader.html">Jekyll::CollectionReader</a>
<li><a href="../../Jekyll/Command.html">Jekyll::Command</a>
<li><a href="../../Jekyll/Commands.html">Jekyll::Commands</a>
<li><a href="../../Jekyll/Commands/Build.html">Jekyll::Commands::Build</a>
<li><a href="../../Jekyll/Commands/Clean.html">Jekyll::Commands::Clean</a>
<li><a href="../../Jekyll/Commands/Doctor.html">Jekyll::Commands::Doctor</a>
<li><a href="../../Jekyll/Commands/Help.html">Jekyll::Commands::Help</a>
<li><a href="../../Jekyll/Commands/New.html">Jekyll::Commands::New</a>
<li><a href="../../Jekyll/Commands/NewTheme.html">Jekyll::Commands::NewTheme</a>
<li><a href="../../Jekyll/Commands/Serve.html">Jekyll::Commands::Serve</a>
<li><a href="../../Jekyll/Commands/Serve/Servlet.html">Jekyll::Commands::Serve::Servlet</a>
<li><a href="../../Jekyll/Configuration.html">Jekyll::Configuration</a>
<li><a href="../../Jekyll/Converter.html">Jekyll::Converter</a>
<li><a href="../../Jekyll/Converters.html">Jekyll::Converters</a>
<li><a href="../../Jekyll/Converters/Identity.html">Jekyll::Converters::Identity</a>
<li><a href="../../Jekyll/Converters/Markdown.html">Jekyll::Converters::Markdown</a>
<li><a href="../../Jekyll/Converters/Markdown/KramdownParser.html">Jekyll::Converters::Markdown::KramdownParser</a>
<li><a href="../../Jekyll/Converters/Markdown/RDiscountParser.html">Jekyll::Converters::Markdown::RDiscountParser</a>
<li><a href="../../Jekyll/Converters/Markdown/RedcarpetParser.html">Jekyll::Converters::Markdown::RedcarpetParser</a>
<li><a href="../../Jekyll/Converters/Markdown/RedcarpetParser/CommonMethods.html">Jekyll::Converters::Markdown::RedcarpetParser::CommonMethods</a>
<li><a href="../../Jekyll/Converters/Markdown/RedcarpetParser/WithPygments.html">Jekyll::Converters::Markdown::RedcarpetParser::WithPygments</a>
<li><a href="../../Jekyll/Converters/Markdown/RedcarpetParser/WithRouge.html">Jekyll::Converters::Markdown::RedcarpetParser::WithRouge</a>
<li><a href="../../Jekyll/Converters/Markdown/RedcarpetParser/WithoutHighlighting.html">Jekyll::Converters::Markdown::RedcarpetParser::WithoutHighlighting</a>
<li><a href="../../Jekyll/Converters/SmartyPants.html">Jekyll::Converters::SmartyPants</a>
<li><a href="../../Jekyll/Convertible.html">Jekyll::Convertible</a>
<li><a href="../../Jekyll/DataReader.html">Jekyll::DataReader</a>
<li><a href="../../Jekyll/Deprecator.html">Jekyll::Deprecator</a>
<li><a href="../../Jekyll/Document.html">Jekyll::Document</a>
<li><a href="../../Jekyll/Drops.html">Jekyll::Drops</a>
<li><a href="../../Jekyll/Drops/CollectionDrop.html">Jekyll::Drops::CollectionDrop</a>
<li><a href="../../Jekyll/Drops/DocumentDrop.html">Jekyll::Drops::DocumentDrop</a>
<li><a href="../../Jekyll/Drops/Drop.html">Jekyll::Drops::Drop</a>
<li><a href="../../Jekyll/Drops/ExcerptDrop.html">Jekyll::Drops::ExcerptDrop</a>
<li><a href="../../Jekyll/Drops/JekyllDrop.html">Jekyll::Drops::JekyllDrop</a>
<li><a href="../../Jekyll/Drops/SiteDrop.html">Jekyll::Drops::SiteDrop</a>
<li><a href="../../Jekyll/Drops/UnifiedPayloadDrop.html">Jekyll::Drops::UnifiedPayloadDrop</a>
<li><a href="../../Jekyll/Drops/UrlDrop.html">Jekyll::Drops::UrlDrop</a>
<li><a href="../../Jekyll/EntryFilter.html">Jekyll::EntryFilter</a>
<li><a href="../../Jekyll/Errors.html">Jekyll::Errors</a>
<li><a href="../../Jekyll/Excerpt.html">Jekyll::Excerpt</a>
<li><a href="../../Jekyll/External.html">Jekyll::External</a>
<li><a href="../../Jekyll/Filters.html">Jekyll::Filters</a>
<li><a href="../../Jekyll/FrontmatterDefaults.html">Jekyll::FrontmatterDefaults</a>
<li><a href="../../Jekyll/Hooks.html">Jekyll::Hooks</a>
<li><a href="../../Jekyll/Layout.html">Jekyll::Layout</a>
<li><a href="../../Jekyll/LayoutReader.html">Jekyll::LayoutReader</a>
<li><a href="../../Jekyll/LiquidExtensions.html">Jekyll::LiquidExtensions</a>
<li><a href="../../Jekyll/LiquidRenderer.html">Jekyll::LiquidRenderer</a>
<li><a href="../../Jekyll/LiquidRenderer/File.html">Jekyll::LiquidRenderer::File</a>
<li><a href="../../Jekyll/LiquidRenderer/Table.html">Jekyll::LiquidRenderer::Table</a>
<li><a href="../../Jekyll/LogAdapter.html">Jekyll::LogAdapter</a>
<li><a href="../../Jekyll/Page.html">Jekyll::Page</a>
<li><a href="../../Jekyll/PageReader.html">Jekyll::PageReader</a>
<li><a href="../../Jekyll/Plugin.html">Jekyll::Plugin</a>
<li><a href="../../Jekyll/PluginManager.html">Jekyll::PluginManager</a>
<li><a href="../../Jekyll/PostReader.html">Jekyll::PostReader</a>
<li><a href="../../Jekyll/Publisher.html">Jekyll::Publisher</a>
<li><a href="../../Jekyll/Reader.html">Jekyll::Reader</a>
<li><a href="../../Jekyll/Regenerator.html">Jekyll::Regenerator</a>
<li><a href="../../Jekyll/RelatedPosts.html">Jekyll::RelatedPosts</a>
<li><a href="../../Jekyll/Renderer.html">Jekyll::Renderer</a>
<li><a href="../../Jekyll/Site.html">Jekyll::Site</a>
<li><a href="../../Jekyll/StaticFile.html">Jekyll::StaticFile</a>
<li><a href="../../Jekyll/StaticFileReader.html">Jekyll::StaticFileReader</a>
<li><a href="../../Jekyll/Stevenson.html">Jekyll::Stevenson</a>
<li><a href="../../Jekyll/Tags.html">Jekyll::Tags</a>
<li><a href="../../Jekyll/Tags/HighlightBlock.html">Jekyll::Tags::HighlightBlock</a>
<li><a href="../../Jekyll/Tags/IncludeRelativeTag.html">Jekyll::Tags::IncludeRelativeTag</a>
<li><a href="../../Jekyll/Tags/IncludeTag.html">Jekyll::Tags::IncludeTag</a>
<li><a href="../../Jekyll/Tags/IncludeTagError.html">Jekyll::Tags::IncludeTagError</a>
<li><a href="../../Jekyll/Tags/Link.html">Jekyll::Tags::Link</a>
<li><a href="../../Jekyll/Tags/PostComparer.html">Jekyll::Tags::PostComparer</a>
<li><a href="../../Jekyll/Tags/PostUrl.html">Jekyll::Tags::PostUrl</a>
<li><a href="../../Jekyll/Theme.html">Jekyll::Theme</a>
<li><a href="../../Jekyll/ThemeBuilder.html">Jekyll::ThemeBuilder</a>
<li><a href="../../Jekyll/ThemeBuilder/ERBRenderer.html">Jekyll::ThemeBuilder::ERBRenderer</a>
<li><a href="../../Jekyll/URL.html">Jekyll::URL</a>
<li><a href="../../Jekyll/Utils.html">Jekyll::Utils</a>
<li><a href="../../Jekyll/Utils/Ansi.html">Jekyll::Utils::Ansi</a>
<li><a href="../../Jekyll/Utils/Platforms.html">Jekyll::Utils::Platforms</a>
<li><a href="../../Jekyll/Utils/Platforms/RbConfig.html">Jekyll::Utils::Platforms::RbConfig</a>
<li><a href="../../Kramdown.html">Kramdown</a>
<li><a href="../../Kramdown/Parser.html">Kramdown::Parser</a>
<li><a href="../../Kramdown/Parser/SmartyPants.html">Kramdown::Parser::SmartyPants</a>
<li><a href="../../Liquid.html">Liquid</a>
<li><a href="../../Object.html">Object</a>
<li><a href="../../SafeYAML.html">SafeYAML</a>
</ul>
</nav>
</div>
</nav>
<div id="documentation" class="description">
<p>—
layout: page
title: About</p>
<h2 id="label-permalink%3A+%2Fabout%2F">permalink: /about/<span><a href="#label-permalink%3A+%2Fabout%2F">¶</a> <a href="#documentation">↑</a></span></h2>
<p>This is the base <a href="../../Jekyll.html">Jekyll</a> theme. You can find
out more info about customizing your <a href="../../Jekyll.html">Jekyll</a>
theme, as well as basic <a href="../../Jekyll.html">Jekyll</a> usage
documentation at <a href="http://jekyllrb.com/">jekyllrb.com</a></p>
<p>You can find the source code for the <a href="../../Jekyll.html">Jekyll</a>
new theme at:
{% include icon-github.html username="jekyll" %}
/
<a href="https://github.com/jekyll/minima">minima</a></p>
<p>You can find the source code for <a href="../../Jekyll.html">Jekyll</a>
at
{% include icon-github.html username="jekyll" %} /
<a
href="https://github.com/jekyll/jekyll">jekyll</a></p>
</div>
<footer id="validator-badges">
<p><a href="http://validator.w3.org/check/referer">[Validate]</a>
<p>Generated by <a href="https://github.com/rdoc/rdoc">RDoc</a> 4.0.0.
<p>Generated with the <a href="http://deveiate.org/projects/Darkfish-Rdoc/">Darkfish Rdoc Generator</a> 3.
</footer>
| {
"pile_set_name": "Github"
} |
{
"injectionSwitch": {
"func": "glUniform2f",
"args": [
0.0,
1.0
]
},
"resolution": {
"func": "glUniform2f",
"args": [
256.0,
256.0
]
},
"$compute": {
"num_groups": [
1,
3,
1
],
"buffer": {
"binding": 0,
"fields": [
{
"type": "vec4",
"data": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0
]
}
]
}
}
}
| {
"pile_set_name": "Github"
} |
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.safari;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.openqa.selenium.Platform.MAC;
import com.google.auto.service.AutoService;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.net.PortProber;
import org.openqa.selenium.remote.BrowserType;
import org.openqa.selenium.remote.service.DriverService;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class SafariDriverService extends DriverService {
/**
* System property that defines the location of the safaridriver executable that will be used by
* the {@link #createDefaultService() default service}.
*/
public static final String SAFARI_DRIVER_EXE_PROPERTY = "webdriver.safari.driver";
private static final File SAFARI_DRIVER_EXECUTABLE = new File("/usr/bin/safaridriver");
private static final File TP_SAFARI_DRIVER_EXECUTABLE =
new File("/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver");
public SafariDriverService(
File executable,
int port,
List<String> args,
Map<String, String> environment) throws IOException {
super(executable, port, DEFAULT_TIMEOUT, args, environment);
}
public SafariDriverService(
File executable,
int port,
Duration timeout,
List<String> args,
Map<String, String> environment) throws IOException {
super(executable, port, timeout, args, environment);
}
public static SafariDriverService createDefaultService() {
return createDefaultService(new SafariOptions());
}
static SafariDriverService createDefaultService(SafariOptions options) {
return new Builder().usingTechnologyPreview(options.getUseTechnologyPreview()).build();
}
static SafariDriverService createDefaultService(Capabilities caps) {
return createDefaultService(new SafariOptions(caps));
}
@Override
protected void waitUntilAvailable() {
try {
PortProber.waitForPortUp(getUrl().getPort(), (int) getTimeout().toMillis(), MILLISECONDS);
} catch (RuntimeException e) {
throw new WebDriverException(e);
}
}
@AutoService(DriverService.Builder.class)
public static class Builder extends DriverService.Builder<
SafariDriverService, SafariDriverService.Builder> {
private boolean useTechnologyPreview = false;
@Override
public int score(Capabilities capabilities) {
int score = 0;
if (BrowserType.SAFARI.equals(capabilities.getBrowserName())) {
score++;
} else if ("Safari Technology Preview".equals(capabilities.getBrowserName())) {
score++;
}
if (capabilities.getCapability(SafariOptions.CAPABILITY) != null) {
score++;
}
if (capabilities.getCapability("se:safari:techPreview") != null) {
score++;
}
return score;
}
public SafariDriverService.Builder usingTechnologyPreview(boolean useTechnologyPreview) {
this.useTechnologyPreview = useTechnologyPreview;
return this;
}
@Override
protected File findDefaultExecutable() {
File exe;
if (System.getProperty(SAFARI_DRIVER_EXE_PROPERTY) != null) {
exe = new File(System.getProperty(SAFARI_DRIVER_EXE_PROPERTY));
} else if (useTechnologyPreview) {
exe = TP_SAFARI_DRIVER_EXECUTABLE;
} else {
exe = SAFARI_DRIVER_EXECUTABLE;
}
if (!exe.isFile()) {
StringBuilder message = new StringBuilder();
message.append("Unable to find driver executable: ").append(exe);
if (!isElCapitanOrLater()) {
message.append("(SafariDriver requires Safari 10 running on OSX El Capitan or greater.)");
}
throw new WebDriverException(message.toString());
}
return exe;
}
private boolean isElCapitanOrLater() {
if (!Platform.getCurrent().is(MAC)) {
return false;
}
// If we're using a version of macOS later than 10, we're set.
if (Platform.getCurrent().getMajorVersion() > 10) {
return true;
}
// Check the El Capitan version
return Platform.getCurrent().getMajorVersion() == 10 &&
Platform.getCurrent().getMinorVersion() >= 11;
}
@Override
protected List<String> createArgs() {
return Arrays.asList("--port", String.valueOf(getPort()));
}
@Override
protected SafariDriverService createDriverService(
File exe,
int port,
Duration timeout,
List<String> args,
Map<String, String> environment) {
try {
return new SafariDriverService(exe, port, timeout, args, environment);
} catch (IOException e) {
throw new WebDriverException(e);
}
}
}
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the HTML sanitizer project.
*
* (c) Titouan Galopin <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\HtmlSanitizer\Sanitizer;
use HtmlSanitizer\Extension\Basic\Sanitizer\AHrefSanitizer;
use PHPUnit\Framework\TestCase;
class AHrefSanitizerTest extends TestCase
{
public function provideUrls()
{
// Simple cases
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => null,
'allowMailTo' => false,
'forceHttps' => false,
'input' => 'https://trusted.com/link.php',
'output' => 'https://trusted.com/link.php',
];
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => ['trusted.com'],
'allowMailTo' => false,
'forceHttps' => false,
'input' => 'https://trusted.com/link.php',
'output' => 'https://trusted.com/link.php',
];
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => ['trusted.com'],
'allowMailTo' => false,
'forceHttps' => false,
'input' => 'https://untrusted.com/link.php',
'output' => null,
];
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => null,
'allowMailTo' => false,
'forceHttps' => false,
'input' => '/link.php',
'output' => null,
];
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => null,
'allowMailTo' => true,
'forceHttps' => false,
'input' => '/link.php',
'output' => null,
];
// Force HTTPS
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => ['trusted.com'],
'allowMailTo' => false,
'forceHttps' => true,
'input' => 'http://trusted.com/link.php',
'output' => 'https://trusted.com/link.php',
];
// Data-URI not allowed
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => null,
'allowMailTo' => true,
'forceHttps' => false,
'input' => 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
'output' => null,
];
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => null,
'allowMailTo' => true,
'forceHttps' => true,
'input' => 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
'output' => null,
];
// MailTo
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => null,
'allowMailTo' => false,
'forceHttps' => false,
'input' => 'mailto:[email protected]',
'output' => null,
];
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => null,
'allowMailTo' => true,
'forceHttps' => false,
'input' => 'mailto:[email protected]',
'output' => 'mailto:[email protected]',
];
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => ['trusted.com'],
'allowMailTo' => true,
'forceHttps' => false,
'input' => 'mailto:[email protected]',
'output' => 'mailto:[email protected]',
];
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => ['trusted.com'],
'allowMailTo' => true,
'forceHttps' => true,
'input' => 'mailto:[email protected]',
'output' => 'mailto:[email protected]',
];
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => null,
'allowMailTo' => true,
'forceHttps' => false,
'input' => 'mailto:invalid',
'output' => null,
];
yield [
'allowedSchemes' => ['http', 'https'],
'allowedHosts' => null,
'allowMailTo' => true,
'forceHttps' => false,
'input' => 'mailto:',
'output' => null,
];
yield [
'allowedSchemes' => ['https'],
'allowedHosts' => null,
'allowMailTo' => true,
'forceHttps' => false,
'input' => 'http://trusted.com/link.php',
'output' => null,
];
}
/**
* @dataProvider provideUrls
*/
public function testSanitize($allowedSchemes, $allowedHosts, $allowMailTo, $forceHttps, $input, $expected)
{
$this->assertSame($expected, (new AHrefSanitizer($allowedSchemes, $allowedHosts, $allowMailTo, $forceHttps))->sanitize($input));
}
}
| {
"pile_set_name": "Github"
} |
*> \brief <b> CSYSV_AA_2STAGE computes the solution to system of linear equations A * X = B for SY matrices</b>
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download CSYSV_AA_2STAGE + dependencies
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/csysv_aasen_2stage.f">
*> [TGZ]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/csysv_aasen_2stage.f">
*> [ZIP]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/csysv_aasen_2stage.f">
*> [TXT]</a>
*> \endhtmlonly
*
* Definition:
* ===========
*
* SUBROUTINE CSYSV_AA_2STAGE( UPLO, N, NRHS, A, LDA, TB, LTB,
* IPIV, IPIV2, B, LDB, WORK, LWORK,
* INFO )
*
* .. Scalar Arguments ..
* CHARACTER UPLO
* INTEGER N, NRHS, LDA, LTB, LDB, LWORK, INFO
* ..
* .. Array Arguments ..
* INTEGER IPIV( * ), IPIV2( * )
* COMPLEX A( LDA, * ), TB( * ), B( LDB, *), WORK( * )
* ..
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> CSYSV_AA_2STAGE computes the solution to a complex system of
*> linear equations
*> A * X = B,
*> where A is an N-by-N symmetric matrix and X and B are N-by-NRHS
*> matrices.
*>
*> Aasen's 2-stage algorithm is used to factor A as
*> A = U * T * U**H, if UPLO = 'U', or
*> A = L * T * L**H, if UPLO = 'L',
*> where U (or L) is a product of permutation and unit upper (lower)
*> triangular matrices, and T is symmetric and band. The matrix T is
*> then LU-factored with partial pivoting. The factored form of A
*> is then used to solve the system of equations A * X = B.
*>
*> This is the blocked version of the algorithm, calling Level 3 BLAS.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] UPLO
*> \verbatim
*> UPLO is CHARACTER*1
*> = 'U': Upper triangle of A is stored;
*> = 'L': Lower triangle of A is stored.
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*> N is INTEGER
*> The order of the matrix A. N >= 0.
*> \endverbatim
*>
*> \param[in] NRHS
*> \verbatim
*> NRHS is INTEGER
*> The number of right hand sides, i.e., the number of columns
*> of the matrix B. NRHS >= 0.
*> \endverbatim
*>
*> \param[in,out] A
*> \verbatim
*> A is COMPLEX array, dimension (LDA,N)
*> On entry, the symmetric matrix A. If UPLO = 'U', the leading
*> N-by-N upper triangular part of A contains the upper
*> triangular part of the matrix A, and the strictly lower
*> triangular part of A is not referenced. If UPLO = 'L', the
*> leading N-by-N lower triangular part of A contains the lower
*> triangular part of the matrix A, and the strictly upper
*> triangular part of A is not referenced.
*>
*> On exit, L is stored below (or above) the subdiaonal blocks,
*> when UPLO is 'L' (or 'U').
*> \endverbatim
*>
*> \param[in] LDA
*> \verbatim
*> LDA is INTEGER
*> The leading dimension of the array A. LDA >= max(1,N).
*> \endverbatim
*>
*> \param[out] TB
*> \verbatim
*> TB is COMPLEX array, dimension (LTB)
*> On exit, details of the LU factorization of the band matrix.
*> \endverbatim
*>
*> \param[in] LTB
*> \verbatim
*> The size of the array TB. LTB >= 4*N, internally
*> used to select NB such that LTB >= (3*NB+1)*N.
*>
*> If LTB = -1, then a workspace query is assumed; the
*> routine only calculates the optimal size of LTB,
*> returns this value as the first entry of TB, and
*> no error message related to LTB is issued by XERBLA.
*> \endverbatim
*>
*> \param[out] IPIV
*> \verbatim
*> IPIV is INTEGER array, dimension (N)
*> On exit, it contains the details of the interchanges, i.e.,
*> the row and column k of A were interchanged with the
*> row and column IPIV(k).
*> \endverbatim
*>
*> \param[out] IPIV2
*> \verbatim
*> IPIV is INTEGER array, dimension (N)
*> On exit, it contains the details of the interchanges, i.e.,
*> the row and column k of T were interchanged with the
*> row and column IPIV(k).
*> \endverbatim
*>
*> \param[in,out] B
*> \verbatim
*> B is COMPLEX array, dimension (LDB,NRHS)
*> On entry, the right hand side matrix B.
*> On exit, the solution matrix X.
*> \endverbatim
*>
*> \param[in] LDB
*> \verbatim
*> LDB is INTEGER
*> The leading dimension of the array B. LDB >= max(1,N).
*> \endverbatim
*>
*> \param[out] WORK
*> \verbatim
*> WORK is COMPLEX workspace of size LWORK
*> \endverbatim
*>
*> \param[in] LWORK
*> \verbatim
*> The size of WORK. LWORK >= N, internally used to select NB
*> such that LWORK >= N*NB.
*>
*> If LWORK = -1, then a workspace query is assumed; the
*> routine only calculates the optimal size of the WORK array,
*> returns this value as the first entry of the WORK array, and
*> no error message related to LWORK is issued by XERBLA.
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*> INFO is INTEGER
*> = 0: successful exit
*> < 0: if INFO = -i, the i-th argument had an illegal value.
*> > 0: if INFO = i, band LU factorization failed on i-th column
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date November 2017
*
*> \ingroup complexSYcomputational
*
* =====================================================================
SUBROUTINE CSYSV_AA_2STAGE( UPLO, N, NRHS, A, LDA, TB, LTB,
$ IPIV, IPIV2, B, LDB, WORK, LWORK,
$ INFO )
*
* -- LAPACK computational routine (version 3.8.0) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* November 2017
*
IMPLICIT NONE
*
* .. Scalar Arguments ..
CHARACTER UPLO
INTEGER N, NRHS, LDA, LDB, LTB, LWORK, INFO
* ..
* .. Array Arguments ..
INTEGER IPIV( * ), IPIV2( * )
COMPLEX A( LDA, * ), B( LDB, * ), TB( * ), WORK( * )
* ..
*
* =====================================================================
*
* .. Local Scalars ..
LOGICAL UPPER, TQUERY, WQUERY
INTEGER LWKOPT
* ..
* .. External Functions ..
LOGICAL LSAME
EXTERNAL LSAME
* ..
* .. External Subroutines ..
EXTERNAL CSYTRF_AA_2STAGE,
$ CSYTRS_AA_2STAGE, XERBLA
* ..
* .. Intrinsic Functions ..
INTRINSIC MAX
* ..
* .. Executable Statements ..
*
* Test the input parameters.
*
INFO = 0
UPPER = LSAME( UPLO, 'U' )
WQUERY = ( LWORK.EQ.-1 )
TQUERY = ( LTB.EQ.-1 )
IF( .NOT.UPPER .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN
INFO = -1
ELSE IF( N.LT.0 ) THEN
INFO = -2
ELSE IF( NRHS.LT.0 ) THEN
INFO = -3
ELSE IF( LDA.LT.MAX( 1, N ) ) THEN
INFO = -5
ELSE IF( LDB.LT.MAX( 1, N ) ) THEN
INFO = -11
END IF
*
IF( INFO.EQ.0 ) THEN
CALL CSYTRF_AA_2STAGE( UPLO, N, A, LDA, TB, -1, IPIV,
$ IPIV2, WORK, -1, INFO )
LWKOPT = INT( WORK(1) )
IF( LTB.LT.INT( TB(1) ) .AND. .NOT.TQUERY ) THEN
INFO = -7
ELSE IF( LWORK.LT.LWKOPT .AND. .NOT.WQUERY ) THEN
INFO = -13
END IF
END IF
*
IF( INFO.NE.0 ) THEN
CALL XERBLA( 'CSYSV_AA_2STAGE', -INFO )
RETURN
ELSE IF( WQUERY .OR. TQUERY ) THEN
RETURN
END IF
*
*
* Compute the factorization A = U*T*U**H or A = L*T*L**H.
*
CALL CSYTRF_AA_2STAGE( UPLO, N, A, LDA, TB, LTB, IPIV, IPIV2,
$ WORK, LWORK, INFO )
IF( INFO.EQ.0 ) THEN
*
* Solve the system A*X = B, overwriting B with X.
*
CALL CSYTRS_AA_2STAGE( UPLO, N, NRHS, A, LDA, TB, LTB, IPIV,
$ IPIV2, B, LDB, INFO )
*
END IF
*
WORK( 1 ) = LWKOPT
*
* End of CSYSV_AA_2STAGE
*
END
| {
"pile_set_name": "Github"
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko.annotationProcessors.classloader;
import java.util.Iterator;
/**
* Class for iterating over an IterableJarLoadingURLClassLoader's classes.
*/
public class JarClassIterator implements Iterator<ClassWithOptions> {
private IterableJarLoadingURLClassLoader mTarget;
private Iterator<String> mTargetClassListIterator;
public JarClassIterator(IterableJarLoadingURLClassLoader aTarget) {
mTarget = aTarget;
mTargetClassListIterator = aTarget.classNames.iterator();
}
@Override
public boolean hasNext() {
return mTargetClassListIterator.hasNext();
}
@Override
public ClassWithOptions next() {
String className = mTargetClassListIterator.next();
try {
Class<?> ret = mTarget.loadClass(className);
final String canonicalName;
// Incremental builds can leave stale classfiles in the jar. Such classfiles will cause
// an exception at this point. We can safely ignore these classes - they cannot possibly
// ever be loaded as they conflict with their parent class and will be killed by Proguard
// later on anyway.
try {
canonicalName = ret.getCanonicalName();
} catch (IncompatibleClassChangeError e) {
return next();
}
if (canonicalName == null || "null".equals(canonicalName)) {
// Anonymous inner class - unsupported.
return next();
}
return new ClassWithOptions(ret, ret.getSimpleName());
} catch (ClassNotFoundException e) {
System.err.println("Unable to enumerate class: " + className + ". Corrupted jar file?");
e.printStackTrace();
System.exit(2);
}
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Removal of classes from iterator not supported.");
}
}
| {
"pile_set_name": "Github"
} |
import _plotly_utils.basevalidators
class ColorbarValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="colorbar", parent_name="heatmap", **kwargs):
super(ColorbarValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "ColorBar"),
data_docs=kwargs.pop(
"data_docs",
"""
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing
this color bar.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
len
Sets the length of the color bar This measure
excludes the padding of both ends. That is, the
color bar length is this length minus the
padding on both ends.
lenmode
Determines whether this color bar's length
(i.e. the measure in the color variation
direction) is set in units of plot "fraction"
or in *pixels. Use `len` to set the value.
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This
measure excludes the size of the padding, ticks
and labels.
thicknessmode
Determines whether this color bar's thickness
(i.e. the measure in the constant color
direction) is set in units of plot "fraction"
or in "pixels". Use `thickness` to set the
value.
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see:
https://github.com/d3/d3-3.x-api-
reference/blob/master/Formatting.md#d3_format
And for dates see:
https://github.com/d3/d3-time-
format#locale_format We add one item to d3's
date formatter: "%{n}f" for fractional seconds
with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f"
would display "09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.heatmap
.colorbar.Tickformatstop` instances or dicts
with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.dat
a.heatmap.colorbar.tickformatstopdefaults),
sets the default property values to use for
elements of heatmap.colorbar.tickformatstops
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for ticktext .
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for tickvals .
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.heatmap.colorbar.T
itle` instance or dict with compatible
properties
titlefont
Deprecated: Please use
heatmap.colorbar.title.font instead. Sets this
color bar's title font. Note that the title's
font used to be set by the now deprecated
`titlefont` attribute.
titleside
Deprecated: Please use
heatmap.colorbar.title.side instead. Determines
the location of color bar's title with respect
to the color bar. Note that the title's
location used to be set by the now deprecated
`titleside` attribute.
x
Sets the x position of the color bar (in plot
fraction).
xanchor
Sets this color bar's horizontal position
anchor. This anchor binds the `x` position to
the "left", "center" or "right" of the color
bar.
xpad
Sets the amount of padding (in px) along the x
direction.
y
Sets the y position of the color bar (in plot
fraction).
yanchor
Sets this color bar's vertical position anchor
This anchor binds the `y` position to the
"top", "middle" or "bottom" of the color bar.
ypad
Sets the amount of padding (in px) along the y
direction.
""",
),
**kwargs
)
| {
"pile_set_name": "Github"
} |
/*
* This file is part of UBIFS.
*
* Copyright (C) 2006-2008 Nokia Corporation
*
* 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.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Authors: Adrian Hunter
* Artem Bityutskiy (Битюцкий Артём)
*/
/*
* This file implements the scan which is a general-purpose function for
* determining what nodes are in an eraseblock. The scan is used to replay the
* journal, to do garbage collection. for the TNC in-the-gaps method, and by
* debugging functions.
*/
#include "ubifs.h"
/**
* scan_padding_bytes - scan for padding bytes.
* @buf: buffer to scan
* @len: length of buffer
*
* This function returns the number of padding bytes on success and
* %SCANNED_GARBAGE on failure.
*/
static int scan_padding_bytes(void *buf, int len)
{
int pad_len = 0, max_pad_len = min_t(int, UBIFS_PAD_NODE_SZ, len);
uint8_t *p = buf;
dbg_scan("not a node");
while (pad_len < max_pad_len && *p++ == UBIFS_PADDING_BYTE)
pad_len += 1;
if (!pad_len || (pad_len & 7))
return SCANNED_GARBAGE;
dbg_scan("%d padding bytes", pad_len);
return pad_len;
}
/**
* ubifs_scan_a_node - scan for a node or padding.
* @c: UBIFS file-system description object
* @buf: buffer to scan
* @len: length of buffer
* @lnum: logical eraseblock number
* @offs: offset within the logical eraseblock
* @quiet: print no messages
*
* This function returns a scanning code to indicate what was scanned.
*/
int ubifs_scan_a_node(const struct ubifs_info *c, void *buf, int len, int lnum,
int offs, int quiet)
{
struct ubifs_ch *ch = buf;
uint32_t magic;
magic = le32_to_cpu(ch->magic);
if (magic == 0xFFFFFFFF) {
dbg_scan("hit empty space");
return SCANNED_EMPTY_SPACE;
}
if (magic != UBIFS_NODE_MAGIC)
return scan_padding_bytes(buf, len);
if (len < UBIFS_CH_SZ)
return SCANNED_GARBAGE;
dbg_scan("scanning %s", dbg_ntype(ch->node_type));
if (ubifs_check_node(c, buf, lnum, offs, quiet, 1))
return SCANNED_A_CORRUPT_NODE;
if (ch->node_type == UBIFS_PAD_NODE) {
struct ubifs_pad_node *pad = buf;
int pad_len = le32_to_cpu(pad->pad_len);
int node_len = le32_to_cpu(ch->len);
/* Validate the padding node */
if (pad_len < 0 ||
offs + node_len + pad_len > c->leb_size) {
if (!quiet) {
ubifs_err("bad pad node at LEB %d:%d",
lnum, offs);
dbg_dump_node(c, pad);
}
return SCANNED_A_BAD_PAD_NODE;
}
/* Make the node pads to 8-byte boundary */
if ((node_len + pad_len) & 7) {
if (!quiet) {
dbg_err("bad padding length %d - %d",
offs, offs + node_len + pad_len);
}
return SCANNED_A_BAD_PAD_NODE;
}
dbg_scan("%d bytes padded, offset now %d",
pad_len, ALIGN(offs + node_len + pad_len, 8));
return node_len + pad_len;
}
return SCANNED_A_NODE;
}
/**
* ubifs_start_scan - create LEB scanning information at start of scan.
* @c: UBIFS file-system description object
* @lnum: logical eraseblock number
* @offs: offset to start at (usually zero)
* @sbuf: scan buffer (must be c->leb_size)
*
* This function returns %0 on success and a negative error code on failure.
*/
struct ubifs_scan_leb *ubifs_start_scan(const struct ubifs_info *c, int lnum,
int offs, void *sbuf)
{
struct ubifs_scan_leb *sleb;
int err;
dbg_scan("scan LEB %d:%d", lnum, offs);
sleb = kzalloc(sizeof(struct ubifs_scan_leb), GFP_NOFS);
if (!sleb)
return ERR_PTR(-ENOMEM);
sleb->lnum = lnum;
INIT_LIST_HEAD(&sleb->nodes);
sleb->buf = sbuf;
err = ubi_read(c->ubi, lnum, sbuf + offs, offs, c->leb_size - offs);
if (err && err != -EBADMSG) {
ubifs_err("cannot read %d bytes from LEB %d:%d,"
" error %d", c->leb_size - offs, lnum, offs, err);
kfree(sleb);
return ERR_PTR(err);
}
if (err == -EBADMSG)
sleb->ecc = 1;
return sleb;
}
/**
* ubifs_end_scan - update LEB scanning information at end of scan.
* @c: UBIFS file-system description object
* @sleb: scanning information
* @lnum: logical eraseblock number
* @offs: offset to start at (usually zero)
*
* This function returns %0 on success and a negative error code on failure.
*/
void ubifs_end_scan(const struct ubifs_info *c, struct ubifs_scan_leb *sleb,
int lnum, int offs)
{
lnum = lnum;
dbg_scan("stop scanning LEB %d at offset %d", lnum, offs);
ubifs_assert(offs % c->min_io_size == 0);
sleb->endpt = ALIGN(offs, c->min_io_size);
}
/**
* ubifs_add_snod - add a scanned node to LEB scanning information.
* @c: UBIFS file-system description object
* @sleb: scanning information
* @buf: buffer containing node
* @offs: offset of node on flash
*
* This function returns %0 on success and a negative error code on failure.
*/
int ubifs_add_snod(const struct ubifs_info *c, struct ubifs_scan_leb *sleb,
void *buf, int offs)
{
struct ubifs_ch *ch = buf;
struct ubifs_ino_node *ino = buf;
struct ubifs_scan_node *snod;
snod = kzalloc(sizeof(struct ubifs_scan_node), GFP_NOFS);
if (!snod)
return -ENOMEM;
snod->sqnum = le64_to_cpu(ch->sqnum);
snod->type = ch->node_type;
snod->offs = offs;
snod->len = le32_to_cpu(ch->len);
snod->node = buf;
switch (ch->node_type) {
case UBIFS_INO_NODE:
case UBIFS_DENT_NODE:
case UBIFS_XENT_NODE:
case UBIFS_DATA_NODE:
case UBIFS_TRUN_NODE:
/*
* The key is in the same place in all keyed
* nodes.
*/
key_read(c, &ino->key, &snod->key);
break;
}
list_add_tail(&snod->list, &sleb->nodes);
sleb->nodes_cnt += 1;
return 0;
}
/**
* ubifs_scanned_corruption - print information after UBIFS scanned corruption.
* @c: UBIFS file-system description object
* @lnum: LEB number of corruption
* @offs: offset of corruption
* @buf: buffer containing corruption
*/
void ubifs_scanned_corruption(const struct ubifs_info *c, int lnum, int offs,
void *buf)
{
int len;
ubifs_err("corrupted data at LEB %d:%d", lnum, offs);
if (dbg_failure_mode)
return;
len = c->leb_size - offs;
if (len > 4096)
len = 4096;
dbg_err("first %d bytes from LEB %d:%d", len, lnum, offs);
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 4, buf, len, 1);
}
/**
* ubifs_scan - scan a logical eraseblock.
* @c: UBIFS file-system description object
* @lnum: logical eraseblock number
* @offs: offset to start at (usually zero)
* @sbuf: scan buffer (must be c->leb_size)
*
* This function scans LEB number @lnum and returns complete information about
* its contents. Returns an error code in case of failure.
*/
struct ubifs_scan_leb *ubifs_scan(const struct ubifs_info *c, int lnum,
int offs, void *sbuf)
{
void *buf = sbuf + offs;
int err, len = c->leb_size - offs;
struct ubifs_scan_leb *sleb;
sleb = ubifs_start_scan(c, lnum, offs, sbuf);
if (IS_ERR(sleb))
return sleb;
while (len >= 8) {
struct ubifs_ch *ch = buf;
int node_len, ret;
dbg_scan("look at LEB %d:%d (%d bytes left)",
lnum, offs, len);
cond_resched();
ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 0);
if (ret > 0) {
/* Padding bytes or a valid padding node */
offs += ret;
buf += ret;
len -= ret;
continue;
}
if (ret == SCANNED_EMPTY_SPACE)
/* Empty space is checked later */
break;
switch (ret) {
case SCANNED_GARBAGE:
dbg_err("garbage");
goto corrupted;
case SCANNED_A_NODE:
break;
case SCANNED_A_CORRUPT_NODE:
case SCANNED_A_BAD_PAD_NODE:
dbg_err("bad node");
goto corrupted;
default:
dbg_err("unknown");
goto corrupted;
}
err = ubifs_add_snod(c, sleb, buf, offs);
if (err)
goto error;
node_len = ALIGN(le32_to_cpu(ch->len), 8);
offs += node_len;
buf += node_len;
len -= node_len;
}
if (offs % c->min_io_size)
goto corrupted;
ubifs_end_scan(c, sleb, lnum, offs);
for (; len > 4; offs += 4, buf = buf + 4, len -= 4)
if (*(uint32_t *)buf != 0xffffffff)
break;
for (; len; offs++, buf++, len--)
if (*(uint8_t *)buf != 0xff) {
ubifs_err("corrupt empty space at LEB %d:%d",
lnum, offs);
goto corrupted;
}
return sleb;
corrupted:
ubifs_scanned_corruption(c, lnum, offs, buf);
err = -EUCLEAN;
error:
ubifs_err("LEB %d scanning failed", lnum);
ubifs_scan_destroy(sleb);
return ERR_PTR(err);
}
/**
* ubifs_scan_destroy - destroy LEB scanning information.
* @sleb: scanning information to free
*/
void ubifs_scan_destroy(struct ubifs_scan_leb *sleb)
{
struct ubifs_scan_node *node;
struct list_head *head;
head = &sleb->nodes;
while (!list_empty(head)) {
node = list_entry(head->next, struct ubifs_scan_node, list);
list_del(&node->list);
kfree(node);
}
kfree(sleb);
}
| {
"pile_set_name": "Github"
} |
--****************************************************************************
--**
--** File : /lua/aeonunits.lua
--** Author(s): John Comes, Gordon Duclos
--**
--** Summary :
--**
--** Copyright © 2005 Gas Powered Games, Inc. All rights reserved.
--****************************************************************************
----------------------------------------------------------------------------
-- AEON DEFAULT UNITS
----------------------------------------------------------------------------
local DefaultUnitsFile = import('defaultunits.lua')
local FactoryUnit = DefaultUnitsFile.FactoryUnit
local AirFactoryUnit = DefaultUnitsFile.AirFactoryUnit
local AirStagingPlatformUnit = DefaultUnitsFile.AirStagingPlatformUnit
local AirUnit = DefaultUnitsFile.AirUnit
local ConcreteStructureUnit = DefaultUnitsFile.ConcreteStructureUnit
local ConstructionUnit = DefaultUnitsFile.ConstructionUnit
local EnergyCreationUnit = DefaultUnitsFile.EnergyCreationUnit
local EnergyStorageUnit = DefaultUnitsFile.EnergyStorageUnit
local LandFactoryUnit = DefaultUnitsFile.LandFactoryUnit
local MassCollectionUnit = DefaultUnitsFile.MassCollectionUnit
local MassFabricationUnit = DefaultUnitsFile.MassFabricationUnit
local MassStorageUnit = DefaultUnitsFile.MassStorageUnit
local RadarUnit = DefaultUnitsFile.RadarUnit
local SeaFactoryUnit = DefaultUnitsFile.SeaFactoryUnit
local ShieldHoverLandUnit = DefaultUnitsFile.ShieldHoverLandUnit
local ShieldLandUnit = DefaultUnitsFile.ShieldLandUnit
local ShieldStructureUnit = DefaultUnitsFile.ShieldStructureUnit
local SonarUnit = DefaultUnitsFile.SonarUnit
local StructureUnit = DefaultUnitsFile.StructureUnit
local QuantumGateUnit = DefaultUnitsFile.QuantumGateUnit
local RadarJammerUnit = DefaultUnitsFile.RadarJammerUnit
local TransportBeaconUnit = DefaultUnitsFile.TransportBeaconUnit
local WalkingLandUnit = DefaultUnitsFile.WalkingLandUnit
local WallStructureUnit = DefaultUnitsFile.WallStructureUnit
local EffectTemplate = import('/lua/EffectTemplates.lua')
local EffectUtil = import('/lua/EffectUtilities.lua')
local CreateAeonFactoryBuildingEffects = EffectUtil.CreateAeonFactoryBuildingEffects
---------------------------------------------------------------
-- FACTORIES
---------------------------------------------------------------
AFactoryUnit = Class(FactoryUnit) {
StartBuildFx = function(self, unitBeingBuilt)
local thread = self:ForkThread(CreateAeonFactoryBuildingEffects, unitBeingBuilt, self.BuildEffectBones, 'Attachpoint', self.BuildEffectsBag)
unitBeingBuilt.Trash:Add(thread)
end,
OnPaused = function(self)
-- When factory is paused take some action
if self:IsUnitState('Building') and self.unitBeingBuilt then
self:StopUnitAmbientSound('ConstructLoop')
StructureUnit.StopBuildingEffects(self, self.UnitBeingBuilt)
self:StartBuildFx(self:GetFocusUnit())
end
StructureUnit.OnPaused(self)
end,
OnUnpaused = function(self)
FactoryUnit.OnUnpaused(self)
if self:IsUnitState('Building') and self.unitBeingBuilt then
StructureUnit.StopBuildingEffects(self, self.UnitBeingBuilt)
self:StartBuildFx(self:GetFocusUnit())
end
end,
}
---------------------------------------------------------------
-- AIR STRUCTURES
---------------------------------------------------------------
AAirFactoryUnit = Class(AirFactoryUnit) {
StartBuildFx = function(self, unitBeingBuilt)
AFactoryUnit.StartBuildFx(self, unitBeingBuilt)
end,
OnPaused = function(self)
AFactoryUnit.OnPaused(self)
end,
OnUnpaused = function(self)
AFactoryUnit.OnUnpaused(self)
end,
}
---------------------------------------------------------------
-- AIR UNITS
---------------------------------------------------------------
AAirUnit = Class(AirUnit) {}
---------------------------------------------------------------
-- AIR STAGING STRUCTURES
---------------------------------------------------------------
AAirStagingPlatformUnit = Class(AirStagingPlatformUnit) {}
---------------------------------------------------------------
-- WALL STRUCTURES
---------------------------------------------------------------
AConcreteStructureUnit = Class(ConcreteStructureUnit) {
AdjacencyBeam = false,
}
---------------------------------------------------------------
-- Construction Units
---------------------------------------------------------------
AConstructionUnit = Class(ConstructionUnit) {
CreateBuildEffects = function(self, unitBeingBuilt, order)
EffectUtil.CreateAeonConstructionUnitBuildingEffects(self, unitBeingBuilt, self.BuildEffectsBag)
end,
}
---------------------------------------------------------------
-- ENERGY CREATION UNITS
---------------------------------------------------------------
AEnergyCreationUnit = Class(EnergyCreationUnit) {
OnCreate = function(self)
EnergyCreationUnit.OnCreate(self)
self.NumUsedAdjacentUnits = 0
end,
OnStopBeingBuilt = function(self,builder,layer)
EnergyCreationUnit.OnStopBeingBuilt(self, builder, layer)
if self.AmbientEffects then
for k, v in EffectTemplate[self.AmbientEffects] do
CreateAttachedEmitter(self, 0, self.Army, v)
end
end
end,
}
---------------------------------------------------------------
-- ENERGY STORAGE STRUCTURES
---------------------------------------------------------------
AEnergyStorageUnit = Class(EnergyStorageUnit) {}
---------------------------------------------------------------
-- HOVERING LAND UNITS
---------------------------------------------------------------
AHoverLandUnit = Class(DefaultUnitsFile.HoverLandUnit) {
FxHoverScale = 1,
HoverEffects = nil,
HoverEffectBones = nil,
}
---------------------------------------------------------------
-- LAND FACTORY STRUCTURES
---------------------------------------------------------------
ALandFactoryUnit = Class(LandFactoryUnit) {
StartBuildFx = function(self, unitBeingBuilt)
AFactoryUnit.StartBuildFx(self, unitBeingBuilt)
end,
OnPaused = function(self)
AFactoryUnit.OnPaused(self)
end,
OnUnpaused = function(self)
AFactoryUnit.OnUnpaused(self)
end,
}
---------------------------------------------------------------
-- LAND UNITS
---------------------------------------------------------------
ALandUnit = Class(DefaultUnitsFile.LandUnit) {}
---------------------------------------------------------------
-- MASS COLLECTION UNITS
---------------------------------------------------------------
AMassCollectionUnit = Class(MassCollectionUnit) {}
---------------------------------------------------------------
-- MASS FABRICATION STRUCTURES
---------------------------------------------------------------
AMassFabricationUnit = Class(MassFabricationUnit) {}
---------------------------------------------------------------
-- MASS STORAGE UNITS
---------------------------------------------------------------
AMassStorageUnit = Class(MassStorageUnit) {}
---------------------------------------------------------------
-- RADAR STRUCTURES
---------------------------------------------------------------
ARadarUnit = Class(RadarUnit) {}
---------------------------------------------------------------
-- RADAR STRUCTURES
---------------------------------------------------------------
ASonarUnit = Class(SonarUnit) {}
---------------------------------------------------------------
-- SEA FACTORY STRUCTURES
---------------------------------------------------------------
ASeaFactoryUnit = Class(SeaFactoryUnit) {
StartBuildFx = function(self, unitBeingBuilt)
local thread = self:ForkThread(CreateAeonFactoryBuildingEffects, unitBeingBuilt, self.BuildEffectBones, 'Attachpoint01', self.BuildEffectsBag)
unitBeingBuilt.Trash:Add(thread)
end,
OnPaused = function(self)
AFactoryUnit.OnPaused(self)
end,
OnUnpaused = function(self)
AFactoryUnit.OnUnpaused(self)
end,
}
---------------------------------------------------------------
-- SEA UNITS
---------------------------------------------------------------
ASeaUnit = Class(DefaultUnitsFile.SeaUnit) {}
---------------------------------------------------------------
-- SHIELD LAND UNITS
---------------------------------------------------------------
AShieldHoverLandUnit = Class(ShieldHoverLandUnit) {}
---------------------------------------------------------------
-- SHIELD LAND UNITS
---------------------------------------------------------------
AShieldLandUnit = Class(ShieldLandUnit) {}
---------------------------------------------------------------
-- SHIELD STRUCTURES
---------------------------------------------------------------
AShieldStructureUnit = Class(ShieldStructureUnit) {
RotateSpeed = 60,
OnShieldEnabled = function(self)
ShieldStructureUnit.OnShieldEnabled(self)
local bp = self:GetBlueprint()
if not self.Rotator then
self.Rotator = CreateRotator(self, 'Pod', 'z', nil, 0, 50, 0)
self.Trash:Add(self.Rotator)
end
self.Rotator:SetSpinDown(false)
self.Rotator:SetTargetSpeed(self.RotateSpeed)
end,
OnShieldDisabled = function(self)
ShieldStructureUnit.OnShieldDisabled(self)
if self.Rotator then
self.Rotator:SetTargetSpeed(0)
end
end,
}
---------------------------------------------------------------
-- STRUCTURES
---------------------------------------------------------------
AStructureUnit = Class(StructureUnit) {}
---------------------------------------------------------------
-- SUBMARINE UNITS
---------------------------------------------------------------
ASubUnit = Class(DefaultUnitsFile.SubUnit) {
IdleSubBones = {},
IdleSubEffects = {}
}
---------------------------------------------------------------
-- TRANSPORT BEACON UNITS
---------------------------------------------------------------
ATransportBeaconUnit = Class(TransportBeaconUnit) {}
---------------------------------------------------------------
-- WALKING LAND UNITS
---------------------------------------------------------------
AWalkingLandUnit = Class(WalkingLandUnit) {}
---------------------------------------------------------------
-- WALL STRUCTURES
---------------------------------------------------------------
AWallStructureUnit = Class(WallStructureUnit) {}
---------------------------------------------------------------
-- CIVILIAN STRUCTURES
---------------------------------------------------------------
ACivilianStructureUnit = Class(AStructureUnit) {}
---------------------------------------------------------------
-- QUANTUM GATE UNITS
---------------------------------------------------------------
AQuantumGateUnit = Class(QuantumGateUnit) {}
---------------------------------------------------------------
-- RADAR JAMMER UNITS
---------------------------------------------------------------
ARadarJammerUnit = Class(RadarJammerUnit) {
RotateSpeed = 60,
OnStopBeingBuilt = function(self, builder, layer)
RadarJammerUnit.OnStopBeingBuilt(self, builder, layer)
local bp = self:GetBlueprint()
local bpAnim = bp.Display.AnimationOpen
if not bpAnim then return end
if not self.OpenAnim then
self.OpenAnim = CreateAnimator(self)
self.OpenAnim:PlayAnim(bpAnim)
self.Trash:Add(self.OpenAnim)
end
if not self.Rotator then
self.Rotator = CreateRotator(self, 'B02', 'z', nil, 0, 50, 0)
self.Trash:Add(self.Rotator)
end
end,
OnIntelEnabled = function(self)
RadarJammerUnit.OnIntelEnabled(self)
if self.OpenAnim then
self.OpenAnim:SetRate(1)
end
if not self.Rotator then
self.Rotator = CreateRotator(self, 'B02', 'z', nil, 0, 50, 0)
self.Trash:Add(self.Rotator)
end
self.Rotator:SetSpinDown(false)
self.Rotator:SetTargetSpeed(self.RotateSpeed)
end,
OnIntelDisabled = function(self)
RadarJammerUnit.OnIntelDisabled(self)
if self.OpenAnim then
self.OpenAnim:SetRate(-1)
end
if self.Rotator then
self.Rotator:SetTargetSpeed(0)
end
end,
}
| {
"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>
<!-- Generated by javadoc (version 1.7.0_25) on Thu Jan 01 17:43:59 PST 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.fasterxml.jackson.databind.deser.std.NumberDeserializers.NumberDeserializer (jackson-databind 2.5.0 API)</title>
<meta name="date" content="2015-01-01">
<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="Uses of Class com.fasterxml.jackson.databind.deser.std.NumberDeserializers.NumberDeserializer (jackson-databind 2.5.0 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><a href="../../../../../../../com/fasterxml/jackson/databind/deser/std/NumberDeserializers.NumberDeserializer.html" title="class in com.fasterxml.jackson.databind.deser.std">Class</a></li>
<li class="navBarCell1Rev">Use</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>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/fasterxml/jackson/databind/deser/std/class-use/NumberDeserializers.NumberDeserializer.html" target="_top">Frames</a></li>
<li><a href="NumberDeserializers.NumberDeserializer.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>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.fasterxml.jackson.databind.deser.std.NumberDeserializers.NumberDeserializer" class="title">Uses of Class<br>com.fasterxml.jackson.databind.deser.std.NumberDeserializers.NumberDeserializer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../com/fasterxml/jackson/databind/deser/std/NumberDeserializers.NumberDeserializer.html" title="class in com.fasterxml.jackson.databind.deser.std">NumberDeserializers.NumberDeserializer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.databind.deser.std">com.fasterxml.jackson.databind.deser.std</a></td>
<td class="colLast">
<div class="block">Contains public standard implementations of abstraction that
Jackson uses.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.fasterxml.jackson.databind.deser.std">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../com/fasterxml/jackson/databind/deser/std/NumberDeserializers.NumberDeserializer.html" title="class in com.fasterxml.jackson.databind.deser.std">NumberDeserializers.NumberDeserializer</a> in <a href="../../../../../../../com/fasterxml/jackson/databind/deser/std/package-summary.html">com.fasterxml.jackson.databind.deser.std</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../../../com/fasterxml/jackson/databind/deser/std/package-summary.html">com.fasterxml.jackson.databind.deser.std</a> declared as <a href="../../../../../../../com/fasterxml/jackson/databind/deser/std/NumberDeserializers.NumberDeserializer.html" title="class in com.fasterxml.jackson.databind.deser.std">NumberDeserializers.NumberDeserializer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../../com/fasterxml/jackson/databind/deser/std/NumberDeserializers.NumberDeserializer.html" title="class in com.fasterxml.jackson.databind.deser.std">NumberDeserializers.NumberDeserializer</a></code></td>
<td class="colLast"><span class="strong">NumberDeserializers.NumberDeserializer.</span><code><strong><a href="../../../../../../../com/fasterxml/jackson/databind/deser/std/NumberDeserializers.NumberDeserializer.html#instance">instance</a></strong></code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= 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><a href="../../../../../../../com/fasterxml/jackson/databind/deser/std/NumberDeserializers.NumberDeserializer.html" title="class in com.fasterxml.jackson.databind.deser.std">Class</a></li>
<li class="navBarCell1Rev">Use</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>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/fasterxml/jackson/databind/deser/std/class-use/NumberDeserializers.NumberDeserializer.html" target="_top">Frames</a></li>
<li><a href="NumberDeserializers.NumberDeserializer.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>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014-2015 <a href="http://fasterxml.com/">FasterXML</a>. All Rights Reserved.</small></p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Operations often used for initializing tensors.
All variable initializers returned by functions in this file should have the
following signature:
def _initializer(shape, dtype=dtypes.float32):
Args:
shape: List of `int` representing the shape of the output `Tensor`. Some
initializers may also be able to accept a `Tensor`.
dtype: (Optional) Type of the output `Tensor`.
Returns:
A `Tensor` of type `dtype` and `shape`.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_linalg_ops
from tensorflow.python.ops import linalg_ops_impl
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import stateless_random_ops
from tensorflow.python.util.tf_export import tf_export
class Initializer(object):
"""Initializer base class: all initializers inherit from this class.
"""
def __call__(self, shape, dtype=None):
"""Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. If not provided will return tensor
of `tf.float32`.
"""
raise NotImplementedError
def get_config(self):
"""Returns the configuration of the initializer as a JSON-serializable dict.
Returns:
A JSON-serializable Python dict.
"""
return {}
@classmethod
def from_config(cls, config):
"""Instantiates an initializer from a configuration dictionary.
Example:
```python
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
Args:
config: A Python dictionary.
It will typically be the output of `get_config`.
Returns:
An Initializer instance.
"""
config.pop("dtype", None)
return cls(**config)
@tf_export("zeros_initializer", v1=[])
class Zeros(Initializer):
"""Initializer that generates tensors initialized to 0."""
def __call__(self, shape, dtype=dtypes.float32):
dtype = dtypes.as_dtype(dtype)
return array_ops.zeros(shape, dtype)
@tf_export("ones_initializer", v1=[])
class Ones(Initializer):
"""Initializer that generates tensors initialized to 1."""
def __call__(self, shape, dtype=dtypes.float32):
"""Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are
supported.
Raises:
ValuesError: If the dtype is not numeric or boolean.
"""
dtype = dtypes.as_dtype(dtype)
if not dtype.is_numpy_compatible or dtype == dtypes.string:
raise ValueError("Expected numeric or boolean dtype, got %s." % dtype)
return array_ops.ones(shape, dtype)
@tf_export("constant_initializer", v1=[])
class Constant(Initializer):
"""Initializer that generates tensors with constant values.
The resulting tensor is populated with values of type `dtype`, as
specified by arguments `value` following the desired `shape` of the
new tensor (see examples below).
The argument `value` can be a constant value, or a list of values of type
`dtype`. If `value` is a list, then the length of the list must be less
than or equal to the number of elements implied by the desired shape of the
tensor. In the case where the total number of elements in `value` is less
than the number of elements required by the tensor shape, the last element
in `value` will be used to fill the remaining entries. If the total number of
elements in `value` is greater than the number of elements required by the
tensor shape, the initializer will raise a `ValueError`.
Args:
value: A Python scalar, list or tuple of values, or a N-dimensional numpy
array. All elements of the initialized variable will be set to the
corresponding value in the `value` argument.
Raises:
TypeError: If the input `value` is not one of the expected types.
Examples:
The following example can be rewritten using a numpy.ndarray instead
of the `value` list, even reshaped, as shown in the two commented lines
below the `value` list initialization.
```python
>>> import numpy as np
>>> import tensorflow as tf
>>> value = [0, 1, 2, 3, 4, 5, 6, 7]
>>> # value = np.array(value)
>>> # value = value.reshape([2, 4])
>>> init = tf.compat.v1.constant_initializer(value)
>>> print('fitting shape:')
>>> with tf.compat.v1.Session():
>>> x = tf.compat.v1.get_variable('x', shape=[2, 4], initializer=init)
>>> x.initializer.run()
>>> print(x.eval())
fitting shape:
[[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]]
>>> print('larger shape:')
>>> with tf.compat.v1.Session():
>>> x = tf.compat.v1.get_variable('x', shape=[3, 4], initializer=init)
>>> x.initializer.run()
>>> print(x.eval())
larger shape:
[[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 7. 7. 7. 7.]]
>>> print('smaller shape:')
>>> with tf.compat.v1.Session():
>>> x = tf.compat.v1.get_variable('x', shape=[2, 3], initializer=init)
ValueError: Too many elements provided. Needed at most 6, but received 8
```
"""
def __init__(self, value=0):
if not (np.isscalar(value) or isinstance(value, (list, tuple, np.ndarray))):
raise TypeError(
"Invalid type for initial value: %s (expected Python scalar, list or "
"tuple of values, or numpy.ndarray)." % type(value))
self.value = value
def __call__(self, shape, dtype=None):
"""Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. If not provided the dtype of the
tensor created will be the type of the inital value.
Raises:
TypeError: If the initializer cannot create a tensor of the requested
dtype.
"""
if dtype is not None:
dtype = dtypes.as_dtype(dtype)
return constant_op.constant(
self.value, dtype=dtype, shape=shape)
def get_config(self):
return {"value": self.value}
@tf_export("random_uniform_initializer", v1=[])
class RandomUniform(Initializer):
"""Initializer that generates tensors with a uniform distribution.
Args:
minval: A python scalar or a scalar tensor. Lower bound of the range
of random values to generate.
maxval: A python scalar or a scalar tensor. Upper bound of the range
of random values to generate. Defaults to 1 for float types.
seed: A Python integer. Used to create random seeds. See
`tf.compat.v1.set_random_seed`
for behavior.
"""
def __init__(self, minval=-0.05, maxval=0.05, seed=None):
self.minval = minval
self.maxval = maxval
self.seed = seed
self._random_generator = _RandomGenerator(seed)
def __call__(self, shape, dtype=dtypes.float32):
"""Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only floating point and integer
types are supported.
Raises:
ValueError: If the dtype is not numeric.
"""
dtype = dtypes.as_dtype(dtype)
if not dtype.is_floating and not dtype.is_integer:
raise ValueError("Expected float or integer dtype, got %s." % dtype)
return self._random_generator.random_uniform(shape, self.minval,
self.maxval, dtype)
def get_config(self):
return {
"minval": self.minval,
"maxval": self.maxval,
"seed": self.seed
}
@tf_export("random_normal_initializer", v1=[])
class RandomNormal(Initializer):
"""Initializer that generates tensors with a normal distribution.
Args:
mean: a python scalar or a scalar tensor. Mean of the random values
to generate.
stddev: a python scalar or a scalar tensor. Standard deviation of the
random values to generate.
seed: A Python integer. Used to create random seeds. See
`tf.compat.v1.set_random_seed`
for behavior.
"""
def __init__(self, mean=0.0, stddev=0.05, seed=None):
self.mean = mean
self.stddev = stddev
self.seed = seed
self._random_generator = _RandomGenerator(seed)
def __call__(self, shape, dtype=dtypes.float32):
"""Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only floating point types are
supported.
Raises:
ValueError: If the dtype is not floating point
"""
dtype = _assert_float_dtype(dtype)
return self._random_generator.random_normal(shape, self.mean, self.stddev,
dtype)
def get_config(self):
return {
"mean": self.mean,
"stddev": self.stddev,
"seed": self.seed
}
class TruncatedNormal(Initializer):
"""Initializer that generates a truncated normal distribution.
These values are similar to values from a `random_normal_initializer`
except that values more than two standard deviations from the mean
are discarded and re-drawn. This is the recommended initializer for
neural network weights and filters.
Args:
mean: a python scalar or a scalar tensor. Mean of the random values
to generate.
stddev: a python scalar or a scalar tensor. Standard deviation of the
random values to generate.
seed: A Python integer. Used to create random seeds. See
`tf.compat.v1.set_random_seed`
for behavior.
"""
def __init__(self, mean=0.0, stddev=0.05, seed=None):
self.mean = mean
self.stddev = stddev
self.seed = seed
self._random_generator = _RandomGenerator(seed)
def __call__(self, shape, dtype=dtypes.float32):
"""Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only floating point types are
supported.
Raises:
ValueError: If the dtype is not floating point
"""
dtype = _assert_float_dtype(dtype)
return self._random_generator.truncated_normal(shape, self.mean,
self.stddev, dtype)
def get_config(self):
return {
"mean": self.mean,
"stddev": self.stddev,
"seed": self.seed
}
class VarianceScaling(Initializer):
"""Initializer capable of adapting its scale to the shape of weights tensors.
With `distribution="truncated_normal" or "untruncated_normal"`,
samples are drawn from a truncated/untruncated normal
distribution with a mean of zero and a standard deviation (after truncation,
if used) `stddev = sqrt(scale / n)`
where n is:
- number of input units in the weight tensor, if mode = "fan_in"
- number of output units, if mode = "fan_out"
- average of the numbers of input and output units, if mode = "fan_avg"
With `distribution="uniform"`, samples are drawn from a uniform distribution
within [-limit, limit], with `limit = sqrt(3 * scale / n)`.
Args:
scale: Scaling factor (positive float).
mode: One of "fan_in", "fan_out", "fan_avg".
distribution: Random distribution to use. One of "truncated_normal",
"untruncated_normal" and "uniform".
seed: A Python integer. Used to create random seeds. See
`tf.compat.v1.set_random_seed`
for behavior.
Raises:
ValueError: In case of an invalid value for the "scale", mode" or
"distribution" arguments.
"""
def __init__(self,
scale=1.0,
mode="fan_in",
distribution="truncated_normal",
seed=None):
if scale <= 0.:
raise ValueError("`scale` must be positive float.")
if mode not in {"fan_in", "fan_out", "fan_avg"}:
raise ValueError("Invalid `mode` argument:", mode)
distribution = distribution.lower()
# Compatibility with keras-team/keras.
if distribution == "normal":
distribution = "truncated_normal"
if distribution not in {"uniform", "truncated_normal",
"untruncated_normal"}:
raise ValueError("Invalid `distribution` argument:", distribution)
self.scale = scale
self.mode = mode
self.distribution = distribution
self.seed = seed
self._random_generator = _RandomGenerator(seed)
def __call__(self, shape, dtype=dtypes.float32):
"""Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only floating point types are
supported.
Raises:
ValueError: If the dtype is not floating point
"""
partition_info = None # Keeps logic so can be readded later if necessary
dtype = _assert_float_dtype(dtype)
scale = self.scale
scale_shape = shape
if partition_info is not None:
scale_shape = partition_info.full_shape
fan_in, fan_out = _compute_fans(scale_shape)
if self.mode == "fan_in":
scale /= max(1., fan_in)
elif self.mode == "fan_out":
scale /= max(1., fan_out)
else:
scale /= max(1., (fan_in + fan_out) / 2.)
if self.distribution == "truncated_normal":
# constant from scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.)
stddev = math.sqrt(scale) / .87962566103423978
return self._random_generator.truncated_normal(shape, 0.0, stddev, dtype)
elif self.distribution == "untruncated_normal":
stddev = math.sqrt(scale)
return self._random_generator.random_normal(shape, 0.0, stddev, dtype)
else:
limit = math.sqrt(3.0 * scale)
return self._random_generator.random_uniform(shape, -limit, limit, dtype)
def get_config(self):
return {
"scale": self.scale,
"mode": self.mode,
"distribution": self.distribution,
"seed": self.seed
}
class Orthogonal(Initializer):
"""Initializer that generates an orthogonal matrix.
If the shape of the tensor to initialize is two-dimensional, it is initialized
with an orthogonal matrix obtained from the QR decomposition of a matrix of
random numbers drawn from a normal distribution.
If the matrix has fewer rows than columns then the output will have orthogonal
rows. Otherwise, the output will have orthogonal columns.
If the shape of the tensor to initialize is more than two-dimensional,
a matrix of shape `(shape[0] * ... * shape[n - 2], shape[n - 1])`
is initialized, where `n` is the length of the shape vector.
The matrix is subsequently reshaped to give a tensor of the desired shape.
Args:
gain: multiplicative factor to apply to the orthogonal matrix
seed: A Python integer. Used to create random seeds. See
`tf.compat.v1.set_random_seed`
for behavior.
References:
[Saxe et al., 2014](https://openreview.net/forum?id=_wzZwKpTDF_9C)
([pdf](https://arxiv.org/pdf/1312.6120.pdf))
"""
def __init__(self, gain=1.0, seed=None):
self.gain = gain
self.seed = seed
self._random_generator = _RandomGenerator(seed)
def __call__(self, shape, dtype=dtypes.float32):
"""Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only floating point types are
supported.
Raises:
ValueError: If the dtype is not floating point or the input shape is not
valid.
"""
dtype = _assert_float_dtype(dtype)
# Check the shape
if len(shape) < 2:
raise ValueError("The tensor to initialize must be "
"at least two-dimensional")
# Flatten the input shape with the last dimension remaining
# its original shape so it works for conv2d
num_rows = 1
for dim in shape[:-1]:
num_rows *= dim
num_cols = shape[-1]
flat_shape = (max(num_cols, num_rows), min(num_cols, num_rows))
# Generate a random matrix
a = self._random_generator.random_normal(flat_shape, dtype=dtype)
# Compute the qr factorization
q, r = gen_linalg_ops.qr(a, full_matrices=False)
# Make Q uniform
d = array_ops.diag_part(r)
q *= math_ops.sign(d)
if num_rows < num_cols:
q = array_ops.matrix_transpose(q)
return self.gain * array_ops.reshape(q, shape)
def get_config(self):
return {"gain": self.gain, "seed": self.seed}
class Identity(Initializer):
"""Initializer that generates the identity matrix.
Only use for 2D matrices.
Args:
gain: Multiplicative factor to apply to the identity matrix.
"""
def __init__(self, gain=1.0):
self.gain = gain
def __call__(self, shape, dtype=dtypes.float32):
"""Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only floating point types are
supported.
Raises:
ValueError: If the dtype is not floating point
"""
partition_info = None # Keeps logic so can be readded later if necessary
dtype = _assert_float_dtype(dtype)
full_shape = shape if partition_info is None else partition_info.full_shape
if len(full_shape) != 2:
raise ValueError(
"Identity matrix initializer can only be used for 2D matrices.")
initializer = linalg_ops_impl.eye(*full_shape, dtype=dtype)
if partition_info is not None:
initializer = array_ops.slice(initializer, partition_info.var_offset,
shape)
return self.gain * initializer
def get_config(self):
return {"gain": self.gain}
class GlorotUniform(VarianceScaling):
"""The Glorot uniform initializer, also called Xavier uniform initializer.
It draws samples from a uniform distribution within [-limit, limit]
where `limit` is `sqrt(6 / (fan_in + fan_out))`
where `fan_in` is the number of input units in the weight tensor
and `fan_out` is the number of output units in the weight tensor.
Args:
seed: A Python integer. Used to create random seeds. See
`tf.compat.v1.set_random_seed`
for behavior.
References:
[Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html)
([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf))
"""
def __init__(self, seed=None):
super(GlorotUniform, self).__init__(
scale=1.0,
mode="fan_avg",
distribution="uniform",
seed=seed)
def get_config(self):
return {"seed": self.seed}
class GlorotNormal(VarianceScaling):
"""The Glorot normal initializer, also called Xavier normal initializer.
It draws samples from a truncated normal distribution centered on 0
with `stddev = sqrt(2 / (fan_in + fan_out))`
where `fan_in` is the number of input units in the weight tensor
and `fan_out` is the number of output units in the weight tensor.
Args:
seed: A Python integer. Used to create random seeds. See
`tf.compat.v1.set_random_seed` for behavior.
References:
[Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html)
([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf))
"""
def __init__(self, seed=None):
super(GlorotNormal, self).__init__(
scale=1.0,
mode="fan_avg",
distribution="truncated_normal",
seed=seed)
def get_config(self):
return {"seed": self.seed}
# Aliases.
# pylint: disable=invalid-name
zeros_initializer = Zeros
ones_initializer = Ones
constant_initializer = Constant
random_uniform_initializer = RandomUniform
random_normal_initializer = RandomNormal
truncated_normal_initializer = TruncatedNormal
variance_scaling_initializer = VarianceScaling
glorot_uniform_initializer = GlorotUniform
glorot_normal_initializer = GlorotNormal
orthogonal_initializer = Orthogonal
identity_initializer = Identity
# pylint: enable=invalid-name
def lecun_normal(seed=None):
"""LeCun normal initializer.
It draws samples from a truncated normal distribution centered on 0
with `stddev = sqrt(1 / fan_in)`
where `fan_in` is the number of input units in the weight tensor.
Arguments:
seed: A Python integer. Used to seed the random generator.
Returns:
An initializer.
References:
- Self-Normalizing Neural Networks,
[Klambauer et al., 2017]
(https://papers.nips.cc/paper/6698-self-normalizing-neural-networks)
([pdf]
(https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf))
- Efficient Backprop,
[Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)
"""
return VarianceScaling(
scale=1., mode="fan_in", distribution="truncated_normal", seed=seed)
def lecun_uniform(seed=None):
"""LeCun uniform initializer.
It draws samples from a uniform distribution within [-limit, limit]
where `limit` is `sqrt(3 / fan_in)`
where `fan_in` is the number of input units in the weight tensor.
Arguments:
seed: A Python integer. Used to seed the random generator.
Returns:
An initializer.
References:
- Self-Normalizing Neural Networks,
[Klambauer et al., 2017](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) # pylint: disable=line-too-long
([pdf](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf))
- Efficient Backprop,
[Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)
"""
return VarianceScaling(
scale=1., mode="fan_in", distribution="uniform", seed=seed)
def he_normal(seed=None):
"""He normal initializer.
It draws samples from a truncated normal distribution centered on 0
with `stddev = sqrt(2 / fan_in)`
where `fan_in` is the number of input units in the weight tensor.
Arguments:
seed: A Python integer. Used to seed the random generator.
Returns:
An initializer.
References:
[He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long
([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf))
"""
return VarianceScaling(
scale=2., mode="fan_in", distribution="truncated_normal", seed=seed)
def he_uniform(seed=None):
"""He uniform variance scaling initializer.
It draws samples from a uniform distribution within [-limit, limit]
where `limit` is `sqrt(6 / fan_in)`
where `fan_in` is the number of input units in the weight tensor.
Arguments:
seed: A Python integer. Used to seed the random generator.
Returns:
An initializer.
References:
[He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long
([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf))
"""
return VarianceScaling(
scale=2., mode="fan_in", distribution="uniform", seed=seed)
# Utility functions.
def _compute_fans(shape):
"""Computes the number of input and output units for a weight shape.
Args:
shape: Integer shape tuple or TF tensor shape.
Returns:
A tuple of scalars (fan_in, fan_out).
"""
if len(shape) < 1: # Just to avoid errors for constants.
fan_in = fan_out = 1
elif len(shape) == 1:
fan_in = fan_out = shape[0]
elif len(shape) == 2:
fan_in = shape[0]
fan_out = shape[1]
else:
# Assuming convolution kernels (2D, 3D, or more).
# kernel shape: (..., input_depth, depth)
receptive_field_size = 1.
for dim in shape[:-2]:
receptive_field_size *= dim
fan_in = shape[-2] * receptive_field_size
fan_out = shape[-1] * receptive_field_size
return fan_in, fan_out
def _assert_float_dtype(dtype):
"""Validate and return floating point type based on `dtype`.
`dtype` must be a floating point type.
Args:
dtype: The data type to validate.
Returns:
Validated type.
Raises:
ValueError: if `dtype` is not a floating point type.
"""
dtype = dtypes.as_dtype(dtype)
if not dtype.is_floating:
raise ValueError("Expected floating point type, got %s." % dtype)
return dtype
class _RandomGenerator(object):
"""Random generator that selects appropriate random ops."""
def __init__(self, seed=None):
super(_RandomGenerator, self).__init__()
if seed is not None:
# Stateless random ops requires 2-int seed.
self.seed = [seed, 0]
else:
self.seed = None
def random_normal(self, shape, mean=0.0, stddev=1, dtype=dtypes.float32):
"""A deterministic random normal if seed is passed."""
if self.seed:
op = stateless_random_ops.stateless_random_normal
else:
op = random_ops.random_normal
return op(
shape=shape, mean=mean, stddev=stddev, dtype=dtype, seed=self.seed)
def random_uniform(self, shape, minval, maxval, dtype):
"""A deterministic random uniform if seed is passed."""
if self.seed:
op = stateless_random_ops.stateless_random_uniform
else:
op = random_ops.random_uniform
return op(
shape=shape, minval=minval, maxval=maxval, dtype=dtype, seed=self.seed)
def truncated_normal(self, shape, mean, stddev, dtype):
"""A deterministic truncated normal if seed is passed."""
if self.seed:
op = stateless_random_ops.stateless_truncated_normal
else:
op = random_ops.truncated_normal
return op(
shape=shape, mean=mean, stddev=stddev, dtype=dtype, seed=self.seed)
# Compatibility aliases
# pylint: disable=invalid-name
zero = zeros = Zeros
one = ones = Ones
constant = Constant
uniform = random_uniform = RandomUniform
normal = random_normal = RandomNormal
truncated_normal = TruncatedNormal
identity = Identity
orthogonal = Orthogonal
glorot_normal = GlorotNormal
glorot_uniform = GlorotUniform
| {
"pile_set_name": "Github"
} |
package rocks.inspectit.server.dao;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import rocks.inspectit.shared.all.communication.DefaultData;
import rocks.inspectit.shared.all.communication.data.HttpTimerData;
import rocks.inspectit.shared.all.communication.data.JmxSensorValueData;
/**
* All implementing classes of this interface are storing and retrieving the default data objects,
* for example in the database.
*
* @author Patrice Bouillet
*
*/
public interface DefaultDataDao {
/**
* Persists or updates all items in the collection.
*
* @param defaultDataCollection
* The collection with {@link DefaultData} objects to persist or update.
*/
void saveAll(List<? extends DefaultData> defaultDataCollection);
/**
* Returns a list of stored {@link DefaultData} objects in the given interval, starting minus
* the passed timeInterval parameter to the current time.
*
* @param template
* The template object to look for.
* @param timeInterval
* The time interval to look for the objects. Ranging minus the passed time interval
* parameter up until now.
* @return Returns a list of data objects which fulfill the criteria.
*/
List<DefaultData> findByExampleWithLastInterval(DefaultData template, long timeInterval);
/**
* Search for data objects which have an ID greater than in the passed template object.
*
* @param template
* The template object to look for with the ID used as the marker.
* @return Returns a list of data objects which fulfill the criteria.
*/
List<DefaultData> findByExampleSinceId(DefaultData template);
/**
* Search for data objects which have an ID greater than in the passed template object. The
* Method Ident is always ignored.
*
* @param template
* The template object to look for with the ID used as the marker.
* @return Returns a list of data objects which fulfill the criteria.
*/
List<DefaultData> findByExampleSinceIdIgnoreMethodId(DefaultData template);
/**
* Search for data objects which are between the from and to {@link Date} object.
*
* @param template
* The template object to look for.
* @param fromDate
* The start date.
* @param toDate
* The end date.
* @return Returns a list of data objects which fulfill the criteria.
*/
List<DefaultData> findByExampleFromToDate(DefaultData template, Date fromDate, Date toDate);
/**
* Searches for the last saved data object.
*
* @param template
* The template object to look for.
* @return Returns the last saved data object.
*/
DefaultData findByExampleLastData(DefaultData template);
/**
* Returns the {@link HttpTimerData} list that can be used as the input for the plotting. From
* the template list the platfrom ident will be used as well as all URI and tagged values.
*
* @param templates
* Templates.
* @param fromDate
* From date.
* @param toDate
* To date
* @param retrieveByTag
* If tag values from the templates should be used when retrieving the data. If false
* is passed, URi will be used from templates.
* @return List of {@link HttpTimerData}.
*/
List<HttpTimerData> getChartingHttpTimerDataFromDateToDate(Collection<HttpTimerData> templates, Date fromDate, Date toDate, boolean retrieveByTag);
/**
* Returns the {@link JmxSensorValueData} list of a given time frame that can be used as partial
* input for the jmx sensor.
*
* @param jmxSensorValueData
* The data.
* @param fromDate
* From date.
* @param toDate
* To date
* @return List of {@link JmxSensorValueData}.
*/
List<JmxSensorValueData> getJmxDataOverview(JmxSensorValueData jmxSensorValueData, Date fromDate, Date toDate);
/**
* Deletes all default data objects in the database with the given platform ID.
*
* @param platformId
* PLatform id of objects to be deleted.
*/
void deleteAll(Long platformId);
}
| {
"pile_set_name": "Github"
} |
<!--
Config page
-->
<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define" xmlns:l="/lib/layout"
xmlns:t="/lib/hudson" xmlns:f="/lib/form">
<f:entry title="${%Description}" help="/help/system-config/master-slave/description.html">
<f:textbox field="nodeDescription" />
</f:entry>
<f:entry title="${%# of executors}" field="numExecutors">
<f:textbox />
</f:entry>
<f:entry title="${%Remote FS root}" field="remoteFs">
<f:textbox />
</f:entry>
<f:entry title="${%Labels}" field="labelString">
<f:textbox />
</f:entry>
<f:slave-mode name="mode" node="${it}" />
<f:descriptorList title="${%Node Properties}" descriptors="${h.getNodePropertyDescriptors(descriptor.clazz)}" field="nodeProperties" />
</j:jelly> | {
"pile_set_name": "Github"
} |
(library
(name scope2)
(public_name scope2)) | {
"pile_set_name": "Github"
} |
$("#g-confirm-delete").submit(
function() {
$("#g-confirm-delete input[type=submit]").gallery_show_loading();
}
);
| {
"pile_set_name": "Github"
} |
The steps to get this Android UI working are:
1. Add a reference to your Core PCL project
2. Remove any old `MainLauncher` activities - eg Activity1
| {
"pile_set_name": "Github"
} |
#region Disclaimer / License
// Copyright (C) 2015, The Duplicati Team
// http://www.duplicati.com, [email protected]
//
// This library 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.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#endregion
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Duplicati.Library.Snapshots")]
[assembly: AssemblyDescription("A disk snapshot implementation for Duplicati")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Duplicati Team")]
[assembly: AssemblyProduct("Duplicati")]
[assembly: AssemblyCopyright("LGPL, Copyright © Duplicati Team 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8646AF32-A3E6-43fc-B541-DE6F6430CF46")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("2.0.0.7")]
[assembly: AssemblyFileVersion("2.0.0.7")]
| {
"pile_set_name": "Github"
} |
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Swagger Petstore",
"description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "Swagger API Team"
},
"license": {
"name": "MIT"
}
},
"host": "petstore.swagger.io",
"basePath": "/api",
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/pets": {
"get": {
"description": "Returns all pets from the system that the user has access to",
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "A list of pets.",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
}
}
}
}
},
"definitions": {
"Pet": {
"type": "object",
"required": [
"id",
"name"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
}
}
} | {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (C) 2013 Freescale Semiconductor, Inc.
*/
#include <linux/clk-provider.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/slab.h>
#include "clk.h"
/**
* struct clk_fixup_mux - imx integer fixup multiplexer clock
* @mux: the parent class
* @ops: pointer to clk_ops of parent class
* @fixup: a hook to fixup the write value
*
* The imx fixup multiplexer clock is a subclass of basic clk_mux
* with an addtional fixup hook.
*/
struct clk_fixup_mux {
struct clk_mux mux;
const struct clk_ops *ops;
void (*fixup)(u32 *val);
};
static inline struct clk_fixup_mux *to_clk_fixup_mux(struct clk_hw *hw)
{
struct clk_mux *mux = to_clk_mux(hw);
return container_of(mux, struct clk_fixup_mux, mux);
}
static u8 clk_fixup_mux_get_parent(struct clk_hw *hw)
{
struct clk_fixup_mux *fixup_mux = to_clk_fixup_mux(hw);
return fixup_mux->ops->get_parent(&fixup_mux->mux.hw);
}
static int clk_fixup_mux_set_parent(struct clk_hw *hw, u8 index)
{
struct clk_fixup_mux *fixup_mux = to_clk_fixup_mux(hw);
struct clk_mux *mux = to_clk_mux(hw);
unsigned long flags;
u32 val;
spin_lock_irqsave(mux->lock, flags);
val = readl(mux->reg);
val &= ~(mux->mask << mux->shift);
val |= index << mux->shift;
fixup_mux->fixup(&val);
writel(val, mux->reg);
spin_unlock_irqrestore(mux->lock, flags);
return 0;
}
static const struct clk_ops clk_fixup_mux_ops = {
.get_parent = clk_fixup_mux_get_parent,
.set_parent = clk_fixup_mux_set_parent,
};
struct clk_hw *imx_clk_hw_fixup_mux(const char *name, void __iomem *reg,
u8 shift, u8 width, const char * const *parents,
int num_parents, void (*fixup)(u32 *val))
{
struct clk_fixup_mux *fixup_mux;
struct clk_hw *hw;
struct clk_init_data init;
int ret;
if (!fixup)
return ERR_PTR(-EINVAL);
fixup_mux = kzalloc(sizeof(*fixup_mux), GFP_KERNEL);
if (!fixup_mux)
return ERR_PTR(-ENOMEM);
init.name = name;
init.ops = &clk_fixup_mux_ops;
init.parent_names = parents;
init.num_parents = num_parents;
init.flags = 0;
fixup_mux->mux.reg = reg;
fixup_mux->mux.shift = shift;
fixup_mux->mux.mask = BIT(width) - 1;
fixup_mux->mux.lock = &imx_ccm_lock;
fixup_mux->mux.hw.init = &init;
fixup_mux->ops = &clk_mux_ops;
fixup_mux->fixup = fixup;
hw = &fixup_mux->mux.hw;
ret = clk_hw_register(NULL, hw);
if (ret) {
kfree(fixup_mux);
return ERR_PTR(ret);
}
return hw;
}
| {
"pile_set_name": "Github"
} |
User-agent: *
Disallow:
| {
"pile_set_name": "Github"
} |
//! moment.js locale configuration
//! locale : Welsh [cy]
//! author : Robert Allen
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, function (moment) { 'use strict';
var cy = moment.defineLocale('cy', {
months: 'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split('_'),
monthsShort: 'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split('_'),
weekdays: 'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split('_'),
weekdaysShort: 'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'),
weekdaysMin: 'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'),
weekdaysParseExact : true,
// time formats are the same as en-gb
longDateFormat: {
LT: 'HH:mm',
LTS : 'HH:mm:ss',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd, D MMMM YYYY HH:mm'
},
calendar: {
sameDay: '[Heddiw am] LT',
nextDay: '[Yfory am] LT',
nextWeek: 'dddd [am] LT',
lastDay: '[Ddoe am] LT',
lastWeek: 'dddd [diwethaf am] LT',
sameElse: 'L'
},
relativeTime: {
future: 'mewn %s',
past: '%s yn ôl',
s: 'ychydig eiliadau',
m: 'munud',
mm: '%d munud',
h: 'awr',
hh: '%d awr',
d: 'diwrnod',
dd: '%d diwrnod',
M: 'mis',
MM: '%d mis',
y: 'blwyddyn',
yy: '%d flynedd'
},
ordinalParse: /\d{1,2}(fed|ain|af|il|ydd|ed|eg)/,
// traditional ordinal numbers above 31 are not commonly used in colloquial Welsh
ordinal: function (number) {
var b = number,
output = '',
lookup = [
'', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed
'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed
];
if (b > 20) {
if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) {
output = 'fed'; // not 30ain, 70ain or 90ain
} else {
output = 'ain';
}
} else if (b > 0) {
output = lookup[b];
}
return number + output;
},
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
return cy;
})); | {
"pile_set_name": "Github"
} |
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -emit-ir
protocol a{typealias B<>:a{}associatedtype e
struct B<T>:a{
var:e
class B<T>:a
| {
"pile_set_name": "Github"
} |
package Leetcode;
/**
* Created by rbhatnagar2 on 1/15/17.
*/
public class Q328_Odd_Even_Linked_List {
}
| {
"pile_set_name": "Github"
} |
# -----------------------------------------------------------------------------
# $RCSfile: Makefile.am,v $
#
# See Copyright for the status of this software.
#
# The OpenSOAP Project
# http://opensoap.jp/
# -----------------------------------------------------------------------------
EXTRA_DIST = \
ReadMeDCOM.txt \
ReadMeDCOM_SJ.txt
| {
"pile_set_name": "Github"
} |
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
# (c) 2005 Clark C. Evans
# This module is part of the Python Paste Project and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
# This code was written with funding by http://prometheusresearch.com
"""
Upload Progress Monitor
This is a WSGI middleware component which monitors the status of files
being uploaded. It includes a small query application which will return
a list of all files being uploaded by particular session/user.
>>> from paste.httpserver import serve
>>> from paste.urlmap import URLMap
>>> from paste.auth.basic import AuthBasicHandler
>>> from paste.debug.debugapp import SlowConsumer, SimpleApplication
>>> # from paste.progress import *
>>> realm = 'Test Realm'
>>> def authfunc(username, password):
... return username == password
>>> map = URLMap({})
>>> ups = UploadProgressMonitor(map, threshold=1024)
>>> map['/upload'] = SlowConsumer()
>>> map['/simple'] = SimpleApplication()
>>> map['/report'] = UploadProgressReporter(ups)
>>> serve(AuthBasicHandler(ups, realm, authfunc))
serving on...
.. note::
This is experimental, and will change in the future.
"""
import time
from paste.wsgilib import catch_errors
DEFAULT_THRESHOLD = 1024 * 1024 # one megabyte
DEFAULT_TIMEOUT = 60*5 # five minutes
ENVIRON_RECEIVED = 'paste.bytes_received'
REQUEST_STARTED = 'paste.request_started'
REQUEST_FINISHED = 'paste.request_finished'
class _ProgressFile(object):
"""
This is the input-file wrapper used to record the number of
``paste.bytes_received`` for the given request.
"""
def __init__(self, environ, rfile):
self._ProgressFile_environ = environ
self._ProgressFile_rfile = rfile
self.flush = rfile.flush
self.write = rfile.write
self.writelines = rfile.writelines
def __iter__(self):
environ = self._ProgressFile_environ
riter = iter(self._ProgressFile_rfile)
def iterwrap():
for chunk in riter:
environ[ENVIRON_RECEIVED] += len(chunk)
yield chunk
return iter(iterwrap)
def read(self, size=-1):
chunk = self._ProgressFile_rfile.read(size)
self._ProgressFile_environ[ENVIRON_RECEIVED] += len(chunk)
return chunk
def readline(self):
chunk = self._ProgressFile_rfile.readline()
self._ProgressFile_environ[ENVIRON_RECEIVED] += len(chunk)
return chunk
def readlines(self, hint=None):
chunk = self._ProgressFile_rfile.readlines(hint)
self._ProgressFile_environ[ENVIRON_RECEIVED] += len(chunk)
return chunk
class UploadProgressMonitor(object):
"""
monitors and reports on the status of uploads in progress
Parameters:
``application``
This is the next application in the WSGI stack.
``threshold``
This is the size in bytes that is needed for the
upload to be included in the monitor.
``timeout``
This is the amount of time (in seconds) that a upload
remains in the monitor after it has finished.
Methods:
``uploads()``
This returns a list of ``environ`` dict objects for each
upload being currently monitored, or finished but whose time
has not yet expired.
For each request ``environ`` that is monitored, there are several
variables that are stored:
``paste.bytes_received``
This is the total number of bytes received for the given
request; it can be compared with ``CONTENT_LENGTH`` to
build a percentage complete. This is an integer value.
``paste.request_started``
This is the time (in seconds) when the request was started
as obtained from ``time.time()``. One would want to format
this for presentation to the user, if necessary.
``paste.request_finished``
This is the time (in seconds) when the request was finished,
canceled, or otherwise disconnected. This is None while
the given upload is still in-progress.
TODO: turn monitor into a queue and purge queue of finished
requests that have passed the timeout period.
"""
def __init__(self, application, threshold=None, timeout=None):
self.application = application
self.threshold = threshold or DEFAULT_THRESHOLD
self.timeout = timeout or DEFAULT_TIMEOUT
self.monitor = []
def __call__(self, environ, start_response):
length = environ.get('CONTENT_LENGTH', 0)
if length and int(length) > self.threshold:
# replace input file object
self.monitor.append(environ)
environ[ENVIRON_RECEIVED] = 0
environ[REQUEST_STARTED] = time.time()
environ[REQUEST_FINISHED] = None
environ['wsgi.input'] = \
_ProgressFile(environ, environ['wsgi.input'])
def finalizer(exc_info=None):
environ[REQUEST_FINISHED] = time.time()
return catch_errors(self.application, environ,
start_response, finalizer, finalizer)
return self.application(environ, start_response)
def uploads(self):
return self.monitor
class UploadProgressReporter(object):
"""
reports on the progress of uploads for a given user
This reporter returns a JSON file (for use in AJAX) listing the
uploads in progress for the given user. By default, this reporter
uses the ``REMOTE_USER`` environment to compare between the current
request and uploads in-progress. If they match, then a response
record is formed.
``match()``
This member function can be overriden to provide alternative
matching criteria. It takes two environments, the first
is the current request, the second is a current upload.
``report()``
This member function takes an environment and builds a
``dict`` that will be used to create a JSON mapping for
the given upload. By default, this just includes the
percent complete and the request url.
"""
def __init__(self, monitor):
self.monitor = monitor
def match(self, search_environ, upload_environ):
if search_environ.get('REMOTE_USER', None) == \
upload_environ.get('REMOTE_USER', 0):
return True
return False
def report(self, environ):
retval = { 'started': time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(environ[REQUEST_STARTED])),
'finished': '',
'content_length': environ.get('CONTENT_LENGTH'),
'bytes_received': environ[ENVIRON_RECEIVED],
'path_info': environ.get('PATH_INFO',''),
'query_string': environ.get('QUERY_STRING','')}
finished = environ[REQUEST_FINISHED]
if finished:
retval['finished'] = time.strftime("%Y:%m:%d %H:%M:%S",
time.gmtime(finished))
return retval
def __call__(self, environ, start_response):
body = []
for map in [self.report(env) for env in self.monitor.uploads()
if self.match(environ, env)]:
parts = []
for k, v in map.items():
v = str(v).replace("\\", "\\\\").replace('"', '\\"')
parts.append('%s: "%s"' % (k, v))
body.append("{ %s }" % ", ".join(parts))
body = "[ %s ]" % ", ".join(body)
start_response("200 OK", [('Content-Type', 'text/plain'),
('Content-Length', len(body))])
return [body]
__all__ = ['UploadProgressMonitor', 'UploadProgressReporter']
if "__main__" == __name__:
import doctest
doctest.testmod(optionflags=doctest.ELLIPSIS)
| {
"pile_set_name": "Github"
} |
# -*- encoding: utf-8 -*-
module IOSpecs
class SubIO < IO
end
def self.collector
Proc.new { |x| ScratchPad << x }
end
def self.lines
[ "Voici la ligne une.\n",
"Qui \303\250 la linea due.\n",
"\n",
"\n",
"Aqu\303\255 est\303\241 la l\303\255nea tres.\n",
"Hier ist Zeile vier.\n",
"\n",
"Est\303\241 aqui a linha cinco.\n",
"Here is line six.\n" ]
end
def self.lines_without_newline_characters
[ "Voici la ligne une.",
"Qui \303\250 la linea due.",
"",
"",
"Aqu\303\255 est\303\241 la l\303\255nea tres.",
"Hier ist Zeile vier.",
"",
"Est\303\241 aqui a linha cinco.",
"Here is line six." ]
end
def self.lines_limit
[ "Voici la l",
"igne une.\n",
"Qui è la ",
"linea due.",
"\n",
"\n",
"\n",
"Aquí está",
" la línea",
" tres.\n",
"Hier ist Z",
"eile vier.",
"\n",
"\n",
"Está aqui",
" a linha c",
"inco.\n",
"Here is li",
"ne six.\n" ]
end
def self.lines_space_separator_limit
[ "Voici ",
"la ",
"ligne ",
"une.\nQui ",
"è ",
"la ",
"linea ",
"due.\n\n\nAqu",
"í ",
"está ",
"la ",
"línea ",
"tres.\nHier",
" ",
"ist ",
"Zeile ",
"vier.\n\nEst",
"á ",
"aqui ",
"a ",
"linha ",
"cinco.\nHer",
"e ",
"is ",
"line ",
"six.\n" ]
end
def self.lines_r_separator
[ "Voici la ligne une.\nQui \303\250 la linea due.\n\n\nAqu\303\255 est\303\241 la l\303\255nea tr",
"es.\nHier",
" ist Zeile vier",
".\n\nEst\303\241 aqui a linha cinco.\nHer",
"e is line six.\n" ]
end
def self.lines_empty_separator
[ "Voici la ligne une.\nQui \303\250 la linea due.\n\n",
"Aqu\303\255 est\303\241 la l\303\255nea tres.\nHier ist Zeile vier.\n\n",
"Est\303\241 aqui a linha cinco.\nHere is line six.\n" ]
end
def self.lines_space_separator
[ "Voici ", "la ", "ligne ", "une.\nQui ",
"\303\250 ", "la ", "linea ", "due.\n\n\nAqu\303\255 ",
"est\303\241 ", "la ", "l\303\255nea ", "tres.\nHier ",
"ist ", "Zeile ", "vier.\n\nEst\303\241 ", "aqui ", "a ",
"linha ", "cinco.\nHere ", "is ", "line ", "six.\n" ]
end
def self.lines_arbitrary_separator
[ "Voici la ligne une.\nQui \303\250",
" la linea due.\n\n\nAqu\303\255 est\303\241 la l\303\255nea tres.\nHier ist Zeile vier.\n\nEst\303\241 aqui a linha cinco.\nHere is line six.\n" ]
end
def self.paragraphs
[ "Voici la ligne une.\nQui \303\250 la linea due.\n\n",
"Aqu\303\255 est\303\241 la l\303\255nea tres.\nHier ist Zeile vier.\n\n",
"Est\303\241 aqui a linha cinco.\nHere is line six.\n" ]
end
# Creates an IO instance for an existing fixture file. The
# file should obviously not be deleted.
def self.io_fixture(name, mode = "r:utf-8")
path = fixture __FILE__, name
name = path if File.exist? path
new_io(name, mode)
end
# Returns a closed instance of IO that was opened to reference
# a fixture file (i.e. the IO instance was perfectly valid at
# one point but is now closed).
def self.closed_io
io = io_fixture "lines.txt"
io.close
io
end
# Creates a pipe-based IO fixture containing the specified
# contents
def self.pipe_fixture(content)
source, sink = IO.pipe
sink.write content
sink.close
source
end
# Defines +method+ on +obj+ using the provided +block+. This
# special helper is needed for e.g. IO.open specs to avoid
# mock methods preventing IO#close from running.
def self.io_mock(obj, method, &block)
obj.singleton_class.send(:define_method, method, &block)
end
module CopyStream
def self.from=(from)
@from = from
end
def self.from
@from
end
end
class CopyStreamRead
def initialize(io)
@io = io
end
def read(size, buf)
@io.read size, buf
end
def send(*args)
raise "send called"
end
end
class CopyStreamReadPartial
def initialize(io)
@io = io
end
def readpartial(size, buf)
@io.readpartial size, buf
end
def send(*args)
raise "send called"
end
end
end
| {
"pile_set_name": "Github"
} |
#****************************************************************************
#**
#** File : /cdimage/units/URB0102/URB0102_script.lua
#** Author(s): David Tomandl
#**
#** Summary : Cybran Tier 1 Air Factory Script
#**
#** Copyright © 2005 Gas Powered Games, Inc. All rights reserved.
#****************************************************************************
local CAirFactoryUnit = import('/lua/cybranunits.lua').CAirFactoryUnit
--Change by IceDreamer: Increased platform animation speed so roll-off time is the same as UEF Air Factory
URB0102 = Class(CAirFactoryUnit) {
PlatformBone = 'B01',
LandUnitBuilt = false,
UpgradeRevealArm1 = 'Arm01',
UpgradeRevealArm2 = 'Arm04',
UpgradeBuilderArm1 = 'Arm01_B02',
UpgradeBuilderArm2 = 'Arm02_B02',
--Overwrite FinishBuildThread to speed up platform lowering rate
FinishBuildThread = function(self, unitBeingBuilt, order)
self:SetBusy(true)
self:SetBlockCommandQueue(true)
local bp = self:GetBlueprint()
local bpAnim = bp.Display.AnimationFinishBuildLand
if bpAnim and EntityCategoryContains(categories.LAND, unitBeingBuilt) then
self.RollOffAnim = CreateAnimator(self):PlayAnim(bpAnim):SetRate(4) --Change: SetRate(4)
self.Trash:Add(self.RollOffAnim)
WaitTicks(1)
WaitFor(self.RollOffAnim)
end
if unitBeingBuilt and not unitBeingBuilt.Dead then
unitBeingBuilt:DetachFrom(true)
end
self:DetachAll(bp.Display.BuildAttachBone or 0)
self:DestroyBuildRotator()
if order != 'Upgrade' then
ChangeState(self, self.RollingOffState)
else
self:SetBusy(false)
self:SetBlockCommandQueue(false)
end
end,
--Overwrite PlayFxRollOffEnd to speed up platform raising rate
PlayFxRollOffEnd = function(self)
if self.RollOffAnim then
self.RollOffAnim:SetRate(-4) --Change: SetRate(-4)
WaitFor(self.RollOffAnim)
self.RollOffAnim:Destroy()
self.RollOffAnim = nil
end
end,
}
TypeClass = URB0102
| {
"pile_set_name": "Github"
} |
--
-- Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
-- under one or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information regarding copyright
-- ownership. Camunda licenses this file to you under the Apache License,
-- Version 2.0; 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.
--
-- INCREASE process def key column size https://app.camunda.com/jira/browse/CAM-4328 --
alter table ACT_RU_JOB
modify PROCESS_DEF_KEY_ NVARCHAR2(255); | {
"pile_set_name": "Github"
} |
/*
* Freeplane - mind map editor
*
* Copyright (C) 2020 Felix Natter
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.commandsearch;
import java.awt.event.ActionEvent;
import java.net.URL;
import javax.swing.AbstractAction;
import org.freeplane.core.resources.ResourceController;
import org.freeplane.core.resources.components.OptionPanel;
import org.freeplane.core.resources.components.OptionPanelBuilder;
import org.freeplane.core.resources.components.ShowPreferencesAction;
import org.freeplane.features.mode.mindmapmode.MModeController;
class ShowPreferenceItemAction extends AbstractAction {
private PreferencesItem preferencesItem;
ShowPreferenceItemAction(PreferencesItem preferencesItem) {
super("Show");
this.preferencesItem = preferencesItem;
}
public void actionPerformed(ActionEvent actionEvent) {
//System.out.format("Showing preferences item: %s\n", preferencesItem);
showPrefsDialog();
}
private void showPrefsDialog()
{
OptionPanelBuilder optionPanelBuilder = new OptionPanelBuilder();
final ResourceController resourceController = ResourceController.getResourceController();
URL preferences = resourceController.getResource("/xml/preferences.xml");
optionPanelBuilder.load(preferences);
ShowPreferencesAction showPreferencesAction = MModeController.createShowPreferencesAction(optionPanelBuilder, this.preferencesItem.key);
int uniqueId = new Long(System.currentTimeMillis()).intValue();
showPreferencesAction.actionPerformed(
new ActionEvent(this, uniqueId, OptionPanel.OPTION_PANEL_RESOURCE_PREFIX + preferencesItem.tab));
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library 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 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package swap
import (
"math/big"
"testing"
"time"
"github.com/insight-chain/inb-go/common"
)
type testInPayment struct {
received []*testPromise
autocashInterval time.Duration
autocashLimit *big.Int
}
type testPromise struct {
amount *big.Int
}
func (test *testInPayment) Receive(promise Promise) (*big.Int, error) {
p := promise.(*testPromise)
test.received = append(test.received, p)
return p.amount, nil
}
func (test *testInPayment) AutoCash(interval time.Duration, limit *big.Int) {
test.autocashInterval = interval
test.autocashLimit = limit
}
func (test *testInPayment) Cash() (string, error) { return "", nil }
func (test *testInPayment) Stop() {}
type testOutPayment struct {
deposits []*big.Int
autodepositInterval time.Duration
autodepositThreshold *big.Int
autodepositBuffer *big.Int
}
func (test *testOutPayment) Issue(amount *big.Int) (promise Promise, err error) {
return &testPromise{amount}, nil
}
func (test *testOutPayment) Deposit(amount *big.Int) (string, error) {
test.deposits = append(test.deposits, amount)
return "", nil
}
func (test *testOutPayment) AutoDeposit(interval time.Duration, threshold, buffer *big.Int) {
test.autodepositInterval = interval
test.autodepositThreshold = threshold
test.autodepositBuffer = buffer
}
func (test *testOutPayment) Stop() {}
type testProtocol struct {
drop bool
amounts []int
promises []*testPromise
}
func (test *testProtocol) Drop() {
test.drop = true
}
func (test *testProtocol) String() string {
return ""
}
func (test *testProtocol) Pay(amount int, promise Promise) {
p := promise.(*testPromise)
test.promises = append(test.promises, p)
test.amounts = append(test.amounts, amount)
}
func TestSwap(t *testing.T) {
strategy := &Strategy{
AutoCashInterval: 1 * time.Second,
AutoCashThreshold: big.NewInt(20),
AutoDepositInterval: 1 * time.Second,
AutoDepositThreshold: big.NewInt(20),
AutoDepositBuffer: big.NewInt(40),
}
local := &Params{
Profile: &Profile{
PayAt: 5,
DropAt: 10,
BuyAt: common.Big3,
SellAt: common.Big2,
},
Strategy: strategy,
}
in := &testInPayment{}
out := &testOutPayment{}
proto := &testProtocol{}
swap, _ := New(local, Payment{In: in, Out: out, Buys: true, Sells: true}, proto)
if in.autocashInterval != strategy.AutoCashInterval {
t.Fatalf("autocash interval not properly set, expect %v, got %v", strategy.AutoCashInterval, in.autocashInterval)
}
if out.autodepositInterval != strategy.AutoDepositInterval {
t.Fatalf("autodeposit interval not properly set, expect %v, got %v", strategy.AutoDepositInterval, out.autodepositInterval)
}
remote := &Profile{
PayAt: 3,
DropAt: 10,
BuyAt: common.Big2,
SellAt: common.Big3,
}
swap.SetRemote(remote)
swap.Add(9)
if proto.drop {
t.Fatalf("not expected peer to be dropped")
}
swap.Add(1)
if !proto.drop {
t.Fatalf("expected peer to be dropped")
}
if !proto.drop {
t.Fatalf("expected peer to be dropped")
}
proto.drop = false
swap.Receive(10, &testPromise{big.NewInt(20)})
if swap.balance != 0 {
t.Fatalf("expected zero balance, got %v", swap.balance)
}
if len(proto.amounts) != 0 {
t.Fatalf("expected zero balance, got %v", swap.balance)
}
swap.Add(-2)
if len(proto.amounts) > 0 {
t.Fatalf("expected no payments yet, got %v", proto.amounts)
}
swap.Add(-1)
if len(proto.amounts) != 1 {
t.Fatalf("expected one payment, got %v", len(proto.amounts))
}
if proto.amounts[0] != 3 {
t.Fatalf("expected payment for %v units, got %v", proto.amounts[0], 3)
}
exp := new(big.Int).Mul(big.NewInt(int64(proto.amounts[0])), remote.SellAt)
if proto.promises[0].amount.Cmp(exp) != 0 {
t.Fatalf("expected payment amount %v, got %v", exp, proto.promises[0].amount)
}
swap.SetParams(&Params{
Profile: &Profile{
PayAt: 5,
DropAt: 10,
BuyAt: common.Big3,
SellAt: common.Big2,
},
Strategy: &Strategy{
AutoCashInterval: 2 * time.Second,
AutoCashThreshold: big.NewInt(40),
AutoDepositInterval: 2 * time.Second,
AutoDepositThreshold: big.NewInt(40),
AutoDepositBuffer: big.NewInt(60),
},
})
}
| {
"pile_set_name": "Github"
} |
# filename: mcrouter1.mrt
# routing table for router 1 of multicast network 2
# connected to host 1,2,3 and router 2
# author: Jochen Reber
ifconfig:
# ethernet card (modelled by point-to-point link)
name: ppp0 inet_addr: 10.1.1.2 MTU: 1500 Metric: 1 POINTTOPOINT MULTICAST
name: ppp1 inet_addr: 10.1.2.1 MTU: 1500 Metric: 1 POINTTOPOINT MULTICAST
ifconfigend.
route:
10.1.1.1 10.1.1.1 255.255.255.255 H 0 ppp0
0.0.0.0 10.1.2.1 0.0.0.0 G 0 ppp1
routeend.
| {
"pile_set_name": "Github"
} |
@echo off
call ..\..\..\..\..\SetCompilerVars.bat
set file=gui
lcc.exe -O -I%PELOCK_SDK_C% %file%.c
lcclnk.exe -reloc -s -subsystem windows %file%.obj %file%.res
del *.obj
if defined PELOCK_COMPILE_ALL goto end
pause
cls
:end | {
"pile_set_name": "Github"
} |
var struct_v_s_t_g_u_i_1_1_c_view_private_1_1_view_took_focus =
[
[ "ViewTookFocus", "struct_v_s_t_g_u_i_1_1_c_view_private_1_1_view_took_focus.html#ab3bfe914b3055aa9762d6f9e5f841d65", null ],
[ "operator()", "struct_v_s_t_g_u_i_1_1_c_view_private_1_1_view_took_focus.html#ac89881bc32608e116258fcfe8bd16e34", null ]
]; | {
"pile_set_name": "Github"
} |
// @ts-nocheck
'use strict';
const _ = require('lodash');
const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule');
const parseSelector = require('../../utils/parseSelector');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const styleSearch = require('style-search');
const validateOptions = require('../../utils/validateOptions');
const ruleName = 'selector-attribute-brackets-space-inside';
const messages = ruleMessages(ruleName, {
expectedOpening: 'Expected single space after "["',
rejectedOpening: 'Unexpected whitespace after "["',
expectedClosing: 'Expected single space before "]"',
rejectedClosing: 'Unexpected whitespace before "]"',
});
function rule(expectation, options, context) {
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: expectation,
possible: ['always', 'never'],
});
if (!validOptions) {
return;
}
root.walkRules((rule) => {
if (!isStandardSyntaxRule(rule)) {
return;
}
if (!rule.selector.includes('[')) {
return;
}
const selector = rule.raws.selector ? rule.raws.selector.raw : rule.selector;
let hasFixed;
const fixedSelector = parseSelector(selector, result, rule, (selectorTree) => {
selectorTree.walkAttributes((attributeNode) => {
const attributeSelectorString = attributeNode.toString();
styleSearch({ source: attributeSelectorString, target: '[' }, (match) => {
const nextCharIsSpace = attributeSelectorString[match.startIndex + 1] === ' ';
const index = attributeNode.sourceIndex + match.startIndex + 1;
if (nextCharIsSpace && expectation === 'never') {
if (context.fix) {
hasFixed = true;
fixBefore(attributeNode);
return;
}
complain(messages.rejectedOpening, index);
}
if (!nextCharIsSpace && expectation === 'always') {
if (context.fix) {
hasFixed = true;
fixBefore(attributeNode);
return;
}
complain(messages.expectedOpening, index);
}
});
styleSearch({ source: attributeSelectorString, target: ']' }, (match) => {
const prevCharIsSpace = attributeSelectorString[match.startIndex - 1] === ' ';
const index = attributeNode.sourceIndex + match.startIndex - 1;
if (prevCharIsSpace && expectation === 'never') {
if (context.fix) {
hasFixed = true;
fixAfter(attributeNode);
return;
}
complain(messages.rejectedClosing, index);
}
if (!prevCharIsSpace && expectation === 'always') {
if (context.fix) {
hasFixed = true;
fixAfter(attributeNode);
return;
}
complain(messages.expectedClosing, index);
}
});
});
});
if (hasFixed) {
if (!rule.raws.selector) {
rule.selector = fixedSelector;
} else {
rule.raws.selector.raw = fixedSelector;
}
}
function complain(message, index) {
report({
message,
index,
result,
ruleName,
node: rule,
});
}
});
};
function fixBefore(attributeNode) {
const rawAttrBefore = _.get(attributeNode, 'raws.spaces.attribute.before');
const { attrBefore, setAttrBefore } = rawAttrBefore
? {
attrBefore: rawAttrBefore,
setAttrBefore(fixed) {
attributeNode.raws.spaces.attribute.before = fixed;
},
}
: {
attrBefore: _.get(attributeNode, 'spaces.attribute.before', ''),
setAttrBefore(fixed) {
_.set(attributeNode, 'spaces.attribute.before', fixed);
},
};
if (expectation === 'always') {
setAttrBefore(attrBefore.replace(/^\s*/, ' '));
} else if (expectation === 'never') {
setAttrBefore(attrBefore.replace(/^\s*/, ''));
}
}
function fixAfter(attributeNode) {
let key;
if (attributeNode.operator) {
if (attributeNode.insensitive) {
key = 'insensitive';
} else {
key = 'value';
}
} else {
key = 'attribute';
}
const rawAfter = _.get(attributeNode, `raws.spaces.${key}.after`);
const { after, setAfter } = rawAfter
? {
after: rawAfter,
setAfter(fixed) {
attributeNode.raws.spaces[key].after = fixed;
},
}
: {
after: _.get(attributeNode, `spaces.${key}.after`, ''),
setAfter(fixed) {
_.set(attributeNode, `spaces.${key}.after`, fixed);
},
};
if (expectation === 'always') {
setAfter(after.replace(/\s*$/, ' '));
} else if (expectation === 'never') {
setAfter(after.replace(/\s*$/, ''));
}
}
}
rule.ruleName = ruleName;
rule.messages = messages;
module.exports = rule;
| {
"pile_set_name": "Github"
} |
-- between.test
--
-- execsql {INSERT INTO t1 VALUES(w,x,y,z)}
INSERT INTO t1 VALUES(w,x,y,z)
| {
"pile_set_name": "Github"
} |
#ifndef MuonGEMDetLayerGeometryBuilder_h
#define MuonGEMDetLayerGeometryBuilder_h
/** \class MuonGEMDetLayerGeometryBuilder
*
* Build the GEM DetLayers.
*
* \author R. Radogna
*/
class DetLayer;
class MuRingForwardDoubleLayer;
class MuDetRing;
#include <Geometry/GEMGeometry/interface/GEMGeometry.h>
#include "RecoMuon/DetLayers/interface/MuDetRod.h"
#include <vector>
class MuonGEMDetLayerGeometryBuilder {
public:
/// Constructor (disabled, only static access is allowed)
MuonGEMDetLayerGeometryBuilder() {}
/// Destructor
virtual ~MuonGEMDetLayerGeometryBuilder();
/// Builds the forward (+Z, return.first) and backward (-Z, return.second) layers.
/// Both vectors are sorted inside-out
static std::pair<std::vector<DetLayer*>, std::vector<DetLayer*> > buildEndcapLayers(const GEMGeometry& geo);
private:
static MuRingForwardDoubleLayer* buildLayer(int endcap,
std::vector<int>& rings,
int station,
int layer,
std::vector<int>& chambers,
std::vector<int>& rolls,
const GEMGeometry& geo);
static bool isFront(const GEMDetId& gemId);
static MuDetRing* makeDetRing(std::vector<const GeomDet*>& geomDets);
};
#endif
| {
"pile_set_name": "Github"
} |
package android.app;
import android.graphics.Bitmap;
import android.graphics.Rect;
public abstract class AbsWallpaperManagerInner {
public interface IBlurWallpaperCallback {
void onBlurWallpaperChanged();
}
public Bitmap getBlurBitmap(Rect rect) {
return null;
}
public void setCallback(IBlurWallpaperCallback callback) {
}
}
| {
"pile_set_name": "Github"
} |
/**
* Polish translation for bootstrap-datepicker
* Robert <[email protected]>
*/
;(function($){
$.fn.datepicker.dates['pl'] = {
days: ["Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela"],
daysShort: ["Nie", "Pn", "Wt", "Śr", "Czw", "Pt", "So", "Nie"],
daysMin: ["N", "Pn", "Wt", "Śr", "Cz", "Pt", "So", "N"],
months: ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"],
monthsShort: ["Sty", "Lu", "Mar", "Kw", "Maj", "Cze", "Lip", "Sie", "Wrz", "Pa", "Lis", "Gru"],
today: "Dzisiaj",
weekStart: 1
};
}(jQuery));
| {
"pile_set_name": "Github"
} |
package com.snowalker;
import com.snowalker.lock.redisson.config.EnableRedissonLock;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableRedissonLock
@EnableScheduling
@SpringBootApplication
public class RedisDistributedLockStarterDemoApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(RedisDistributedLockStarterDemoApplication.class, args);
}
}
| {
"pile_set_name": "Github"
} |
// Copyright (C) 2005 Arkadiy Vertleyb, Peder Holt.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_TYPEOF_STD_istream_hpp_INCLUDED
#define BOOST_TYPEOF_STD_istream_hpp_INCLUDED
#include <istream>
#include <boost/typeof/typeof.hpp>
#include <boost/typeof/std/string.hpp>
#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
BOOST_TYPEOF_REGISTER_TEMPLATE(std::basic_istream, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(std::basic_istream, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(std::basic_iostream, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(std::basic_iostream, 2)
BOOST_TYPEOF_REGISTER_TYPE(std::istream)
BOOST_TYPEOF_REGISTER_TYPE(std::iostream)
#endif//BOOST_TYPEOF_STD_istream_hpp_INCLUDED
| {
"pile_set_name": "Github"
} |
/**
* \brief Errno definitions
* \author Sebastian Sumpf
* \date 2017-08-24
*/
/*
* Copyright (C) 2017 Genode Labs GmbH
*
* This file is part of the Genode OS framework, which is distributed
* under the terms of the GNU Affero General Public License version 3.
*/
#ifndef _ERRNO_H_
#define _ERRNO_H_
enum {
ENOSYS = 38,
};
#endif /* _ERRNO_H_ */
| {
"pile_set_name": "Github"
} |
#======================================================================
#
# Trigger Tests
# test cases for TRIGGER privilege on db, table and column level
#======================================================================
--disable_abort_on_error
#########################################################
################ Section 3.5.3 ##########################
# Check for column privileges of Triggers #
#########################################################
# General setup to be used in all testcases
let $message= ####### Testcase for column privileges of triggers: #######;
--source include/show_msg.inc
--disable_warnings
drop database if exists priv_db;
drop database if exists no_priv_db;
--enable_warnings
create database priv_db;
use priv_db;
eval create table t1 (f1 char(20)) engine= $engine_type;
eval create table t2 (f1 char(20)) engine= $engine_type;
create User test_yesprivs@localhost;
set password for test_yesprivs@localhost = password('PWD');
revoke ALL PRIVILEGES, GRANT OPTION FROM test_yesprivs@localhost;
grant TRIGGER on priv_db.* to test_yesprivs@localhost;
show grants for test_yesprivs@localhost;
create User test_noprivs@localhost;
set password for test_noprivs@localhost = password('PWD');
revoke ALL PRIVILEGES, GRANT OPTION FROM test_noprivs@localhost;
grant SELECT,UPDATE on priv_db.* to test_noprivs@localhost;
show grants for test_noprivs@localhost;
connect (yes_privs,localhost,test_yesprivs,PWD,test,$MASTER_MYPORT,$MASTER_MYSOCK);
connect (no_privs,localhost,test_noprivs,PWD,test,$MASTER_MYPORT,$MASTER_MYSOCK);
# grant TRIGGER and UPDATE on column -> succeed
let $message= update only on column:;
--source include/show_msg.inc
connection default;
select current_user;
grant SELECT(f1),INSERT,UPDATE(f1) on priv_db.t1
to test_yesprivs@localhost;
grant SELECT(f1),INSERT,UPDATE(f1) on priv_db.t2
to test_yesprivs@localhost;
connection yes_privs;
select current_user;
use priv_db;
insert into t1 (f1) values ('insert1-yes');
insert into t2 (f1) values ('insert1-yes');
create trigger trg1_1 before UPDATE on t1 for each row
set new.f1 = 'trig 1_1-yes';
create trigger trg2_1 before UPDATE on t2 for each row
set new.f1 = 'trig 2_1-yes';
connection no_privs;
select current_user;
use priv_db;
select f1 from t1 order by f1;
update t1 set f1 = 'update1_no'
where f1 like '%insert%';
select f1 from t1 order by f1;
select f1 from t2 order by f1;
update t2 set f1 = 'update1_no'
where f1 like '%insert%';
select f1 from t2 order by f1;
connection default;
select current_user;
revoke UPDATE on priv_db.*
from test_yesprivs@localhost;
revoke UPDATE(f1) on priv_db.t2
from test_yesprivs@localhost;
show grants for test_yesprivs@localhost;
connection yes_privs;
select current_user;
use priv_db;
insert into t1 (f1) values ('insert2-yes');
insert into t2 (f1) values ('insert2-yes');
connection no_privs;
select current_user;
use priv_db;
update t1 set f1 = 'update2_no'
where f1 like '%insert%';
--error ER_COLUMNACCESS_DENIED_ERROR
update t2 set f1 = 'update2_no'
where f1 like '%insert%';
update t1 set f1 = 'update3_no'
where f1 like '%insert%';
--error ER_COLUMNACCESS_DENIED_ERROR
update t2 set f1 = 'update3_no'
where f1 like '%insert%';
select f1 from t1 order by f1;
select f1 from t2 order by f1;
# check with three columns
let $message= check if access only on one of three columns;
--source include/show_msg.inc
connection default;
select current_user;
alter table priv_db.t1 add f2 char(20), add f3 int;
revoke TRIGGER on priv_db.* from test_yesprivs@localhost;
grant TRIGGER,SELECT on priv_db.t1 to test_yesprivs@localhost;
grant UPDATE on priv_db.t2 to test_yesprivs@localhost;
connection yes_privs;
select current_user;
use priv_db;
insert into t1 values ('insert2-yes','insert2-yes',1);
insert into t1 values ('insert3-yes','insert3-yes',2);
select * from t1 order by f1;
connection no_privs;
select current_user;
use priv_db;
update t1 set f1 = 'update4-no',
f2 = 'update4-yes',
f3 = f3*10
where f2 like '%yes';
select * from t1 order by f1,f2,f3;
connection yes_privs;
select current_user;
create trigger trg1_2 after UPDATE on t1 for each row
set @f2 = 'trig 1_2-yes';
connection no_privs;
select current_user;
update t1 set f1 = 'update5-yes',
f2 = 'update5-yes'
where f2 like '%yes';
select * from t1 order by f1,f2,f3;
select @f2;
update t1 set f1 = 'update6_no'
where f1 like '%insert%';
--error ER_TABLEACCESS_DENIED_ERROR
update t2 set f1 = 'update6_no'
where f1 like '%insert%';
update t1 set f1 = 'update7_no'
where f1 like '%insert%';
--error ER_TABLEACCESS_DENIED_ERROR
update t2 set f1 = 'update7_no'
where f1 like '%insert%';
select f1 from t1 order by f1;
select f1 from t2 order by f1;
# check with three columns
# check if update is rejected without trigger privilege
let $message= check if rejected without trigger privilege:;
--source include/show_msg.inc
connection default;
select current_user;
revoke TRIGGER on priv_db.t1 from test_yesprivs@localhost;
connection no_privs;
select current_user;
--error ER_TABLEACCESS_DENIED_ERROR
update t1 set f1 = 'update8-no',
f2 = 'update8-no'
where f2 like '%yes';
select * from t1 order by f1,f2,f3;
select @f2;
# check trigger, but not update privilege on column
let $message= check trigger, but not update privilege on column:;
--source include/show_msg.inc
connection default;
select current_user;
revoke UPDATE(f1) on priv_db.t1 from test_yesprivs@localhost;
grant TRIGGER,UPDATE(f2),UPDATE(f3) on priv_db.t1
to test_yesprivs@localhost;
show grants for test_yesprivs@localhost;
connection yes_privs;
select current_user;
use priv_db;
drop trigger trg1_1;
create trigger trg1_3 before UPDATE on t1 for each row
set new.f1 = 'trig 1_3-yes';
connection no_privs;
select current_user;
use priv_db;
--error ER_COLUMNACCESS_DENIED_ERROR
update t1 set f1 = 'update9-no',
f2 = 'update9-no'
where f2 like '%yes';
select * from t1 order by f1,f2,f3;
# trigger is involved (table privilege) ->fail
--error ER_COLUMNACCESS_DENIED_ERROR
update t1 set f3= f3+1;
select f3 from t1 order by f3;
connection default;
select current_user;
revoke TRIGGER on priv_db.t1 from test_yesprivs@localhost;
grant UPDATE(f1),UPDATE(f2),UPDATE(f3) on priv_db.t1
to test_yesprivs@localhost;
show grants for test_yesprivs@localhost;
# trigger is involved (table privilege) ->fail
connection no_privs;
select current_user;
use priv_db;
--error ER_TABLEACCESS_DENIED_ERROR
update t1 set f3= f3+1;
select f3 from t1 order by f3;
let $message= ##### trigger privilege on column level? #######;
--source include/show_msg.inc
--error ER_PARSE_ERROR
grant TRIGGER(f1) on priv_db.t1 to test_yesprivs@localhost;
# Cleanup table level
--disable_warnings
disconnect yes_privs;
disconnect no_privs;
connection default;
select current_user;
# general Cleanup
drop database if exists priv_db;
drop user test_yesprivs@localhost;
drop user test_noprivs@localhost;
--enable_warnings
| {
"pile_set_name": "Github"
} |
---
layout: base
title: 'Statistics of goeswith in UD_Estonian-EWT'
udver: '2'
---
## Treebank Statistics: UD_Estonian-EWT: Relations: `goeswith`
This relation is universal.
9 nodes (0%) are attached to their parents as `goeswith`.
9 instances of `goeswith` (100%) are left-to-right (parent precedes child).
Average distance between parent and child is 1.
The following 7 pairs of parts of speech are connected with `goeswith`: <tt><a href="et_ewt-pos-NOUN.html">NOUN</a></tt>-<tt><a href="et_ewt-pos-NOUN.html">NOUN</a></tt> (3; 33% instances), <tt><a href="et_ewt-pos-ADV.html">ADV</a></tt>-<tt><a href="et_ewt-pos-ADV.html">ADV</a></tt> (1; 11% instances), <tt><a href="et_ewt-pos-ADV.html">ADV</a></tt>-<tt><a href="et_ewt-pos-VERB.html">VERB</a></tt> (1; 11% instances), <tt><a href="et_ewt-pos-NOUN.html">NOUN</a></tt>-<tt><a href="et_ewt-pos-ADJ.html">ADJ</a></tt> (1; 11% instances), <tt><a href="et_ewt-pos-NUM.html">NUM</a></tt>-<tt><a href="et_ewt-pos-ADJ.html">ADJ</a></tt> (1; 11% instances), <tt><a href="et_ewt-pos-PRON.html">PRON</a></tt>-<tt><a href="et_ewt-pos-ADV.html">ADV</a></tt> (1; 11% instances), <tt><a href="et_ewt-pos-X.html">X</a></tt>-<tt><a href="et_ewt-pos-X.html">X</a></tt> (1; 11% instances).
~~~ conllu
# visual-style 17 bgColor:blue
# visual-style 17 fgColor:white
# visual-style 16 bgColor:blue
# visual-style 16 fgColor:white
# visual-style 16 17 goeswith color:blue
1 Meie mina PRON P Case=Gen|Number=Plur|Person=1|PronType=Prs 2 nmod 2:nmod _
2 mõistus mõistus NOUN S Case=Nom|Number=Sing 4 nsubj 4:nsubj _
3 ei ei AUX V Polarity=Neg 4 aux 4:aux _
4 taha tahtma VERB V Connegative=Yes|Mood=Ind|Tense=Pres|VerbForm=Fin|Voice=Act 0 root 0:root _
5 alati alati ADV D _ 4 advmod 4:advmod _
6 tunnistada tunnistama VERB V VerbForm=Inf 4 xcomp 4:xcomp SpaceAfter=No
7 , , PUNCT Z _ 10 punct 10:punct _
8 et et SCONJ J _ 10 mark 10:mark _
9 tasakaalustavaks tasa_kaalustav ADJ A Case=Tra|Degree=Pos|Number=Sing|Tense=Pres|VerbForm=Part|Voice=Act 10 acl 10:acl _
10 pooleks pool NOUN S Case=Tra|Number=Sing 6 ccomp 6:ccomp _
11 võib võima AUX V Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin|Voice=Act 10 aux 10:aux _
12 vahel vahel ADV D _ 10 advmod 10:advmod _
13 olla olema AUX V VerbForm=Inf 10 cop 10:cop _
14 ka ka ADV D _ 10 advmod 10:advmod _
15 Meie mina PRON P Case=Gen|Number=Plur|Person=1|PronType=Prs 16 nmod 16:nmod _
16 Inim inim NOUN S _ 18 obl 18:obl _
17 mõistusele mõistus NOUN S Case=All|Number=Sing 16 goeswith 16:goeswith _
18 negatiivne negatiivne ADJ A Case=Nom|Degree=Pos|Number=Sing 19 amod 19:amod _
19 varjund varjund NOUN S Case=Nom|Number=Sing 10 nsubj:cop 10:nsubj SpaceAfter=No
20 . . PUNCT Z _ 4 punct 4:punct _
~~~
~~~ conllu
# visual-style 3 bgColor:blue
# visual-style 3 fgColor:white
# visual-style 2 bgColor:blue
# visual-style 2 fgColor:white
# visual-style 2 3 goeswith color:blue
1 Ma mina PRON P Case=Nom|Number=Sing|Person=1|PronType=Prs 4 nsubj 4:nsubj _
2 üle üle ADV D _ 4 advmod 4:advmod _
3 homme homme ADV D _ 2 goeswith 2:goeswith _
4 näen nägema VERB V Mood=Ind|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin|Voice=Act 0 root 0:root _
5 teda tema PRON P Case=Par|Number=Sing|Person=3|PronType=Prs 4 obj 4:obj SpaceAfter=No
6 , , PUNCT Z _ 8 punct 8:punct _
7 siis siis ADV D _ 8 advmod 8:advmod _
8 räägin rääkima VERB V Mood=Ind|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin|Voice=Act 4 conj 4:conj _
9 temaga tema PRON P Case=Com|Number=Sing|Person=3|PronType=Prs 8 obl 8:obl SpaceAfter=No
10 . . PUNCT Z _ 4 punct 4:punct _
~~~
~~~ conllu
# visual-style 13 bgColor:blue
# visual-style 13 fgColor:white
# visual-style 12 bgColor:blue
# visual-style 12 fgColor:white
# visual-style 12 13 goeswith color:blue
1 Teise teine DET P Case=Gen|Number=Sing|PronType=Dem 2 det 2:det _
2 inimese inimene NOUN S Case=Gen|Number=Sing 4 nmod 4:nmod _
3 eest eest ADP K AdpType=Post 2 case 2:case _
4 maksmine maksmine NOUN S Case=Nom|Number=Sing 25 nsubj:cop 25:nsubj SpaceAfter=No
5 , , PUNCT Z _ 21 punct 21:punct _
6 kes kes PRON P Case=Nom|Number=Sing|PronType=Int,Rel 21 nsubj 21:nsubj _
7 sinu sina PRON P Case=Gen|Number=Sing|Person=2|PronType=Prs 8 nmod 8:nmod _
8 elus elu NOUN S Case=Ine|Number=Sing 19 obl 19:obl _
9 ( ( PUNCT Z _ 10 punct 10:punct SpaceAfter=No
10 veel veel ADV D _ 19 parataxis 19:parataxis _
11 ja ja CCONJ J _ 15 cc 15:cc _
12 võib võima ADV D _ 15 advmod 15:advmod _
13 olla olema VERB V VerbForm=Inf 12 goeswith 12:goeswith _
14 mitte mitte ADV D Polarity=Neg 15 advmod 15:advmod _
15 kunagi kunagi ADV D _ 10 conj 10:conj SpaceAfter=No
16 ) ) PUNCT Z _ 10 punct 10:punct _
17 mingit mingi DET P Case=Par|Number=Sing|PronType=Ind 18 det 18:det _
18 rolli roll NOUN S Case=Par|Number=Sing 19 obj 19:obj _
19 mängima mängima VERB V Case=Ill|VerbForm=Sup|Voice=Act 21 xcomp 21:xcomp _
20 ei ei AUX V Polarity=Neg 21 aux 21:aux _
21 hakka hakkama VERB V Connegative=Yes|Mood=Ind|Tense=Pres|VerbForm=Fin|Voice=Act 4 acl:relcl 4:acl _
22 peaks pidama AUX V Mood=Cnd|Number=Sing|Tense=Pres|VerbForm=Fin|Voice=Act 25 aux 25:aux _
23 ju ju ADV D _ 25 advmod 25:advmod _
24 pisut pisut ADV D _ 25 advmod 25:advmod _
25 alandav alandav ADJ A Case=Nom|Degree=Pos|Number=Sing|Tense=Pres|VerbForm=Part|Voice=Act 0 root 0:root _
26 olema olema AUX V Case=Ill|VerbForm=Sup|Voice=Act 25 cop 25:cop SpaceAfter=No
27 ? ? PUNCT Z _ 25 punct 25:punct _
~~~
| {
"pile_set_name": "Github"
} |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- ~ COORDINATES ~ -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<artifactId>ff4j-store-commonsconfig</artifactId>
<packaging>jar</packaging>
<name>ff4j-store-commonsconfig</name>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- ~ PARENT ~ -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<parent>
<groupId>org.ff4j</groupId>
<artifactId>ff4j-parent</artifactId>
<version>1.8.10-SNAPSHOT</version>
</parent>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- ~ PROPERTIES ~ -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<properties>
<license.licenseResolver>${project.baseUri}/../src/license</license.licenseResolver>
<commonsconfig.version>1.10</commonsconfig.version>
</properties>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- ~ DEPENDENCIES ~ -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<dependencies>
<!-- logger -->
<dependency>
<groupId>org.ff4j</groupId>
<artifactId>ff4j-core</artifactId>
<version>${project.version}</version>
</dependency>
<!-- CommonsConfig -->
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>${commonsconfig.version}</version>
</dependency>
<!-- Tests -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.ff4j</groupId>
<artifactId>ff4j-test</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {
"pile_set_name": "Github"
} |
//
// arduino-serial-lib -- simple library for reading/writing serial ports
//
// 2006-2013, Tod E. Kurt, http://todbot.com/blog/
//
#include "arduino-serial-lib.h"
#include <stdio.h> // Standard input/output definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h> // POSIX terminal control definitions
#include <string.h> // String function definitions
#include <sys/ioctl.h>
// uncomment this to debug reads
//#define SERIALPORTDEBUG
// takes the string name of the serial port (e.g. "/dev/tty.usbserial","COM1")
// and a baud rate (bps) and connects to that port at that speed and 8N1.
// opens the port in fully raw mode so you can send binary data.
// returns valid fd, or -1 on error
int serialport_init(const char* serialport, int baud)
{
struct termios toptions;
int fd;
//fd = open(serialport, O_RDWR | O_NOCTTY | O_NDELAY);
fd = open(serialport, O_RDWR | O_NONBLOCK );
if (fd == -1) {
perror("serialport_init: Unable to open port ");
return -1;
}
//int iflags = TIOCM_DTR;
//ioctl(fd, TIOCMBIS, &iflags); // turn on DTR
//ioctl(fd, TIOCMBIC, &iflags); // turn off DTR
if (tcgetattr(fd, &toptions) < 0) {
perror("serialport_init: Couldn't get term attributes");
return -1;
}
speed_t brate = baud; // let you override switch below if needed
switch(baud) {
case 4800: brate=B4800; break;
case 9600: brate=B9600; break;
#ifdef B14400
case 14400: brate=B14400; break;
#endif
case 19200: brate=B19200; break;
#ifdef B28800
case 28800: brate=B28800; break;
#endif
case 38400: brate=B38400; break;
case 57600: brate=B57600; break;
case 115200: brate=B115200; break;
}
cfsetispeed(&toptions, brate);
cfsetospeed(&toptions, brate);
// 8N1
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
// no flow control
toptions.c_cflag &= ~CRTSCTS;
//toptions.c_cflag &= ~HUPCL; // disable hang-up-on-close to avoid reset
toptions.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
toptions.c_oflag &= ~OPOST; // make raw
// see: http://unixwiz.net/techtips/termios-vmin-vtime.html
toptions.c_cc[VMIN] = 0;
toptions.c_cc[VTIME] = 0;
//toptions.c_cc[VTIME] = 20;
tcsetattr(fd, TCSANOW, &toptions);
if( tcsetattr(fd, TCSAFLUSH, &toptions) < 0) {
perror("init_serialport: Couldn't set term attributes");
return -1;
}
return fd;
}
//
int serialport_close( int fd )
{
return close( fd );
}
//
int serialport_writebyte( int fd, uint8_t b)
{
int n = write(fd,&b,1);
if( n!=1)
return -1;
return 0;
}
//
int serialport_write(int fd, const char* str)
{
int len = strlen(str);
int n = write(fd, str, len);
if( n!=len ) {
perror("serialport_write: couldn't write whole string\n");
return -1;
}
return 0;
}
//
int serialport_read_until(int fd, char* buf, char until, int buf_max, int timeout)
{
char b[1]; // read expects an array, so we give it a 1-byte array
int i=0;
do {
int n = read(fd, b, 1); // read a char at a time
if( n==-1) return -1; // couldn't read
if( n==0 ) {
usleep( 1 * 1000 ); // wait 1 msec try again
timeout--;
if( timeout==0 ) return -2;
continue;
}
#ifdef SERIALPORTDEBUG
printf("serialport_read_until: i=%d, n=%d b='%c'\n",i,n,b[0]); // debug
#endif
buf[i] = b[0];
i++;
} while( b[0] != until && i < buf_max && timeout>0 );
buf[i] = 0; // null terminate the string
return 0;
}
//
int serialport_flush(int fd)
{
sleep(2); //required to make flush work, for some reason
return tcflush(fd, TCIOFLUSH);
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.